1 /*
   2  * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "code/codeCache.hpp"
  27 #include "code/icBuffer.hpp"
  28 #include "gc_implementation/g1/bufferingOopClosure.hpp"
  29 #include "gc_implementation/g1/concurrentG1Refine.hpp"
  30 #include "gc_implementation/g1/concurrentG1RefineThread.hpp"
  31 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
  32 #include "gc_implementation/g1/g1AllocRegion.inline.hpp"
  33 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  34 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
  35 #include "gc_implementation/g1/g1ErgoVerbose.hpp"
  36 #include "gc_implementation/g1/g1EvacFailure.hpp"
  37 #include "gc_implementation/g1/g1GCPhaseTimes.hpp"
  38 #include "gc_implementation/g1/g1Log.hpp"
  39 #include "gc_implementation/g1/g1MarkSweep.hpp"
  40 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
  41 #include "gc_implementation/g1/g1RemSet.inline.hpp"
  42 #include "gc_implementation/g1/g1YCTypes.hpp"
  43 #include "gc_implementation/g1/heapRegion.inline.hpp"
  44 #include "gc_implementation/g1/heapRegionRemSet.hpp"
  45 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
  46 #include "gc_implementation/g1/vm_operations_g1.hpp"
  47 #include "gc_implementation/shared/gcHeapSummary.hpp"
  48 #include "gc_implementation/shared/gcTimer.hpp"
  49 #include "gc_implementation/shared/gcTrace.hpp"
  50 #include "gc_implementation/shared/gcTraceTime.hpp"
  51 #include "gc_implementation/shared/isGCActiveMark.hpp"
  52 #include "memory/gcLocker.inline.hpp"
  53 #include "memory/genOopClosures.inline.hpp"
  54 #include "memory/generationSpec.hpp"
  55 #include "memory/referenceProcessor.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "oops/oop.pcgc.inline.hpp"
  58 #include "runtime/aprofiler.hpp"
  59 #include "runtime/vmThread.hpp"
  60 #include "utilities/ticks.hpp"
  61 
  62 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
  63 
  64 // turn it on so that the contents of the young list (scan-only /
  65 // to-be-collected) are printed at "strategic" points before / during
  66 // / after the collection --- this is useful for debugging
  67 #define YOUNG_LIST_VERBOSE 0
  68 // CURRENT STATUS
  69 // This file is under construction.  Search for "FIXME".
  70 
  71 // INVARIANTS/NOTES
  72 //
  73 // All allocation activity covered by the G1CollectedHeap interface is
  74 // serialized by acquiring the HeapLock.  This happens in mem_allocate
  75 // and allocate_new_tlab, which are the "entry" points to the
  76 // allocation code from the rest of the JVM.  (Note that this does not
  77 // apply to TLAB allocation, which is not part of this interface: it
  78 // is done by clients of this interface.)
  79 
  80 // Notes on implementation of parallelism in different tasks.
  81 //
  82 // G1ParVerifyTask uses heap_region_par_iterate_chunked() for parallelism.
  83 // The number of GC workers is passed to heap_region_par_iterate_chunked().
  84 // It does use run_task() which sets _n_workers in the task.
  85 // G1ParTask executes g1_process_strong_roots() ->
  86 // SharedHeap::process_strong_roots() which calls eventually to
  87 // CardTableModRefBS::par_non_clean_card_iterate_work() which uses
  88 // SequentialSubTasksDone.  SharedHeap::process_strong_roots() also
  89 // directly uses SubTasksDone (_process_strong_tasks field in SharedHeap).
  90 //
  91 
  92 // Local to this file.
  93 
  94 class RefineCardTableEntryClosure: public CardTableEntryClosure {
  95   SuspendibleThreadSet* _sts;
  96   G1RemSet* _g1rs;
  97   ConcurrentG1Refine* _cg1r;
  98   bool _concurrent;
  99 public:
 100   RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
 101                               G1RemSet* g1rs,
 102                               ConcurrentG1Refine* cg1r) :
 103     _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
 104   {}
 105   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
 106     bool oops_into_cset = _g1rs->refine_card(card_ptr, worker_i, false);
 107     // This path is executed by the concurrent refine or mutator threads,
 108     // concurrently, and so we do not care if card_ptr contains references
 109     // that point into the collection set.
 110     assert(!oops_into_cset, "should be");
 111 
 112     if (_concurrent && _sts->should_yield()) {
 113       // Caller will actually yield.
 114       return false;
 115     }
 116     // Otherwise, we finished successfully; return true.
 117     return true;
 118   }
 119   void set_concurrent(bool b) { _concurrent = b; }
 120 };
 121 
 122 
 123 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
 124   int _calls;
 125   G1CollectedHeap* _g1h;
 126   CardTableModRefBS* _ctbs;
 127   int _histo[256];
 128 public:
 129   ClearLoggedCardTableEntryClosure() :
 130     _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set())
 131   {
 132     for (int i = 0; i < 256; i++) _histo[i] = 0;
 133   }
 134   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
 135     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
 136       _calls++;
 137       unsigned char* ujb = (unsigned char*)card_ptr;
 138       int ind = (int)(*ujb);
 139       _histo[ind]++;
 140       *card_ptr = -1;
 141     }
 142     return true;
 143   }
 144   int calls() { return _calls; }
 145   void print_histo() {
 146     gclog_or_tty->print_cr("Card table value histogram:");
 147     for (int i = 0; i < 256; i++) {
 148       if (_histo[i] != 0) {
 149         gclog_or_tty->print_cr("  %d: %d", i, _histo[i]);
 150       }
 151     }
 152   }
 153 };
 154 
 155 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
 156   int _calls;
 157   G1CollectedHeap* _g1h;
 158   CardTableModRefBS* _ctbs;
 159 public:
 160   RedirtyLoggedCardTableEntryClosure() :
 161     _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set()) {}
 162 
 163   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
 164     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
 165       _calls++;
 166       *card_ptr = 0;
 167     }
 168     return true;
 169   }
 170   int calls() { return _calls; }
 171 };
 172 
 173 class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
 174 public:
 175   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
 176     *card_ptr = CardTableModRefBS::dirty_card_val();
 177     return true;
 178   }
 179 };
 180 
 181 YoungList::YoungList(G1CollectedHeap* g1h) :
 182     _g1h(g1h), _head(NULL), _length(0), _last_sampled_rs_lengths(0),
 183     _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0) {
 184   guarantee(check_list_empty(false), "just making sure...");
 185 }
 186 
 187 void YoungList::push_region(HeapRegion *hr) {
 188   assert(!hr->is_young(), "should not already be young");
 189   assert(hr->get_next_young_region() == NULL, "cause it should!");
 190 
 191   hr->set_next_young_region(_head);
 192   _head = hr;
 193 
 194   _g1h->g1_policy()->set_region_eden(hr, (int) _length);
 195   ++_length;
 196 }
 197 
 198 void YoungList::add_survivor_region(HeapRegion* hr) {
 199   assert(hr->is_survivor(), "should be flagged as survivor region");
 200   assert(hr->get_next_young_region() == NULL, "cause it should!");
 201 
 202   hr->set_next_young_region(_survivor_head);
 203   if (_survivor_head == NULL) {
 204     _survivor_tail = hr;
 205   }
 206   _survivor_head = hr;
 207   ++_survivor_length;
 208 }
 209 
 210 void YoungList::empty_list(HeapRegion* list) {
 211   while (list != NULL) {
 212     HeapRegion* next = list->get_next_young_region();
 213     list->set_next_young_region(NULL);
 214     list->uninstall_surv_rate_group();
 215     list->set_not_young();
 216     list = next;
 217   }
 218 }
 219 
 220 void YoungList::empty_list() {
 221   assert(check_list_well_formed(), "young list should be well formed");
 222 
 223   empty_list(_head);
 224   _head = NULL;
 225   _length = 0;
 226 
 227   empty_list(_survivor_head);
 228   _survivor_head = NULL;
 229   _survivor_tail = NULL;
 230   _survivor_length = 0;
 231 
 232   _last_sampled_rs_lengths = 0;
 233 
 234   assert(check_list_empty(false), "just making sure...");
 235 }
 236 
 237 bool YoungList::check_list_well_formed() {
 238   bool ret = true;
 239 
 240   uint length = 0;
 241   HeapRegion* curr = _head;
 242   HeapRegion* last = NULL;
 243   while (curr != NULL) {
 244     if (!curr->is_young()) {
 245       gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
 246                              "incorrectly tagged (y: %d, surv: %d)",
 247                              curr->bottom(), curr->end(),
 248                              curr->is_young(), curr->is_survivor());
 249       ret = false;
 250     }
 251     ++length;
 252     last = curr;
 253     curr = curr->get_next_young_region();
 254   }
 255   ret = ret && (length == _length);
 256 
 257   if (!ret) {
 258     gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
 259     gclog_or_tty->print_cr("###   list has %u entries, _length is %u",
 260                            length, _length);
 261   }
 262 
 263   return ret;
 264 }
 265 
 266 bool YoungList::check_list_empty(bool check_sample) {
 267   bool ret = true;
 268 
 269   if (_length != 0) {
 270     gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %u",
 271                   _length);
 272     ret = false;
 273   }
 274   if (check_sample && _last_sampled_rs_lengths != 0) {
 275     gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
 276     ret = false;
 277   }
 278   if (_head != NULL) {
 279     gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
 280     ret = false;
 281   }
 282   if (!ret) {
 283     gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
 284   }
 285 
 286   return ret;
 287 }
 288 
 289 void
 290 YoungList::rs_length_sampling_init() {
 291   _sampled_rs_lengths = 0;
 292   _curr               = _head;
 293 }
 294 
 295 bool
 296 YoungList::rs_length_sampling_more() {
 297   return _curr != NULL;
 298 }
 299 
 300 void
 301 YoungList::rs_length_sampling_next() {
 302   assert( _curr != NULL, "invariant" );
 303   size_t rs_length = _curr->rem_set()->occupied();
 304 
 305   _sampled_rs_lengths += rs_length;
 306 
 307   // The current region may not yet have been added to the
 308   // incremental collection set (it gets added when it is
 309   // retired as the current allocation region).
 310   if (_curr->in_collection_set()) {
 311     // Update the collection set policy information for this region
 312     _g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);
 313   }
 314 
 315   _curr = _curr->get_next_young_region();
 316   if (_curr == NULL) {
 317     _last_sampled_rs_lengths = _sampled_rs_lengths;
 318     // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
 319   }
 320 }
 321 
 322 void
 323 YoungList::reset_auxilary_lists() {
 324   guarantee( is_empty(), "young list should be empty" );
 325   assert(check_list_well_formed(), "young list should be well formed");
 326 
 327   // Add survivor regions to SurvRateGroup.
 328   _g1h->g1_policy()->note_start_adding_survivor_regions();
 329   _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
 330 
 331   int young_index_in_cset = 0;
 332   for (HeapRegion* curr = _survivor_head;
 333        curr != NULL;
 334        curr = curr->get_next_young_region()) {
 335     _g1h->g1_policy()->set_region_survivor(curr, young_index_in_cset);
 336 
 337     // The region is a non-empty survivor so let's add it to
 338     // the incremental collection set for the next evacuation
 339     // pause.
 340     _g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);
 341     young_index_in_cset += 1;
 342   }
 343   assert((uint) young_index_in_cset == _survivor_length, "post-condition");
 344   _g1h->g1_policy()->note_stop_adding_survivor_regions();
 345 
 346   _head   = _survivor_head;
 347   _length = _survivor_length;
 348   if (_survivor_head != NULL) {
 349     assert(_survivor_tail != NULL, "cause it shouldn't be");
 350     assert(_survivor_length > 0, "invariant");
 351     _survivor_tail->set_next_young_region(NULL);
 352   }
 353 
 354   // Don't clear the survivor list handles until the start of
 355   // the next evacuation pause - we need it in order to re-tag
 356   // the survivor regions from this evacuation pause as 'young'
 357   // at the start of the next.
 358 
 359   _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
 360 
 361   assert(check_list_well_formed(), "young list should be well formed");
 362 }
 363 
 364 void YoungList::print() {
 365   HeapRegion* lists[] = {_head,   _survivor_head};
 366   const char* names[] = {"YOUNG", "SURVIVOR"};
 367 
 368   for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
 369     gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
 370     HeapRegion *curr = lists[list];
 371     if (curr == NULL)
 372       gclog_or_tty->print_cr("  empty");
 373     while (curr != NULL) {
 374       gclog_or_tty->print_cr("  "HR_FORMAT", P: "PTR_FORMAT "N: "PTR_FORMAT", age: %4d",
 375                              HR_FORMAT_PARAMS(curr),
 376                              curr->prev_top_at_mark_start(),
 377                              curr->next_top_at_mark_start(),
 378                              curr->age_in_surv_rate_group_cond());
 379       curr = curr->get_next_young_region();
 380     }
 381   }
 382 
 383   gclog_or_tty->print_cr("");
 384 }
 385 
 386 void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)
 387 {
 388   // Claim the right to put the region on the dirty cards region list
 389   // by installing a self pointer.
 390   HeapRegion* next = hr->get_next_dirty_cards_region();
 391   if (next == NULL) {
 392     HeapRegion* res = (HeapRegion*)
 393       Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),
 394                           NULL);
 395     if (res == NULL) {
 396       HeapRegion* head;
 397       do {
 398         // Put the region to the dirty cards region list.
 399         head = _dirty_cards_region_list;
 400         next = (HeapRegion*)
 401           Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);
 402         if (next == head) {
 403           assert(hr->get_next_dirty_cards_region() == hr,
 404                  "hr->get_next_dirty_cards_region() != hr");
 405           if (next == NULL) {
 406             // The last region in the list points to itself.
 407             hr->set_next_dirty_cards_region(hr);
 408           } else {
 409             hr->set_next_dirty_cards_region(next);
 410           }
 411         }
 412       } while (next != head);
 413     }
 414   }
 415 }
 416 
 417 HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
 418 {
 419   HeapRegion* head;
 420   HeapRegion* hr;
 421   do {
 422     head = _dirty_cards_region_list;
 423     if (head == NULL) {
 424       return NULL;
 425     }
 426     HeapRegion* new_head = head->get_next_dirty_cards_region();
 427     if (head == new_head) {
 428       // The last region.
 429       new_head = NULL;
 430     }
 431     hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,
 432                                           head);
 433   } while (hr != head);
 434   assert(hr != NULL, "invariant");
 435   hr->set_next_dirty_cards_region(NULL);
 436   return hr;
 437 }
 438 
 439 void G1CollectedHeap::stop_conc_gc_threads() {
 440   _cg1r->stop();
 441   _cmThread->stop();
 442 }
 443 
 444 #ifdef ASSERT
 445 // A region is added to the collection set as it is retired
 446 // so an address p can point to a region which will be in the
 447 // collection set but has not yet been retired.  This method
 448 // therefore is only accurate during a GC pause after all
 449 // regions have been retired.  It is used for debugging
 450 // to check if an nmethod has references to objects that can
 451 // be move during a partial collection.  Though it can be
 452 // inaccurate, it is sufficient for G1 because the conservative
 453 // implementation of is_scavengable() for G1 will indicate that
 454 // all nmethods must be scanned during a partial collection.
 455 bool G1CollectedHeap::is_in_partial_collection(const void* p) {
 456   HeapRegion* hr = heap_region_containing(p);
 457   return hr != NULL && hr->in_collection_set();
 458 }
 459 #endif
 460 
 461 // Returns true if the reference points to an object that
 462 // can move in an incremental collection.
 463 bool G1CollectedHeap::is_scavengable(const void* p) {
 464   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 465   G1CollectorPolicy* g1p = g1h->g1_policy();
 466   HeapRegion* hr = heap_region_containing(p);
 467   if (hr == NULL) {
 468      // perm gen (or null)
 469      return false;
 470   } else {
 471     return !hr->isHumongous();
 472   }
 473 }
 474 
 475 void G1CollectedHeap::check_ct_logs_at_safepoint() {
 476   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
 477   CardTableModRefBS* ct_bs = g1_barrier_set();
 478 
 479   // Count the dirty cards at the start.
 480   CountNonCleanMemRegionClosure count1(this);
 481   ct_bs->mod_card_iterate(&count1);
 482   int orig_count = count1.n();
 483 
 484   // First clear the logged cards.
 485   ClearLoggedCardTableEntryClosure clear;
 486   dcqs.set_closure(&clear);
 487   dcqs.apply_closure_to_all_completed_buffers();
 488   dcqs.iterate_closure_all_threads(false);
 489   clear.print_histo();
 490 
 491   // Now ensure that there's no dirty cards.
 492   CountNonCleanMemRegionClosure count2(this);
 493   ct_bs->mod_card_iterate(&count2);
 494   if (count2.n() != 0) {
 495     gclog_or_tty->print_cr("Card table has %d entries; %d originally",
 496                            count2.n(), orig_count);
 497   }
 498   guarantee(count2.n() == 0, "Card table should be clean.");
 499 
 500   RedirtyLoggedCardTableEntryClosure redirty;
 501   JavaThread::dirty_card_queue_set().set_closure(&redirty);
 502   dcqs.apply_closure_to_all_completed_buffers();
 503   dcqs.iterate_closure_all_threads(false);
 504   gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
 505                          clear.calls(), orig_count);
 506   guarantee(redirty.calls() == clear.calls(),
 507             "Or else mechanism is broken.");
 508 
 509   CountNonCleanMemRegionClosure count3(this);
 510   ct_bs->mod_card_iterate(&count3);
 511   if (count3.n() != orig_count) {
 512     gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
 513                            orig_count, count3.n());
 514     guarantee(count3.n() >= orig_count, "Should have restored them all.");
 515   }
 516 
 517   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
 518 }
 519 
 520 // Private class members.
 521 
 522 G1CollectedHeap* G1CollectedHeap::_g1h;
 523 
 524 // Private methods.
 525 
 526 HeapRegion*
 527 G1CollectedHeap::new_region_try_secondary_free_list() {
 528   MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
 529   while (!_secondary_free_list.is_empty() || free_regions_coming()) {
 530     if (!_secondary_free_list.is_empty()) {
 531       if (G1ConcRegionFreeingVerbose) {
 532         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 533                                "secondary_free_list has %u entries",
 534                                _secondary_free_list.length());
 535       }
 536       // It looks as if there are free regions available on the
 537       // secondary_free_list. Let's move them to the free_list and try
 538       // again to allocate from it.
 539       append_secondary_free_list();
 540 
 541       assert(!_free_list.is_empty(), "if the secondary_free_list was not "
 542              "empty we should have moved at least one entry to the free_list");
 543       HeapRegion* res = _free_list.remove_head();
 544       if (G1ConcRegionFreeingVerbose) {
 545         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 546                                "allocated "HR_FORMAT" from secondary_free_list",
 547                                HR_FORMAT_PARAMS(res));
 548       }
 549       return res;
 550     }
 551 
 552     // Wait here until we get notified either when (a) there are no
 553     // more free regions coming or (b) some regions have been moved on
 554     // the secondary_free_list.
 555     SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
 556   }
 557 
 558   if (G1ConcRegionFreeingVerbose) {
 559     gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 560                            "could not allocate from secondary_free_list");
 561   }
 562   return NULL;
 563 }
 564 
 565 HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool do_expand) {
 566   assert(!isHumongous(word_size) || word_size <= HeapRegion::GrainWords,
 567          "the only time we use this to allocate a humongous region is "
 568          "when we are allocating a single humongous region");
 569 
 570   HeapRegion* res;
 571   if (G1StressConcRegionFreeing) {
 572     if (!_secondary_free_list.is_empty()) {
 573       if (G1ConcRegionFreeingVerbose) {
 574         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 575                                "forced to look at the secondary_free_list");
 576       }
 577       res = new_region_try_secondary_free_list();
 578       if (res != NULL) {
 579         return res;
 580       }
 581     }
 582   }
 583   res = _free_list.remove_head_or_null();
 584   if (res == NULL) {
 585     if (G1ConcRegionFreeingVerbose) {
 586       gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 587                              "res == NULL, trying the secondary_free_list");
 588     }
 589     res = new_region_try_secondary_free_list();
 590   }
 591   if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
 592     // Currently, only attempts to allocate GC alloc regions set
 593     // do_expand to true. So, we should only reach here during a
 594     // safepoint. If this assumption changes we might have to
 595     // reconsider the use of _expand_heap_after_alloc_failure.
 596     assert(SafepointSynchronize::is_at_safepoint(), "invariant");
 597 
 598     ergo_verbose1(ErgoHeapSizing,
 599                   "attempt heap expansion",
 600                   ergo_format_reason("region allocation request failed")
 601                   ergo_format_byte("allocation request"),
 602                   word_size * HeapWordSize);
 603     if (expand(word_size * HeapWordSize)) {
 604       // Given that expand() succeeded in expanding the heap, and we
 605       // always expand the heap by an amount aligned to the heap
 606       // region size, the free list should in theory not be empty. So
 607       // it would probably be OK to use remove_head(). But the extra
 608       // check for NULL is unlikely to be a performance issue here (we
 609       // just expanded the heap!) so let's just be conservative and
 610       // use remove_head_or_null().
 611       res = _free_list.remove_head_or_null();
 612     } else {
 613       _expand_heap_after_alloc_failure = false;
 614     }
 615   }
 616   return res;
 617 }
 618 
 619 uint G1CollectedHeap::humongous_obj_allocate_find_first(uint num_regions,
 620                                                         size_t word_size) {
 621   assert(isHumongous(word_size), "word_size should be humongous");
 622   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
 623 
 624   uint first = G1_NULL_HRS_INDEX;
 625   if (num_regions == 1) {
 626     // Only one region to allocate, no need to go through the slower
 627     // path. The caller will attempt the expansion if this fails, so
 628     // let's not try to expand here too.
 629     HeapRegion* hr = new_region(word_size, false /* do_expand */);
 630     if (hr != NULL) {
 631       first = hr->hrs_index();
 632     } else {
 633       first = G1_NULL_HRS_INDEX;
 634     }
 635   } else {
 636     // We can't allocate humongous regions while cleanupComplete() is
 637     // running, since some of the regions we find to be empty might not
 638     // yet be added to the free list and it is not straightforward to
 639     // know which list they are on so that we can remove them. Note
 640     // that we only need to do this if we need to allocate more than
 641     // one region to satisfy the current humongous allocation
 642     // request. If we are only allocating one region we use the common
 643     // region allocation code (see above).
 644     wait_while_free_regions_coming();
 645     append_secondary_free_list_if_not_empty_with_lock();
 646 
 647     if (free_regions() >= num_regions) {
 648       first = _hrs.find_contiguous(num_regions);
 649       if (first != G1_NULL_HRS_INDEX) {
 650         for (uint i = first; i < first + num_regions; ++i) {
 651           HeapRegion* hr = region_at(i);
 652           assert(hr->is_empty(), "sanity");
 653           assert(is_on_master_free_list(hr), "sanity");
 654           hr->set_pending_removal(true);
 655         }
 656         _free_list.remove_all_pending(num_regions);
 657       }
 658     }
 659   }
 660   return first;
 661 }
 662 
 663 HeapWord*
 664 G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first,
 665                                                            uint num_regions,
 666                                                            size_t word_size) {
 667   assert(first != G1_NULL_HRS_INDEX, "pre-condition");
 668   assert(isHumongous(word_size), "word_size should be humongous");
 669   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
 670 
 671   // Index of last region in the series + 1.
 672   uint last = first + num_regions;
 673 
 674   // We need to initialize the region(s) we just discovered. This is
 675   // a bit tricky given that it can happen concurrently with
 676   // refinement threads refining cards on these regions and
 677   // potentially wanting to refine the BOT as they are scanning
 678   // those cards (this can happen shortly after a cleanup; see CR
 679   // 6991377). So we have to set up the region(s) carefully and in
 680   // a specific order.
 681 
 682   // The word size sum of all the regions we will allocate.
 683   size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
 684   assert(word_size <= word_size_sum, "sanity");
 685 
 686   // This will be the "starts humongous" region.
 687   HeapRegion* first_hr = region_at(first);
 688   // The header of the new object will be placed at the bottom of
 689   // the first region.
 690   HeapWord* new_obj = first_hr->bottom();
 691   // This will be the new end of the first region in the series that
 692   // should also match the end of the last region in the series.
 693   HeapWord* new_end = new_obj + word_size_sum;
 694   // This will be the new top of the first region that will reflect
 695   // this allocation.
 696   HeapWord* new_top = new_obj + word_size;
 697 
 698   // First, we need to zero the header of the space that we will be
 699   // allocating. When we update top further down, some refinement
 700   // threads might try to scan the region. By zeroing the header we
 701   // ensure that any thread that will try to scan the region will
 702   // come across the zero klass word and bail out.
 703   //
 704   // NOTE: It would not have been correct to have used
 705   // CollectedHeap::fill_with_object() and make the space look like
 706   // an int array. The thread that is doing the allocation will
 707   // later update the object header to a potentially different array
 708   // type and, for a very short period of time, the klass and length
 709   // fields will be inconsistent. This could cause a refinement
 710   // thread to calculate the object size incorrectly.
 711   Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
 712 
 713   // We will set up the first region as "starts humongous". This
 714   // will also update the BOT covering all the regions to reflect
 715   // that there is a single object that starts at the bottom of the
 716   // first region.
 717   first_hr->set_startsHumongous(new_top, new_end);
 718 
 719   // Then, if there are any, we will set up the "continues
 720   // humongous" regions.
 721   HeapRegion* hr = NULL;
 722   for (uint i = first + 1; i < last; ++i) {
 723     hr = region_at(i);
 724     hr->set_continuesHumongous(first_hr);
 725   }
 726   // If we have "continues humongous" regions (hr != NULL), then the
 727   // end of the last one should match new_end.
 728   assert(hr == NULL || hr->end() == new_end, "sanity");
 729 
 730   // Up to this point no concurrent thread would have been able to
 731   // do any scanning on any region in this series. All the top
 732   // fields still point to bottom, so the intersection between
 733   // [bottom,top] and [card_start,card_end] will be empty. Before we
 734   // update the top fields, we'll do a storestore to make sure that
 735   // no thread sees the update to top before the zeroing of the
 736   // object header and the BOT initialization.
 737   OrderAccess::storestore();
 738 
 739   // Now that the BOT and the object header have been initialized,
 740   // we can update top of the "starts humongous" region.
 741   assert(first_hr->bottom() < new_top && new_top <= first_hr->end(),
 742          "new_top should be in this region");
 743   first_hr->set_top(new_top);
 744   if (_hr_printer.is_active()) {
 745     HeapWord* bottom = first_hr->bottom();
 746     HeapWord* end = first_hr->orig_end();
 747     if ((first + 1) == last) {
 748       // the series has a single humongous region
 749       _hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top);
 750     } else {
 751       // the series has more than one humongous regions
 752       _hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end);
 753     }
 754   }
 755 
 756   // Now, we will update the top fields of the "continues humongous"
 757   // regions. The reason we need to do this is that, otherwise,
 758   // these regions would look empty and this will confuse parts of
 759   // G1. For example, the code that looks for a consecutive number
 760   // of empty regions will consider them empty and try to
 761   // re-allocate them. We can extend is_empty() to also include
 762   // !continuesHumongous(), but it is easier to just update the top
 763   // fields here. The way we set top for all regions (i.e., top ==
 764   // end for all regions but the last one, top == new_top for the
 765   // last one) is actually used when we will free up the humongous
 766   // region in free_humongous_region().
 767   hr = NULL;
 768   for (uint i = first + 1; i < last; ++i) {
 769     hr = region_at(i);
 770     if ((i + 1) == last) {
 771       // last continues humongous region
 772       assert(hr->bottom() < new_top && new_top <= hr->end(),
 773              "new_top should fall on this region");
 774       hr->set_top(new_top);
 775       _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top);
 776     } else {
 777       // not last one
 778       assert(new_top > hr->end(), "new_top should be above this region");
 779       hr->set_top(hr->end());
 780       _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end());
 781     }
 782   }
 783   // If we have continues humongous regions (hr != NULL), then the
 784   // end of the last one should match new_end and its top should
 785   // match new_top.
 786   assert(hr == NULL ||
 787          (hr->end() == new_end && hr->top() == new_top), "sanity");
 788 
 789   assert(first_hr->used() == word_size * HeapWordSize, "invariant");
 790   _summary_bytes_used += first_hr->used();
 791   _humongous_set.add(first_hr);
 792 
 793   return new_obj;
 794 }
 795 
 796 // If could fit into free regions w/o expansion, try.
 797 // Otherwise, if can expand, do so.
 798 // Otherwise, if using ex regions might help, try with ex given back.
 799 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
 800   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
 801 
 802   verify_region_sets_optional();
 803 
 804   size_t word_size_rounded = round_to(word_size, HeapRegion::GrainWords);
 805   uint num_regions = (uint) (word_size_rounded / HeapRegion::GrainWords);
 806   uint x_num = expansion_regions();
 807   uint fs = _hrs.free_suffix();
 808   uint first = humongous_obj_allocate_find_first(num_regions, word_size);
 809   if (first == G1_NULL_HRS_INDEX) {
 810     // The only thing we can do now is attempt expansion.
 811     if (fs + x_num >= num_regions) {
 812       // If the number of regions we're trying to allocate for this
 813       // object is at most the number of regions in the free suffix,
 814       // then the call to humongous_obj_allocate_find_first() above
 815       // should have succeeded and we wouldn't be here.
 816       //
 817       // We should only be trying to expand when the free suffix is
 818       // not sufficient for the object _and_ we have some expansion
 819       // room available.
 820       assert(num_regions > fs, "earlier allocation should have succeeded");
 821 
 822       ergo_verbose1(ErgoHeapSizing,
 823                     "attempt heap expansion",
 824                     ergo_format_reason("humongous allocation request failed")
 825                     ergo_format_byte("allocation request"),
 826                     word_size * HeapWordSize);
 827       if (expand((num_regions - fs) * HeapRegion::GrainBytes)) {
 828         // Even though the heap was expanded, it might not have
 829         // reached the desired size. So, we cannot assume that the
 830         // allocation will succeed.
 831         first = humongous_obj_allocate_find_first(num_regions, word_size);
 832       }
 833     }
 834   }
 835 
 836   HeapWord* result = NULL;
 837   if (first != G1_NULL_HRS_INDEX) {
 838     result =
 839       humongous_obj_allocate_initialize_regions(first, num_regions, word_size);
 840     assert(result != NULL, "it should always return a valid result");
 841 
 842     // A successful humongous object allocation changes the used space
 843     // information of the old generation so we need to recalculate the
 844     // sizes and update the jstat counters here.
 845     g1mm()->update_sizes();
 846   }
 847 
 848   verify_region_sets_optional();
 849 
 850   return result;
 851 }
 852 
 853 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {
 854   assert_heap_not_locked_and_not_at_safepoint();
 855   assert(!isHumongous(word_size), "we do not allow humongous TLABs");
 856 
 857   unsigned int dummy_gc_count_before;
 858   return attempt_allocation(word_size, &dummy_gc_count_before);
 859 }
 860 
 861 HeapWord*
 862 G1CollectedHeap::mem_allocate(size_t word_size,
 863                               bool*  gc_overhead_limit_was_exceeded) {
 864   assert_heap_not_locked_and_not_at_safepoint();
 865 
 866   // Loop until the allocation is satisfied, or unsatisfied after GC.
 867   for (int try_count = 1; /* we'll return */; try_count += 1) {
 868     unsigned int gc_count_before;
 869 
 870     HeapWord* result = NULL;
 871     if (!isHumongous(word_size)) {
 872       result = attempt_allocation(word_size, &gc_count_before);
 873     } else {
 874       result = attempt_allocation_humongous(word_size, &gc_count_before);
 875     }
 876     if (result != NULL) {
 877       return result;
 878     }
 879 
 880     // Create the garbage collection operation...
 881     VM_G1CollectForAllocation op(gc_count_before, word_size);
 882     // ...and get the VM thread to execute it.
 883     VMThread::execute(&op);
 884 
 885     if (op.prologue_succeeded() && op.pause_succeeded()) {
 886       // If the operation was successful we'll return the result even
 887       // if it is NULL. If the allocation attempt failed immediately
 888       // after a Full GC, it's unlikely we'll be able to allocate now.
 889       HeapWord* result = op.result();
 890       if (result != NULL && !isHumongous(word_size)) {
 891         // Allocations that take place on VM operations do not do any
 892         // card dirtying and we have to do it here. We only have to do
 893         // this for non-humongous allocations, though.
 894         dirty_young_block(result, word_size);
 895       }
 896       return result;
 897     } else {
 898       assert(op.result() == NULL,
 899              "the result should be NULL if the VM op did not succeed");
 900     }
 901 
 902     // Give a warning if we seem to be looping forever.
 903     if ((QueuedAllocationWarningCount > 0) &&
 904         (try_count % QueuedAllocationWarningCount == 0)) {
 905       warning("G1CollectedHeap::mem_allocate retries %d times", try_count);
 906     }
 907   }
 908 
 909   ShouldNotReachHere();
 910   return NULL;
 911 }
 912 
 913 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
 914                                            unsigned int *gc_count_before_ret) {
 915   // Make sure you read the note in attempt_allocation_humongous().
 916 
 917   assert_heap_not_locked_and_not_at_safepoint();
 918   assert(!isHumongous(word_size), "attempt_allocation_slow() should not "
 919          "be called for humongous allocation requests");
 920 
 921   // We should only get here after the first-level allocation attempt
 922   // (attempt_allocation()) failed to allocate.
 923 
 924   // We will loop until a) we manage to successfully perform the
 925   // allocation or b) we successfully schedule a collection which
 926   // fails to perform the allocation. b) is the only case when we'll
 927   // return NULL.
 928   HeapWord* result = NULL;
 929   for (int try_count = 1; /* we'll return */; try_count += 1) {
 930     bool should_try_gc;
 931     unsigned int gc_count_before;
 932 
 933     {
 934       MutexLockerEx x(Heap_lock);
 935 
 936       result = _mutator_alloc_region.attempt_allocation_locked(word_size,
 937                                                       false /* bot_updates */);
 938       if (result != NULL) {
 939         return result;
 940       }
 941 
 942       // If we reach here, attempt_allocation_locked() above failed to
 943       // allocate a new region. So the mutator alloc region should be NULL.
 944       assert(_mutator_alloc_region.get() == NULL, "only way to get here");
 945 
 946       if (GC_locker::is_active_and_needs_gc()) {
 947         if (g1_policy()->can_expand_young_list()) {
 948           // No need for an ergo verbose message here,
 949           // can_expand_young_list() does this when it returns true.
 950           result = _mutator_alloc_region.attempt_allocation_force(word_size,
 951                                                       false /* bot_updates */);
 952           if (result != NULL) {
 953             return result;
 954           }
 955         }
 956         should_try_gc = false;
 957       } else {
 958         // The GCLocker may not be active but the GCLocker initiated
 959         // GC may not yet have been performed (GCLocker::needs_gc()
 960         // returns true). In this case we do not try this GC and
 961         // wait until the GCLocker initiated GC is performed, and
 962         // then retry the allocation.
 963         if (GC_locker::needs_gc()) {
 964           should_try_gc = false;
 965         } else {
 966           // Read the GC count while still holding the Heap_lock.
 967           gc_count_before = total_collections();
 968           should_try_gc = true;
 969         }
 970       }
 971     }
 972 
 973     if (should_try_gc) {
 974       bool succeeded;
 975       result = do_collection_pause(word_size, gc_count_before, &succeeded);
 976       if (result != NULL) {
 977         assert(succeeded, "only way to get back a non-NULL result");
 978         return result;
 979       }
 980 
 981       if (succeeded) {
 982         // If we get here we successfully scheduled a collection which
 983         // failed to allocate. No point in trying to allocate
 984         // further. We'll just return NULL.
 985         MutexLockerEx x(Heap_lock);
 986         *gc_count_before_ret = total_collections();
 987         return NULL;
 988       }
 989     } else {
 990       // The GCLocker is either active or the GCLocker initiated
 991       // GC has not yet been performed. Stall until it is and
 992       // then retry the allocation.
 993       GC_locker::stall_until_clear();
 994     }
 995 
 996     // We can reach here if we were unsuccessful in scheduling a
 997     // collection (because another thread beat us to it) or if we were
 998     // stalled due to the GC locker. In either can we should retry the
 999     // allocation attempt in case another thread successfully
1000     // performed a collection and reclaimed enough space. We do the
1001     // first attempt (without holding the Heap_lock) here and the
1002     // follow-on attempt will be at the start of the next loop
1003     // iteration (after taking the Heap_lock).
1004     result = _mutator_alloc_region.attempt_allocation(word_size,
1005                                                       false /* bot_updates */);
1006     if (result != NULL) {
1007       return result;
1008     }
1009 
1010     // Give a warning if we seem to be looping forever.
1011     if ((QueuedAllocationWarningCount > 0) &&
1012         (try_count % QueuedAllocationWarningCount == 0)) {
1013       warning("G1CollectedHeap::attempt_allocation_slow() "
1014               "retries %d times", try_count);
1015     }
1016   }
1017 
1018   ShouldNotReachHere();
1019   return NULL;
1020 }
1021 
1022 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
1023                                           unsigned int * gc_count_before_ret) {
1024   // The structure of this method has a lot of similarities to
1025   // attempt_allocation_slow(). The reason these two were not merged
1026   // into a single one is that such a method would require several "if
1027   // allocation is not humongous do this, otherwise do that"
1028   // conditional paths which would obscure its flow. In fact, an early
1029   // version of this code did use a unified method which was harder to
1030   // follow and, as a result, it had subtle bugs that were hard to
1031   // track down. So keeping these two methods separate allows each to
1032   // be more readable. It will be good to keep these two in sync as
1033   // much as possible.
1034 
1035   assert_heap_not_locked_and_not_at_safepoint();
1036   assert(isHumongous(word_size), "attempt_allocation_humongous() "
1037          "should only be called for humongous allocations");
1038 
1039   // Humongous objects can exhaust the heap quickly, so we should check if we
1040   // need to start a marking cycle at each humongous object allocation. We do
1041   // the check before we do the actual allocation. The reason for doing it
1042   // before the allocation is that we avoid having to keep track of the newly
1043   // allocated memory while we do a GC.
1044   if (g1_policy()->need_to_start_conc_mark("concurrent humongous allocation",
1045                                            word_size)) {
1046     collect(GCCause::_g1_humongous_allocation);
1047   }
1048 
1049   // We will loop until a) we manage to successfully perform the
1050   // allocation or b) we successfully schedule a collection which
1051   // fails to perform the allocation. b) is the only case when we'll
1052   // return NULL.
1053   HeapWord* result = NULL;
1054   for (int try_count = 1; /* we'll return */; try_count += 1) {
1055     bool should_try_gc;
1056     unsigned int gc_count_before;
1057 
1058     {
1059       MutexLockerEx x(Heap_lock);
1060 
1061       // Given that humongous objects are not allocated in young
1062       // regions, we'll first try to do the allocation without doing a
1063       // collection hoping that there's enough space in the heap.
1064       result = humongous_obj_allocate(word_size);
1065       if (result != NULL) {
1066         return result;
1067       }
1068 
1069       if (GC_locker::is_active_and_needs_gc()) {
1070         should_try_gc = false;
1071       } else {
1072          // The GCLocker may not be active but the GCLocker initiated
1073         // GC may not yet have been performed (GCLocker::needs_gc()
1074         // returns true). In this case we do not try this GC and
1075         // wait until the GCLocker initiated GC is performed, and
1076         // then retry the allocation.
1077         if (GC_locker::needs_gc()) {
1078           should_try_gc = false;
1079         } else {
1080           // Read the GC count while still holding the Heap_lock.
1081           gc_count_before = total_collections();
1082           should_try_gc = true;
1083         }
1084       }
1085     }
1086 
1087     if (should_try_gc) {
1088       // If we failed to allocate the humongous object, we should try to
1089       // do a collection pause (if we're allowed) in case it reclaims
1090       // enough space for the allocation to succeed after the pause.
1091 
1092       bool succeeded;
1093       result = do_collection_pause(word_size, gc_count_before, &succeeded);
1094       if (result != NULL) {
1095         assert(succeeded, "only way to get back a non-NULL result");
1096         return result;
1097       }
1098 
1099       if (succeeded) {
1100         // If we get here we successfully scheduled a collection which
1101         // failed to allocate. No point in trying to allocate
1102         // further. We'll just return NULL.
1103         MutexLockerEx x(Heap_lock);
1104         *gc_count_before_ret = total_collections();
1105         return NULL;
1106       }
1107     } else {
1108       // The GCLocker is either active or the GCLocker initiated
1109       // GC has not yet been performed. Stall until it is and
1110       // then retry the allocation.
1111       GC_locker::stall_until_clear();
1112     }
1113 
1114     // We can reach here if we were unsuccessful in scheduling a
1115     // collection (because another thread beat us to it) or if we were
1116     // stalled due to the GC locker. In either can we should retry the
1117     // allocation attempt in case another thread successfully
1118     // performed a collection and reclaimed enough space.  Give a
1119     // warning if we seem to be looping forever.
1120 
1121     if ((QueuedAllocationWarningCount > 0) &&
1122         (try_count % QueuedAllocationWarningCount == 0)) {
1123       warning("G1CollectedHeap::attempt_allocation_humongous() "
1124               "retries %d times", try_count);
1125     }
1126   }
1127 
1128   ShouldNotReachHere();
1129   return NULL;
1130 }
1131 
1132 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
1133                                        bool expect_null_mutator_alloc_region) {
1134   assert_at_safepoint(true /* should_be_vm_thread */);
1135   assert(_mutator_alloc_region.get() == NULL ||
1136                                              !expect_null_mutator_alloc_region,
1137          "the current alloc region was unexpectedly found to be non-NULL");
1138 
1139   if (!isHumongous(word_size)) {
1140     return _mutator_alloc_region.attempt_allocation_locked(word_size,
1141                                                       false /* bot_updates */);
1142   } else {
1143     HeapWord* result = humongous_obj_allocate(word_size);
1144     if (result != NULL && g1_policy()->need_to_start_conc_mark("STW humongous allocation")) {
1145       g1_policy()->set_initiate_conc_mark_if_possible();
1146     }
1147     return result;
1148   }
1149 
1150   ShouldNotReachHere();
1151 }
1152 
1153 class PostMCRemSetClearClosure: public HeapRegionClosure {
1154   G1CollectedHeap* _g1h;
1155   ModRefBarrierSet* _mr_bs;
1156 public:
1157   PostMCRemSetClearClosure(G1CollectedHeap* g1h, ModRefBarrierSet* mr_bs) :
1158     _g1h(g1h), _mr_bs(mr_bs) {}
1159 
1160   bool doHeapRegion(HeapRegion* r) {
1161     HeapRegionRemSet* hrrs = r->rem_set();
1162 
1163     if (r->continuesHumongous()) {
1164       // We'll assert that the strong code root list and RSet is empty
1165       assert(hrrs->strong_code_roots_list_length() == 0, "sanity");
1166       assert(hrrs->occupied() == 0, "RSet should be empty");
1167       return false;
1168     }
1169 
1170     _g1h->reset_gc_time_stamps(r);
1171     hrrs->clear();
1172     // You might think here that we could clear just the cards
1173     // corresponding to the used region.  But no: if we leave a dirty card
1174     // in a region we might allocate into, then it would prevent that card
1175     // from being enqueued, and cause it to be missed.
1176     // Re: the performance cost: we shouldn't be doing full GC anyway!
1177     _mr_bs->clear(MemRegion(r->bottom(), r->end()));
1178 
1179     return false;
1180   }
1181 };
1182 
1183 void G1CollectedHeap::clear_rsets_post_compaction() {
1184   PostMCRemSetClearClosure rs_clear(this, g1_barrier_set());
1185   heap_region_iterate(&rs_clear);
1186 }
1187 
1188 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
1189   G1CollectedHeap*   _g1h;
1190   UpdateRSOopClosure _cl;
1191   int                _worker_i;
1192 public:
1193   RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
1194     _cl(g1->g1_rem_set(), worker_i),
1195     _worker_i(worker_i),
1196     _g1h(g1)
1197   { }
1198 
1199   bool doHeapRegion(HeapRegion* r) {
1200     if (!r->continuesHumongous()) {
1201       _cl.set_from(r);
1202       r->oop_iterate(&_cl);
1203     }
1204     return false;
1205   }
1206 };
1207 
1208 class ParRebuildRSTask: public AbstractGangTask {
1209   G1CollectedHeap* _g1;
1210 public:
1211   ParRebuildRSTask(G1CollectedHeap* g1)
1212     : AbstractGangTask("ParRebuildRSTask"),
1213       _g1(g1)
1214   { }
1215 
1216   void work(uint worker_id) {
1217     RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);
1218     _g1->heap_region_par_iterate_chunked(&rebuild_rs, worker_id,
1219                                           _g1->workers()->active_workers(),
1220                                          HeapRegion::RebuildRSClaimValue);
1221   }
1222 };
1223 
1224 class PostCompactionPrinterClosure: public HeapRegionClosure {
1225 private:
1226   G1HRPrinter* _hr_printer;
1227 public:
1228   bool doHeapRegion(HeapRegion* hr) {
1229     assert(!hr->is_young(), "not expecting to find young regions");
1230     // We only generate output for non-empty regions.
1231     if (!hr->is_empty()) {
1232       if (!hr->isHumongous()) {
1233         _hr_printer->post_compaction(hr, G1HRPrinter::Old);
1234       } else if (hr->startsHumongous()) {
1235         if (hr->region_num() == 1) {
1236           // single humongous region
1237           _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
1238         } else {
1239           _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
1240         }
1241       } else {
1242         assert(hr->continuesHumongous(), "only way to get here");
1243         _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
1244       }
1245     }
1246     return false;
1247   }
1248 
1249   PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
1250     : _hr_printer(hr_printer) { }
1251 };
1252 
1253 void G1CollectedHeap::print_hrs_post_compaction() {
1254   PostCompactionPrinterClosure cl(hr_printer());
1255   heap_region_iterate(&cl);
1256 }
1257 
1258 bool G1CollectedHeap::do_collection(bool explicit_gc,
1259                                     bool clear_all_soft_refs,
1260                                     size_t word_size) {
1261   assert_at_safepoint(true /* should_be_vm_thread */);
1262 
1263   if (GC_locker::check_active_before_gc()) {
1264     return false;
1265   }
1266 
1267   STWGCTimer* gc_timer = G1MarkSweep::gc_timer();
1268   gc_timer->register_gc_start();
1269 
1270   SerialOldTracer* gc_tracer = G1MarkSweep::gc_tracer();
1271   gc_tracer->report_gc_start(gc_cause(), gc_timer->gc_start());
1272 
1273   SvcGCMarker sgcm(SvcGCMarker::FULL);
1274   ResourceMark rm;
1275 
1276   print_heap_before_gc();
1277   trace_heap_before_gc(gc_tracer);
1278 
1279   HRSPhaseSetter x(HRSPhaseFullGC);
1280   verify_region_sets_optional();
1281 
1282   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1283                            collector_policy()->should_clear_all_soft_refs();
1284 
1285   ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
1286 
1287   {
1288     IsGCActiveMark x;
1289 
1290     // Timing
1291     assert(gc_cause() != GCCause::_java_lang_system_gc || explicit_gc, "invariant");
1292     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
1293 
1294     {
1295       GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL);
1296       TraceCollectorStats tcs(g1mm()->full_collection_counters());
1297       TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
1298 
1299       double start = os::elapsedTime();
1300       g1_policy()->record_full_collection_start();
1301 
1302       // Note: When we have a more flexible GC logging framework that
1303       // allows us to add optional attributes to a GC log record we
1304       // could consider timing and reporting how long we wait in the
1305       // following two methods.
1306       wait_while_free_regions_coming();
1307       // If we start the compaction before the CM threads finish
1308       // scanning the root regions we might trip them over as we'll
1309       // be moving objects / updating references. So let's wait until
1310       // they are done. By telling them to abort, they should complete
1311       // early.
1312       _cm->root_regions()->abort();
1313       _cm->root_regions()->wait_until_scan_finished();
1314       append_secondary_free_list_if_not_empty_with_lock();
1315 
1316       gc_prologue(true);
1317       increment_total_collections(true /* full gc */);
1318       increment_old_marking_cycles_started();
1319 
1320       assert(used() == recalculate_used(), "Should be equal");
1321 
1322       verify_before_gc();
1323 
1324       pre_full_gc_dump(gc_timer);
1325 
1326       COMPILER2_PRESENT(DerivedPointerTable::clear());
1327 
1328       // Disable discovery and empty the discovered lists
1329       // for the CM ref processor.
1330       ref_processor_cm()->disable_discovery();
1331       ref_processor_cm()->abandon_partial_discovery();
1332       ref_processor_cm()->verify_no_references_recorded();
1333 
1334       // Abandon current iterations of concurrent marking and concurrent
1335       // refinement, if any are in progress. We have to do this before
1336       // wait_until_scan_finished() below.
1337       concurrent_mark()->abort();
1338 
1339       // Make sure we'll choose a new allocation region afterwards.
1340       release_mutator_alloc_region();
1341       abandon_gc_alloc_regions();
1342       g1_rem_set()->cleanupHRRS();
1343 
1344       // We should call this after we retire any currently active alloc
1345       // regions so that all the ALLOC / RETIRE events are generated
1346       // before the start GC event.
1347       _hr_printer.start_gc(true /* full */, (size_t) total_collections());
1348 
1349       // We may have added regions to the current incremental collection
1350       // set between the last GC or pause and now. We need to clear the
1351       // incremental collection set and then start rebuilding it afresh
1352       // after this full GC.
1353       abandon_collection_set(g1_policy()->inc_cset_head());
1354       g1_policy()->clear_incremental_cset();
1355       g1_policy()->stop_incremental_cset_building();
1356 
1357       tear_down_region_sets(false /* free_list_only */);
1358       g1_policy()->set_gcs_are_young(true);
1359 
1360       // See the comments in g1CollectedHeap.hpp and
1361       // G1CollectedHeap::ref_processing_init() about
1362       // how reference processing currently works in G1.
1363 
1364       // Temporarily make discovery by the STW ref processor single threaded (non-MT).
1365       ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);
1366 
1367       // Temporarily clear the STW ref processor's _is_alive_non_header field.
1368       ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);
1369 
1370       ref_processor_stw()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
1371       ref_processor_stw()->setup_policy(do_clear_all_soft_refs);
1372 
1373       // Do collection work
1374       {
1375         HandleMark hm;  // Discard invalid handles created during gc
1376         G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);
1377       }
1378 
1379       assert(free_regions() == 0, "we should not have added any free regions");
1380       rebuild_region_sets(false /* free_list_only */);
1381 
1382       // Enqueue any discovered reference objects that have
1383       // not been removed from the discovered lists.
1384       ref_processor_stw()->enqueue_discovered_references();
1385 
1386       COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1387 
1388       MemoryService::track_memory_usage();
1389 
1390       assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
1391       ref_processor_stw()->verify_no_references_recorded();
1392 
1393       // Note: since we've just done a full GC, concurrent
1394       // marking is no longer active. Therefore we need not
1395       // re-enable reference discovery for the CM ref processor.
1396       // That will be done at the start of the next marking cycle.
1397       assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");
1398       ref_processor_cm()->verify_no_references_recorded();
1399 
1400       reset_gc_time_stamp();
1401       // Since everything potentially moved, we will clear all remembered
1402       // sets, and clear all cards.  Later we will rebuild remembered
1403       // sets. We will also reset the GC time stamps of the regions.
1404       clear_rsets_post_compaction();
1405       check_gc_time_stamps();
1406 
1407       // Resize the heap if necessary.
1408       resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
1409 
1410       if (_hr_printer.is_active()) {
1411         // We should do this after we potentially resize the heap so
1412         // that all the COMMIT / UNCOMMIT events are generated before
1413         // the end GC event.
1414 
1415         print_hrs_post_compaction();
1416         _hr_printer.end_gc(true /* full */, (size_t) total_collections());
1417       }
1418 
1419       G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
1420       if (hot_card_cache->use_cache()) {
1421         hot_card_cache->reset_card_counts();
1422         hot_card_cache->reset_hot_cache();
1423       }
1424 
1425       // Rebuild remembered sets of all regions.
1426       if (G1CollectedHeap::use_parallel_gc_threads()) {
1427         uint n_workers =
1428           AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
1429                                                   workers()->active_workers(),
1430                                                   Threads::number_of_non_daemon_threads());
1431         assert(UseDynamicNumberOfGCThreads ||
1432                n_workers == workers()->total_workers(),
1433                "If not dynamic should be using all the  workers");
1434         workers()->set_active_workers(n_workers);
1435         // Set parallel threads in the heap (_n_par_threads) only
1436         // before a parallel phase and always reset it to 0 after
1437         // the phase so that the number of parallel threads does
1438         // no get carried forward to a serial phase where there
1439         // may be code that is "possibly_parallel".
1440         set_par_threads(n_workers);
1441 
1442         ParRebuildRSTask rebuild_rs_task(this);
1443         assert(check_heap_region_claim_values(
1444                HeapRegion::InitialClaimValue), "sanity check");
1445         assert(UseDynamicNumberOfGCThreads ||
1446                workers()->active_workers() == workers()->total_workers(),
1447                "Unless dynamic should use total workers");
1448         // Use the most recent number of  active workers
1449         assert(workers()->active_workers() > 0,
1450                "Active workers not properly set");
1451         set_par_threads(workers()->active_workers());
1452         workers()->run_task(&rebuild_rs_task);
1453         set_par_threads(0);
1454         assert(check_heap_region_claim_values(
1455                HeapRegion::RebuildRSClaimValue), "sanity check");
1456         reset_heap_region_claim_values();
1457       } else {
1458         RebuildRSOutOfRegionClosure rebuild_rs(this);
1459         heap_region_iterate(&rebuild_rs);
1460       }
1461 
1462       // Rebuild the strong code root lists for each region
1463       rebuild_strong_code_roots();
1464 
1465       if (true) { // FIXME
1466         // Ask the permanent generation to adjust size for full collections
1467         perm()->compute_new_size();
1468       }
1469 
1470 #ifdef TRACESPINNING
1471       ParallelTaskTerminator::print_termination_counts();
1472 #endif
1473 
1474       // Discard all rset updates
1475       JavaThread::dirty_card_queue_set().abandon_logs();
1476       assert(!G1DeferredRSUpdate
1477              || (G1DeferredRSUpdate &&
1478                 (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
1479 
1480       _young_list->reset_sampled_info();
1481       // At this point there should be no regions in the
1482       // entire heap tagged as young.
1483       assert(check_young_list_empty(true /* check_heap */),
1484              "young list should be empty at this point");
1485 
1486       // Update the number of full collections that have been completed.
1487       increment_old_marking_cycles_completed(false /* concurrent */);
1488 
1489       _hrs.verify_optional();
1490       verify_region_sets_optional();
1491 
1492       verify_after_gc();
1493 
1494       // Start a new incremental collection set for the next pause
1495       assert(g1_policy()->collection_set() == NULL, "must be");
1496       g1_policy()->start_incremental_cset_building();
1497 
1498       // Clear the _cset_fast_test bitmap in anticipation of adding
1499       // regions to the incremental collection set for the next
1500       // evacuation pause.
1501       clear_cset_fast_test();
1502 
1503       init_mutator_alloc_region();
1504 
1505       double end = os::elapsedTime();
1506       g1_policy()->record_full_collection_end();
1507 
1508       if (G1Log::fine()) {
1509         g1_policy()->print_heap_transition();
1510       }
1511 
1512       // We must call G1MonitoringSupport::update_sizes() in the same scoping level
1513       // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
1514       // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
1515       // before any GC notifications are raised.
1516       g1mm()->update_sizes();
1517 
1518       gc_epilogue(true);
1519     }
1520 
1521     if (G1Log::finer()) {
1522       g1_policy()->print_detailed_heap_transition();
1523     }
1524 
1525     print_heap_after_gc();
1526     trace_heap_after_gc(gc_tracer);
1527 
1528     post_full_gc_dump(gc_timer);
1529   }
1530 
1531   gc_timer->register_gc_end();
1532   gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
1533 
1534   return true;
1535 }
1536 
1537 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1538   // do_collection() will return whether it succeeded in performing
1539   // the GC. Currently, there is no facility on the
1540   // do_full_collection() API to notify the caller than the collection
1541   // did not succeed (e.g., because it was locked out by the GC
1542   // locker). So, right now, we'll ignore the return value.
1543   bool dummy = do_collection(true,                /* explicit_gc */
1544                              clear_all_soft_refs,
1545                              0                    /* word_size */);
1546 }
1547 
1548 // This code is mostly copied from TenuredGeneration.
1549 void
1550 G1CollectedHeap::
1551 resize_if_necessary_after_full_collection(size_t word_size) {
1552   // Include the current allocation, if any, and bytes that will be
1553   // pre-allocated to support collections, as "used".
1554   const size_t used_after_gc = used();
1555   const size_t capacity_after_gc = capacity();
1556   const size_t free_after_gc = capacity_after_gc - used_after_gc;
1557 
1558   // This is enforced in arguments.cpp.
1559   assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
1560          "otherwise the code below doesn't make sense");
1561 
1562   // We don't have floating point command-line arguments
1563   const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
1564   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1565   const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
1566   const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1567 
1568   const size_t min_heap_size = collector_policy()->min_heap_byte_size();
1569   const size_t max_heap_size = collector_policy()->max_heap_byte_size();
1570 
1571   // We have to be careful here as these two calculations can overflow
1572   // 32-bit size_t's.
1573   double used_after_gc_d = (double) used_after_gc;
1574   double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
1575   double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
1576 
1577   // Let's make sure that they are both under the max heap size, which
1578   // by default will make them fit into a size_t.
1579   double desired_capacity_upper_bound = (double) max_heap_size;
1580   minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
1581                                     desired_capacity_upper_bound);
1582   maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
1583                                     desired_capacity_upper_bound);
1584 
1585   // We can now safely turn them into size_t's.
1586   size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
1587   size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
1588 
1589   // This assert only makes sense here, before we adjust them
1590   // with respect to the min and max heap size.
1591   assert(minimum_desired_capacity <= maximum_desired_capacity,
1592          err_msg("minimum_desired_capacity = "SIZE_FORMAT", "
1593                  "maximum_desired_capacity = "SIZE_FORMAT,
1594                  minimum_desired_capacity, maximum_desired_capacity));
1595 
1596   // Should not be greater than the heap max size. No need to adjust
1597   // it with respect to the heap min size as it's a lower bound (i.e.,
1598   // we'll try to make the capacity larger than it, not smaller).
1599   minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);
1600   // Should not be less than the heap min size. No need to adjust it
1601   // with respect to the heap max size as it's an upper bound (i.e.,
1602   // we'll try to make the capacity smaller than it, not greater).
1603   maximum_desired_capacity =  MAX2(maximum_desired_capacity, min_heap_size);
1604 
1605   if (capacity_after_gc < minimum_desired_capacity) {
1606     // Don't expand unless it's significant
1607     size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1608     ergo_verbose4(ErgoHeapSizing,
1609                   "attempt heap expansion",
1610                   ergo_format_reason("capacity lower than "
1611                                      "min desired capacity after Full GC")
1612                   ergo_format_byte("capacity")
1613                   ergo_format_byte("occupancy")
1614                   ergo_format_byte_perc("min desired capacity"),
1615                   capacity_after_gc, used_after_gc,
1616                   minimum_desired_capacity, (double) MinHeapFreeRatio);
1617     expand(expand_bytes);
1618 
1619     // No expansion, now see if we want to shrink
1620   } else if (capacity_after_gc > maximum_desired_capacity) {
1621     // Capacity too large, compute shrinking size
1622     size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1623     ergo_verbose4(ErgoHeapSizing,
1624                   "attempt heap shrinking",
1625                   ergo_format_reason("capacity higher than "
1626                                      "max desired capacity after Full GC")
1627                   ergo_format_byte("capacity")
1628                   ergo_format_byte("occupancy")
1629                   ergo_format_byte_perc("max desired capacity"),
1630                   capacity_after_gc, used_after_gc,
1631                   maximum_desired_capacity, (double) MaxHeapFreeRatio);
1632     shrink(shrink_bytes);
1633   }
1634 }
1635 
1636 
1637 HeapWord*
1638 G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1639                                            bool* succeeded) {
1640   assert_at_safepoint(true /* should_be_vm_thread */);
1641 
1642   *succeeded = true;
1643   // Let's attempt the allocation first.
1644   HeapWord* result =
1645     attempt_allocation_at_safepoint(word_size,
1646                                  false /* expect_null_mutator_alloc_region */);
1647   if (result != NULL) {
1648     assert(*succeeded, "sanity");
1649     return result;
1650   }
1651 
1652   // In a G1 heap, we're supposed to keep allocation from failing by
1653   // incremental pauses.  Therefore, at least for now, we'll favor
1654   // expansion over collection.  (This might change in the future if we can
1655   // do something smarter than full collection to satisfy a failed alloc.)
1656   result = expand_and_allocate(word_size);
1657   if (result != NULL) {
1658     assert(*succeeded, "sanity");
1659     return result;
1660   }
1661 
1662   // Expansion didn't work, we'll try to do a Full GC.
1663   bool gc_succeeded = do_collection(false, /* explicit_gc */
1664                                     false, /* clear_all_soft_refs */
1665                                     word_size);
1666   if (!gc_succeeded) {
1667     *succeeded = false;
1668     return NULL;
1669   }
1670 
1671   // Retry the allocation
1672   result = attempt_allocation_at_safepoint(word_size,
1673                                   true /* expect_null_mutator_alloc_region */);
1674   if (result != NULL) {
1675     assert(*succeeded, "sanity");
1676     return result;
1677   }
1678 
1679   // Then, try a Full GC that will collect all soft references.
1680   gc_succeeded = do_collection(false, /* explicit_gc */
1681                                true,  /* clear_all_soft_refs */
1682                                word_size);
1683   if (!gc_succeeded) {
1684     *succeeded = false;
1685     return NULL;
1686   }
1687 
1688   // Retry the allocation once more
1689   result = attempt_allocation_at_safepoint(word_size,
1690                                   true /* expect_null_mutator_alloc_region */);
1691   if (result != NULL) {
1692     assert(*succeeded, "sanity");
1693     return result;
1694   }
1695 
1696   assert(!collector_policy()->should_clear_all_soft_refs(),
1697          "Flag should have been handled and cleared prior to this point");
1698 
1699   // What else?  We might try synchronous finalization later.  If the total
1700   // space available is large enough for the allocation, then a more
1701   // complete compaction phase than we've tried so far might be
1702   // appropriate.
1703   assert(*succeeded, "sanity");
1704   return NULL;
1705 }
1706 
1707 // Attempting to expand the heap sufficiently
1708 // to support an allocation of the given "word_size".  If
1709 // successful, perform the allocation and return the address of the
1710 // allocated block, or else "NULL".
1711 
1712 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1713   assert_at_safepoint(true /* should_be_vm_thread */);
1714 
1715   verify_region_sets_optional();
1716 
1717   size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1718   ergo_verbose1(ErgoHeapSizing,
1719                 "attempt heap expansion",
1720                 ergo_format_reason("allocation request failed")
1721                 ergo_format_byte("allocation request"),
1722                 word_size * HeapWordSize);
1723   if (expand(expand_bytes)) {
1724     _hrs.verify_optional();
1725     verify_region_sets_optional();
1726     return attempt_allocation_at_safepoint(word_size,
1727                                  false /* expect_null_mutator_alloc_region */);
1728   }
1729   return NULL;
1730 }
1731 
1732 void G1CollectedHeap::update_committed_space(HeapWord* old_end,
1733                                              HeapWord* new_end) {
1734   assert(old_end != new_end, "don't call this otherwise");
1735   assert((HeapWord*) _g1_storage.high() == new_end, "invariant");
1736 
1737   // Update the committed mem region.
1738   _g1_committed.set_end(new_end);
1739   // Tell the card table about the update.
1740   Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1741   // Tell the BOT about the update.
1742   _bot_shared->resize(_g1_committed.word_size());
1743   // Tell the hot card cache about the update
1744   _cg1r->hot_card_cache()->resize_card_counts(capacity());
1745 }
1746 
1747 bool G1CollectedHeap::expand(size_t expand_bytes) {
1748   size_t old_mem_size = _g1_storage.committed_size();
1749   size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1750   aligned_expand_bytes = align_size_up(aligned_expand_bytes,
1751                                        HeapRegion::GrainBytes);
1752   ergo_verbose2(ErgoHeapSizing,
1753                 "expand the heap",
1754                 ergo_format_byte("requested expansion amount")
1755                 ergo_format_byte("attempted expansion amount"),
1756                 expand_bytes, aligned_expand_bytes);
1757 
1758   // First commit the memory.
1759   HeapWord* old_end = (HeapWord*) _g1_storage.high();
1760   bool successful = _g1_storage.expand_by(aligned_expand_bytes);
1761   if (successful) {
1762     // Then propagate this update to the necessary data structures.
1763     HeapWord* new_end = (HeapWord*) _g1_storage.high();
1764     update_committed_space(old_end, new_end);
1765 
1766     FreeRegionList expansion_list("Local Expansion List");
1767     MemRegion mr = _hrs.expand_by(old_end, new_end, &expansion_list);
1768     assert(mr.start() == old_end, "post-condition");
1769     // mr might be a smaller region than what was requested if
1770     // expand_by() was unable to allocate the HeapRegion instances
1771     assert(mr.end() <= new_end, "post-condition");
1772 
1773     size_t actual_expand_bytes = mr.byte_size();
1774     assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1775     assert(actual_expand_bytes == expansion_list.total_capacity_bytes(),
1776            "post-condition");
1777     if (actual_expand_bytes < aligned_expand_bytes) {
1778       // We could not expand _hrs to the desired size. In this case we
1779       // need to shrink the committed space accordingly.
1780       assert(mr.end() < new_end, "invariant");
1781 
1782       size_t diff_bytes = aligned_expand_bytes - actual_expand_bytes;
1783       // First uncommit the memory.
1784       _g1_storage.shrink_by(diff_bytes);
1785       // Then propagate this update to the necessary data structures.
1786       update_committed_space(new_end, mr.end());
1787     }
1788     _free_list.add_as_tail(&expansion_list);
1789 
1790     if (_hr_printer.is_active()) {
1791       HeapWord* curr = mr.start();
1792       while (curr < mr.end()) {
1793         HeapWord* curr_end = curr + HeapRegion::GrainWords;
1794         _hr_printer.commit(curr, curr_end);
1795         curr = curr_end;
1796       }
1797       assert(curr == mr.end(), "post-condition");
1798     }
1799     g1_policy()->record_new_heap_size(n_regions());
1800   } else {
1801     ergo_verbose0(ErgoHeapSizing,
1802                   "did not expand the heap",
1803                   ergo_format_reason("heap expansion operation failed"));
1804     // The expansion of the virtual storage space was unsuccessful.
1805     // Let's see if it was because we ran out of swap.
1806     if (G1ExitOnExpansionFailure &&
1807         _g1_storage.uncommitted_size() >= aligned_expand_bytes) {
1808       // We had head room...
1809       vm_exit_out_of_memory(aligned_expand_bytes, "G1 heap expansion");
1810     }
1811   }
1812   return successful;
1813 }
1814 
1815 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1816   size_t old_mem_size = _g1_storage.committed_size();
1817   size_t aligned_shrink_bytes =
1818     ReservedSpace::page_align_size_down(shrink_bytes);
1819   aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
1820                                          HeapRegion::GrainBytes);
1821   uint num_regions_deleted = 0;
1822   MemRegion mr = _hrs.shrink_by(aligned_shrink_bytes, &num_regions_deleted);
1823   HeapWord* old_end = (HeapWord*) _g1_storage.high();
1824   assert(mr.end() == old_end, "post-condition");
1825 
1826   ergo_verbose3(ErgoHeapSizing,
1827                 "shrink the heap",
1828                 ergo_format_byte("requested shrinking amount")
1829                 ergo_format_byte("aligned shrinking amount")
1830                 ergo_format_byte("attempted shrinking amount"),
1831                 shrink_bytes, aligned_shrink_bytes, mr.byte_size());
1832   if (mr.byte_size() > 0) {
1833     if (_hr_printer.is_active()) {
1834       HeapWord* curr = mr.end();
1835       while (curr > mr.start()) {
1836         HeapWord* curr_end = curr;
1837         curr -= HeapRegion::GrainWords;
1838         _hr_printer.uncommit(curr, curr_end);
1839       }
1840       assert(curr == mr.start(), "post-condition");
1841     }
1842 
1843     _g1_storage.shrink_by(mr.byte_size());
1844     HeapWord* new_end = (HeapWord*) _g1_storage.high();
1845     assert(mr.start() == new_end, "post-condition");
1846 
1847     _expansion_regions += num_regions_deleted;
1848     update_committed_space(old_end, new_end);
1849     HeapRegionRemSet::shrink_heap(n_regions());
1850     g1_policy()->record_new_heap_size(n_regions());
1851   } else {
1852     ergo_verbose0(ErgoHeapSizing,
1853                   "did not shrink the heap",
1854                   ergo_format_reason("heap shrinking operation failed"));
1855   }
1856 }
1857 
1858 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1859   verify_region_sets_optional();
1860 
1861   // We should only reach here at the end of a Full GC which means we
1862   // should not not be holding to any GC alloc regions. The method
1863   // below will make sure of that and do any remaining clean up.
1864   abandon_gc_alloc_regions();
1865 
1866   // Instead of tearing down / rebuilding the free lists here, we
1867   // could instead use the remove_all_pending() method on free_list to
1868   // remove only the ones that we need to remove.
1869   tear_down_region_sets(true /* free_list_only */);
1870   shrink_helper(shrink_bytes);
1871   rebuild_region_sets(true /* free_list_only */);
1872 
1873   _hrs.verify_optional();
1874   verify_region_sets_optional();
1875 }
1876 
1877 // Public methods.
1878 
1879 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
1880 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
1881 #endif // _MSC_VER
1882 
1883 
1884 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
1885   SharedHeap(policy_),
1886   _g1_policy(policy_),
1887   _dirty_card_queue_set(false),
1888   _into_cset_dirty_card_queue_set(false),
1889   _is_alive_closure_cm(this),
1890   _is_alive_closure_stw(this),
1891   _ref_processor_cm(NULL),
1892   _ref_processor_stw(NULL),
1893   _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
1894   _bot_shared(NULL),
1895   _evac_failure_scan_stack(NULL),
1896   _mark_in_progress(false),
1897   _cg1r(NULL), _summary_bytes_used(0),
1898   _g1mm(NULL),
1899   _refine_cte_cl(NULL),
1900   _full_collection(false),
1901   _free_list("Master Free List"),
1902   _secondary_free_list("Secondary Free List"),
1903   _old_set("Old Set"),
1904   _humongous_set("Master Humongous Set"),
1905   _free_regions_coming(false),
1906   _young_list(new YoungList(this)),
1907   _gc_time_stamp(0),
1908   _retained_old_gc_alloc_region(NULL),
1909   _survivor_plab_stats(YoungPLABSize, PLABWeight),
1910   _old_plab_stats(OldPLABSize, PLABWeight),
1911   _expand_heap_after_alloc_failure(true),
1912   _surviving_young_words(NULL),
1913   _old_marking_cycles_started(0),
1914   _old_marking_cycles_completed(0),
1915   _concurrent_cycle_started(false),
1916   _in_cset_fast_test(NULL),
1917   _in_cset_fast_test_base(NULL),
1918   _dirty_cards_region_list(NULL),
1919   _worker_cset_start_region(NULL),
1920   _worker_cset_start_region_time_stamp(NULL),
1921   _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1922   _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
1923   _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1924   _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()) {
1925 
1926   _g1h = this;
1927   if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
1928     vm_exit_during_initialization("Failed necessary allocation.");
1929   }
1930 
1931   _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2;
1932 
1933   int n_queues = MAX2((int)ParallelGCThreads, 1);
1934   _task_queues = new RefToScanQueueSet(n_queues);
1935 
1936   int n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
1937   assert(n_rem_sets > 0, "Invariant.");
1938 
1939   HeapRegionRemSetIterator** iter_arr = NEW_C_HEAP_ARRAY(HeapRegionRemSetIterator*, n_queues, mtGC);
1940   _worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC);
1941   _worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(unsigned int, n_queues, mtGC);
1942   _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
1943 
1944   for (int i = 0; i < n_queues; i++) {
1945     RefToScanQueue* q = new RefToScanQueue();
1946     q->initialize();
1947     _task_queues->register_queue(i, q);
1948     iter_arr[i] = new HeapRegionRemSetIterator();
1949     ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
1950   }
1951   _rem_set_iterator = iter_arr;
1952 
1953   clear_cset_start_regions();
1954 
1955   // Initialize the G1EvacuationFailureALot counters and flags.
1956   NOT_PRODUCT(reset_evacuation_should_fail();)
1957 
1958   guarantee(_task_queues != NULL, "task_queues allocation failure.");
1959 }
1960 
1961 jint G1CollectedHeap::initialize() {
1962   CollectedHeap::pre_initialize();
1963   os::enable_vtime();
1964 
1965   G1Log::init();
1966 
1967   // Necessary to satisfy locking discipline assertions.
1968 
1969   MutexLocker x(Heap_lock);
1970 
1971   // We have to initialize the printer before committing the heap, as
1972   // it will be used then.
1973   _hr_printer.set_active(G1PrintHeapRegions);
1974 
1975   // While there are no constraints in the GC code that HeapWordSize
1976   // be any particular value, there are multiple other areas in the
1977   // system which believe this to be true (e.g. oop->object_size in some
1978   // cases incorrectly returns the size in wordSize units rather than
1979   // HeapWordSize).
1980   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1981 
1982   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
1983   size_t max_byte_size = collector_policy()->max_heap_byte_size();
1984   size_t heap_alignment = collector_policy()->max_alignment();
1985 
1986   // Ensure that the sizes are properly aligned.
1987   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1988   Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
1989   Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap");
1990 
1991   _cg1r = new ConcurrentG1Refine(this);
1992 
1993   // Reserve the maximum.
1994   PermanentGenerationSpec* pgs = collector_policy()->permanent_generation();
1995   // Includes the perm-gen.
1996 
1997   // When compressed oops are enabled, the preferred heap base
1998   // is calculated by subtracting the requested size from the
1999   // 32Gb boundary and using the result as the base address for
2000   // heap reservation. If the requested size is not aligned to
2001   // HeapRegion::GrainBytes (i.e. the alignment that is passed
2002   // into the ReservedHeapSpace constructor) then the actual
2003   // base of the reserved heap may end up differing from the
2004   // address that was requested (i.e. the preferred heap base).
2005   // If this happens then we could end up using a non-optimal
2006   // compressed oops mode.
2007 
2008   // Since max_byte_size is aligned to the size of a heap region (checked
2009   // above), we also need to align the perm gen size as it might not be.
2010   size_t total_reserved = 0;
2011 
2012   total_reserved = add_and_check_overflow(total_reserved, max_byte_size);
2013   size_t pg_max_size = (size_t) align_size_up(pgs->max_size(), heap_alignment);
2014   total_reserved = add_and_check_overflow(total_reserved, pg_max_size);
2015 
2016   Universe::check_alignment(total_reserved, HeapRegion::GrainBytes, "g1 heap and perm");
2017 
2018   char* addr = Universe::preferred_heap_base(total_reserved, heap_alignment, Universe::UnscaledNarrowOop);
2019 
2020   ReservedHeapSpace heap_rs(total_reserved, heap_alignment,
2021                             UseLargePages, addr);
2022 
2023   if (UseCompressedOops) {
2024     if (addr != NULL && !heap_rs.is_reserved()) {
2025       // Failed to reserve at specified address - the requested memory
2026       // region is taken already, for example, by 'java' launcher.
2027       // Try again to reserver heap higher.
2028       addr = Universe::preferred_heap_base(total_reserved, heap_alignment, Universe::ZeroBasedNarrowOop);
2029 
2030       ReservedHeapSpace heap_rs0(total_reserved, heap_alignment,
2031                                  UseLargePages, addr);
2032 
2033       if (addr != NULL && !heap_rs0.is_reserved()) {
2034         // Failed to reserve at specified address again - give up.
2035         addr = Universe::preferred_heap_base(total_reserved, heap_alignment, Universe::HeapBasedNarrowOop);
2036         assert(addr == NULL, "");
2037 
2038         ReservedHeapSpace heap_rs1(total_reserved, heap_alignment,
2039                                    UseLargePages, addr);
2040         heap_rs = heap_rs1;
2041       } else {
2042         heap_rs = heap_rs0;
2043       }
2044     }
2045   }
2046 
2047   if (!heap_rs.is_reserved()) {
2048     vm_exit_during_initialization("Could not reserve enough space for object heap");
2049     return JNI_ENOMEM;
2050   }
2051 
2052   // It is important to do this in a way such that concurrent readers can't
2053   // temporarily think something is in the heap.  (I've actually seen this
2054   // happen in asserts: DLD.)
2055   _reserved.set_word_size(0);
2056   _reserved.set_start((HeapWord*)heap_rs.base());
2057   _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
2058 
2059   _expansion_regions = (uint) (max_byte_size / HeapRegion::GrainBytes);
2060 
2061   // Create the gen rem set (and barrier set) for the entire reserved region.
2062   _rem_set = collector_policy()->create_rem_set(_reserved, 2);
2063   set_barrier_set(rem_set()->bs());
2064   if (!barrier_set()->is_a(BarrierSet::G1SATBCTLogging)) {
2065     vm_exit_during_initialization("G1 requires a G1SATBLoggingCardTableModRefBS");
2066     return JNI_ENOMEM;
2067   }
2068 
2069   // Also create a G1 rem set.
2070   _g1_rem_set = new G1RemSet(this, g1_barrier_set());
2071 
2072   // Carve out the G1 part of the heap.
2073 
2074   ReservedSpace g1_rs   = heap_rs.first_part(max_byte_size);
2075   _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
2076                            g1_rs.size()/HeapWordSize);
2077   ReservedSpace perm_gen_rs = heap_rs.last_part(max_byte_size);
2078 
2079   _perm_gen = pgs->init(perm_gen_rs, pgs->init_size(), rem_set());
2080 
2081   _g1_storage.initialize(g1_rs, 0);
2082   _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
2083   _hrs.initialize((HeapWord*) _g1_reserved.start(),
2084                   (HeapWord*) _g1_reserved.end(),
2085                   _expansion_regions);
2086 
2087   // Do later initialization work for concurrent refinement.
2088   _cg1r->init();
2089 
2090   // 6843694 - ensure that the maximum region index can fit
2091   // in the remembered set structures.
2092   const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
2093   guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
2094 
2095   size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
2096   guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
2097   guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
2098             "too many cards per region");
2099 
2100   HeapRegionSet::set_unrealistically_long_length(max_regions() + 1);
2101 
2102   _bot_shared = new G1BlockOffsetSharedArray(_reserved,
2103                                              heap_word_size(init_byte_size));
2104 
2105   _g1h = this;
2106 
2107   _in_cset_fast_test_length = max_regions();
2108   _in_cset_fast_test_base =
2109                    NEW_C_HEAP_ARRAY(bool, (size_t) _in_cset_fast_test_length, mtGC);
2110 
2111   // We're biasing _in_cset_fast_test to avoid subtracting the
2112   // beginning of the heap every time we want to index; basically
2113   // it's the same with what we do with the card table.
2114   _in_cset_fast_test = _in_cset_fast_test_base -
2115                ((uintx) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
2116 
2117   // Clear the _cset_fast_test bitmap in anticipation of adding
2118   // regions to the incremental collection set for the first
2119   // evacuation pause.
2120   clear_cset_fast_test();
2121 
2122   // Create the ConcurrentMark data structure and thread.
2123   // (Must do this late, so that "max_regions" is defined.)
2124   _cm       = new ConcurrentMark(heap_rs, max_regions());
2125   _cmThread = _cm->cmThread();
2126 
2127   // Initialize the from_card cache structure of HeapRegionRemSet.
2128   HeapRegionRemSet::init_heap(max_regions());
2129 
2130   // Now expand into the initial heap size.
2131   if (!expand(init_byte_size)) {
2132     vm_exit_during_initialization("Failed to allocate initial heap.");
2133     return JNI_ENOMEM;
2134   }
2135 
2136   // Perform any initialization actions delegated to the policy.
2137   g1_policy()->init();
2138 
2139   _refine_cte_cl =
2140     new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
2141                                     g1_rem_set(),
2142                                     concurrent_g1_refine());
2143   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
2144 
2145   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
2146                                                SATB_Q_FL_lock,
2147                                                G1SATBProcessCompletedThreshold,
2148                                                Shared_SATB_Q_lock);
2149 
2150   JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
2151                                                 DirtyCardQ_FL_lock,
2152                                                 concurrent_g1_refine()->yellow_zone(),
2153                                                 concurrent_g1_refine()->red_zone(),
2154                                                 Shared_DirtyCardQ_lock);
2155 
2156   if (G1DeferredRSUpdate) {
2157     dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
2158                                       DirtyCardQ_FL_lock,
2159                                       -1, // never trigger processing
2160                                       -1, // no limit on length
2161                                       Shared_DirtyCardQ_lock,
2162                                       &JavaThread::dirty_card_queue_set());
2163   }
2164 
2165   // Initialize the card queue set used to hold cards containing
2166   // references into the collection set.
2167   _into_cset_dirty_card_queue_set.initialize(DirtyCardQ_CBL_mon,
2168                                              DirtyCardQ_FL_lock,
2169                                              -1, // never trigger processing
2170                                              -1, // no limit on length
2171                                              Shared_DirtyCardQ_lock,
2172                                              &JavaThread::dirty_card_queue_set());
2173 
2174   // In case we're keeping closure specialization stats, initialize those
2175   // counts and that mechanism.
2176   SpecializationStats::clear();
2177 
2178   // Here we allocate the dummy full region that is required by the
2179   // G1AllocRegion class. If we don't pass an address in the reserved
2180   // space here, lots of asserts fire.
2181 
2182   HeapRegion* dummy_region = new_heap_region(0 /* index of bottom region */,
2183                                              _g1_reserved.start());
2184   // We'll re-use the same region whether the alloc region will
2185   // require BOT updates or not and, if it doesn't, then a non-young
2186   // region will complain that it cannot support allocations without
2187   // BOT updates. So we'll tag the dummy region as young to avoid that.
2188   dummy_region->set_young();
2189   // Make sure it's full.
2190   dummy_region->set_top(dummy_region->end());
2191   G1AllocRegion::setup(this, dummy_region);
2192 
2193   init_mutator_alloc_region();
2194 
2195   // Do create of the monitoring and management support so that
2196   // values in the heap have been properly initialized.
2197   _g1mm = new G1MonitoringSupport(this);
2198 
2199   return JNI_OK;
2200 }
2201 
2202 void G1CollectedHeap::ref_processing_init() {
2203   // Reference processing in G1 currently works as follows:
2204   //
2205   // * There are two reference processor instances. One is
2206   //   used to record and process discovered references
2207   //   during concurrent marking; the other is used to
2208   //   record and process references during STW pauses
2209   //   (both full and incremental).
2210   // * Both ref processors need to 'span' the entire heap as
2211   //   the regions in the collection set may be dotted around.
2212   //
2213   // * For the concurrent marking ref processor:
2214   //   * Reference discovery is enabled at initial marking.
2215   //   * Reference discovery is disabled and the discovered
2216   //     references processed etc during remarking.
2217   //   * Reference discovery is MT (see below).
2218   //   * Reference discovery requires a barrier (see below).
2219   //   * Reference processing may or may not be MT
2220   //     (depending on the value of ParallelRefProcEnabled
2221   //     and ParallelGCThreads).
2222   //   * A full GC disables reference discovery by the CM
2223   //     ref processor and abandons any entries on it's
2224   //     discovered lists.
2225   //
2226   // * For the STW processor:
2227   //   * Non MT discovery is enabled at the start of a full GC.
2228   //   * Processing and enqueueing during a full GC is non-MT.
2229   //   * During a full GC, references are processed after marking.
2230   //
2231   //   * Discovery (may or may not be MT) is enabled at the start
2232   //     of an incremental evacuation pause.
2233   //   * References are processed near the end of a STW evacuation pause.
2234   //   * For both types of GC:
2235   //     * Discovery is atomic - i.e. not concurrent.
2236   //     * Reference discovery will not need a barrier.
2237 
2238   SharedHeap::ref_processing_init();
2239   MemRegion mr = reserved_region();
2240 
2241   // Concurrent Mark ref processor
2242   _ref_processor_cm =
2243     new ReferenceProcessor(mr,    // span
2244                            ParallelRefProcEnabled && (ParallelGCThreads > 1),
2245                                 // mt processing
2246                            (int) ParallelGCThreads,
2247                                 // degree of mt processing
2248                            (ParallelGCThreads > 1) || (ConcGCThreads > 1),
2249                                 // mt discovery
2250                            (int) MAX2(ParallelGCThreads, ConcGCThreads),
2251                                 // degree of mt discovery
2252                            false,
2253                                 // Reference discovery is not atomic
2254                            &_is_alive_closure_cm,
2255                                 // is alive closure
2256                                 // (for efficiency/performance)
2257                            true);
2258                                 // Setting next fields of discovered
2259                                 // lists requires a barrier.
2260 
2261   // STW ref processor
2262   _ref_processor_stw =
2263     new ReferenceProcessor(mr,    // span
2264                            ParallelRefProcEnabled && (ParallelGCThreads > 1),
2265                                 // mt processing
2266                            MAX2((int)ParallelGCThreads, 1),
2267                                 // degree of mt processing
2268                            (ParallelGCThreads > 1),
2269                                 // mt discovery
2270                            MAX2((int)ParallelGCThreads, 1),
2271                                 // degree of mt discovery
2272                            true,
2273                                 // Reference discovery is atomic
2274                            &_is_alive_closure_stw,
2275                                 // is alive closure
2276                                 // (for efficiency/performance)
2277                            false);
2278                                 // Setting next fields of discovered
2279                                 // lists requires a barrier.
2280 }
2281 
2282 size_t G1CollectedHeap::capacity() const {
2283   return _g1_committed.byte_size();
2284 }
2285 
2286 void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) {
2287   assert(!hr->continuesHumongous(), "pre-condition");
2288   hr->reset_gc_time_stamp();
2289   if (hr->startsHumongous()) {
2290     uint first_index = hr->hrs_index() + 1;
2291     uint last_index = hr->last_hc_index();
2292     for (uint i = first_index; i < last_index; i += 1) {
2293       HeapRegion* chr = region_at(i);
2294       assert(chr->continuesHumongous(), "sanity");
2295       chr->reset_gc_time_stamp();
2296     }
2297   }
2298 }
2299 
2300 #ifndef PRODUCT
2301 class CheckGCTimeStampsHRClosure : public HeapRegionClosure {
2302 private:
2303   unsigned _gc_time_stamp;
2304   bool _failures;
2305 
2306 public:
2307   CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) :
2308     _gc_time_stamp(gc_time_stamp), _failures(false) { }
2309 
2310   virtual bool doHeapRegion(HeapRegion* hr) {
2311     unsigned region_gc_time_stamp = hr->get_gc_time_stamp();
2312     if (_gc_time_stamp != region_gc_time_stamp) {
2313       gclog_or_tty->print_cr("Region "HR_FORMAT" has GC time stamp = %d, "
2314                              "expected %d", HR_FORMAT_PARAMS(hr),
2315                              region_gc_time_stamp, _gc_time_stamp);
2316       _failures = true;
2317     }
2318     return false;
2319   }
2320 
2321   bool failures() { return _failures; }
2322 };
2323 
2324 void G1CollectedHeap::check_gc_time_stamps() {
2325   CheckGCTimeStampsHRClosure cl(_gc_time_stamp);
2326   heap_region_iterate(&cl);
2327   guarantee(!cl.failures(), "all GC time stamps should have been reset");
2328 }
2329 #endif // PRODUCT
2330 
2331 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,
2332                                                  DirtyCardQueue* into_cset_dcq,
2333                                                  bool concurrent,
2334                                                  int worker_i) {
2335   // Clean cards in the hot card cache
2336   G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
2337   hot_card_cache->drain(worker_i, g1_rem_set(), into_cset_dcq);
2338 
2339   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2340   int n_completed_buffers = 0;
2341   while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {
2342     n_completed_buffers++;
2343   }
2344   g1_policy()->phase_times()->record_update_rs_processed_buffers(worker_i, n_completed_buffers);
2345   dcqs.clear_n_completed_buffers();
2346   assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
2347 }
2348 
2349 
2350 // Computes the sum of the storage used by the various regions.
2351 
2352 size_t G1CollectedHeap::used() const {
2353   assert(Heap_lock->owner() != NULL,
2354          "Should be owned on this thread's behalf.");
2355   size_t result = _summary_bytes_used;
2356   // Read only once in case it is set to NULL concurrently
2357   HeapRegion* hr = _mutator_alloc_region.get();
2358   if (hr != NULL)
2359     result += hr->used();
2360   return result;
2361 }
2362 
2363 size_t G1CollectedHeap::used_unlocked() const {
2364   size_t result = _summary_bytes_used;
2365   return result;
2366 }
2367 
2368 class SumUsedClosure: public HeapRegionClosure {
2369   size_t _used;
2370 public:
2371   SumUsedClosure() : _used(0) {}
2372   bool doHeapRegion(HeapRegion* r) {
2373     if (!r->continuesHumongous()) {
2374       _used += r->used();
2375     }
2376     return false;
2377   }
2378   size_t result() { return _used; }
2379 };
2380 
2381 size_t G1CollectedHeap::recalculate_used() const {
2382   SumUsedClosure blk;
2383   heap_region_iterate(&blk);
2384   return blk.result();
2385 }
2386 
2387 size_t G1CollectedHeap::unsafe_max_alloc() {
2388   if (free_regions() > 0) return HeapRegion::GrainBytes;
2389   // otherwise, is there space in the current allocation region?
2390 
2391   // We need to store the current allocation region in a local variable
2392   // here. The problem is that this method doesn't take any locks and
2393   // there may be other threads which overwrite the current allocation
2394   // region field. attempt_allocation(), for example, sets it to NULL
2395   // and this can happen *after* the NULL check here but before the call
2396   // to free(), resulting in a SIGSEGV. Note that this doesn't appear
2397   // to be a problem in the optimized build, since the two loads of the
2398   // current allocation region field are optimized away.
2399   HeapRegion* hr = _mutator_alloc_region.get();
2400   if (hr == NULL) {
2401     return 0;
2402   }
2403   return hr->free();
2404 }
2405 
2406 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
2407   switch (cause) {
2408     case GCCause::_gc_locker:               return GCLockerInvokesConcurrent;
2409     case GCCause::_java_lang_system_gc:     return ExplicitGCInvokesConcurrent;
2410     case GCCause::_g1_humongous_allocation: return true;
2411     default:                                return false;
2412   }
2413 }
2414 
2415 #ifndef PRODUCT
2416 void G1CollectedHeap::allocate_dummy_regions() {
2417   // Let's fill up most of the region
2418   size_t word_size = HeapRegion::GrainWords - 1024;
2419   // And as a result the region we'll allocate will be humongous.
2420   guarantee(isHumongous(word_size), "sanity");
2421 
2422   for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
2423     // Let's use the existing mechanism for the allocation
2424     HeapWord* dummy_obj = humongous_obj_allocate(word_size);
2425     if (dummy_obj != NULL) {
2426       MemRegion mr(dummy_obj, word_size);
2427       CollectedHeap::fill_with_object(mr);
2428     } else {
2429       // If we can't allocate once, we probably cannot allocate
2430       // again. Let's get out of the loop.
2431       break;
2432     }
2433   }
2434 }
2435 #endif // !PRODUCT
2436 
2437 void G1CollectedHeap::increment_old_marking_cycles_started() {
2438   assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
2439     _old_marking_cycles_started == _old_marking_cycles_completed + 1,
2440     err_msg("Wrong marking cycle count (started: %d, completed: %d)",
2441     _old_marking_cycles_started, _old_marking_cycles_completed));
2442 
2443   _old_marking_cycles_started++;
2444 }
2445 
2446 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) {
2447   MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
2448 
2449   // We assume that if concurrent == true, then the caller is a
2450   // concurrent thread that was joined the Suspendible Thread
2451   // Set. If there's ever a cheap way to check this, we should add an
2452   // assert here.
2453 
2454   // Given that this method is called at the end of a Full GC or of a
2455   // concurrent cycle, and those can be nested (i.e., a Full GC can
2456   // interrupt a concurrent cycle), the number of full collections
2457   // completed should be either one (in the case where there was no
2458   // nesting) or two (when a Full GC interrupted a concurrent cycle)
2459   // behind the number of full collections started.
2460 
2461   // This is the case for the inner caller, i.e. a Full GC.
2462   assert(concurrent ||
2463          (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
2464          (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
2465          err_msg("for inner caller (Full GC): _old_marking_cycles_started = %u "
2466                  "is inconsistent with _old_marking_cycles_completed = %u",
2467                  _old_marking_cycles_started, _old_marking_cycles_completed));
2468 
2469   // This is the case for the outer caller, i.e. the concurrent cycle.
2470   assert(!concurrent ||
2471          (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
2472          err_msg("for outer caller (concurrent cycle): "
2473                  "_old_marking_cycles_started = %u "
2474                  "is inconsistent with _old_marking_cycles_completed = %u",
2475                  _old_marking_cycles_started, _old_marking_cycles_completed));
2476 
2477   _old_marking_cycles_completed += 1;
2478 
2479   // We need to clear the "in_progress" flag in the CM thread before
2480   // we wake up any waiters (especially when ExplicitInvokesConcurrent
2481   // is set) so that if a waiter requests another System.gc() it doesn't
2482   // incorrectly see that a marking cycle is still in progress.
2483   if (concurrent) {
2484     _cmThread->clear_in_progress();
2485   }
2486 
2487   // This notify_all() will ensure that a thread that called
2488   // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
2489   // and it's waiting for a full GC to finish will be woken up. It is
2490   // waiting in VM_G1IncCollectionPause::doit_epilogue().
2491   FullGCCount_lock->notify_all();
2492 }
2493 
2494 void G1CollectedHeap::register_concurrent_cycle_start(const Ticks& start_time) {
2495   _concurrent_cycle_started = true;
2496   _gc_timer_cm->register_gc_start(start_time);
2497 
2498   _gc_tracer_cm->report_gc_start(gc_cause(), _gc_timer_cm->gc_start());
2499   trace_heap_before_gc(_gc_tracer_cm);
2500 }
2501 
2502 void G1CollectedHeap::register_concurrent_cycle_end() {
2503   if (_concurrent_cycle_started) {
2504     _gc_timer_cm->register_gc_end();
2505 
2506     if (_cm->has_aborted()) {
2507       _gc_tracer_cm->report_concurrent_mode_failure();
2508     }
2509     _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
2510 
2511     _concurrent_cycle_started = false;
2512   }
2513 }
2514 
2515 void G1CollectedHeap::trace_heap_after_concurrent_cycle() {
2516   if (_concurrent_cycle_started) {
2517     trace_heap_after_gc(_gc_tracer_cm);
2518   }
2519 }
2520 
2521 G1YCType G1CollectedHeap::yc_type() {
2522   bool is_young = g1_policy()->gcs_are_young();
2523   bool is_initial_mark = g1_policy()->during_initial_mark_pause();
2524   bool is_during_mark = mark_in_progress();
2525 
2526   if (is_initial_mark) {
2527     return InitialMark;
2528   } else if (is_during_mark) {
2529     return DuringMark;
2530   } else if (is_young) {
2531     return Normal;
2532   } else {
2533     return Mixed;
2534   }
2535 }
2536 
2537 void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
2538   assert_at_safepoint(true /* should_be_vm_thread */);
2539   GCCauseSetter gcs(this, cause);
2540   switch (cause) {
2541     case GCCause::_heap_inspection:
2542     case GCCause::_heap_dump: {
2543       HandleMark hm;
2544       do_full_collection(false);         // don't clear all soft refs
2545       break;
2546     }
2547     default: // XXX FIX ME
2548       ShouldNotReachHere(); // Unexpected use of this function
2549   }
2550 }
2551 
2552 void G1CollectedHeap::collect(GCCause::Cause cause) {
2553   assert_heap_not_locked();
2554 
2555   unsigned int gc_count_before;
2556   unsigned int old_marking_count_before;
2557   bool retry_gc;
2558 
2559   do {
2560     retry_gc = false;
2561 
2562     {
2563       MutexLocker ml(Heap_lock);
2564 
2565       // Read the GC count while holding the Heap_lock
2566       gc_count_before = total_collections();
2567       old_marking_count_before = _old_marking_cycles_started;
2568     }
2569 
2570     if (should_do_concurrent_full_gc(cause)) {
2571       // Schedule an initial-mark evacuation pause that will start a
2572       // concurrent cycle. We're setting word_size to 0 which means that
2573       // we are not requesting a post-GC allocation.
2574       VM_G1IncCollectionPause op(gc_count_before,
2575                                  0,     /* word_size */
2576                                  true,  /* should_initiate_conc_mark */
2577                                  g1_policy()->max_pause_time_ms(),
2578                                  cause);
2579 
2580       VMThread::execute(&op);
2581       if (!op.pause_succeeded()) {
2582         if (old_marking_count_before == _old_marking_cycles_started) {
2583           retry_gc = op.should_retry_gc();
2584         } else {
2585           // A Full GC happened while we were trying to schedule the
2586           // initial-mark GC. No point in starting a new cycle given
2587           // that the whole heap was collected anyway.
2588         }
2589 
2590         if (retry_gc) {
2591           if (GC_locker::is_active_and_needs_gc()) {
2592             GC_locker::stall_until_clear();
2593           }
2594         }
2595       }
2596     } else {
2597       if (cause == GCCause::_gc_locker
2598           DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2599 
2600         // Schedule a standard evacuation pause. We're setting word_size
2601         // to 0 which means that we are not requesting a post-GC allocation.
2602         VM_G1IncCollectionPause op(gc_count_before,
2603                                    0,     /* word_size */
2604                                    false, /* should_initiate_conc_mark */
2605                                    g1_policy()->max_pause_time_ms(),
2606                                    cause);
2607         VMThread::execute(&op);
2608       } else {
2609         // Schedule a Full GC.
2610         VM_G1CollectFull op(gc_count_before, old_marking_count_before, cause);
2611         VMThread::execute(&op);
2612       }
2613     }
2614   } while (retry_gc);
2615 }
2616 
2617 bool G1CollectedHeap::is_in(const void* p) const {
2618   if (_g1_committed.contains(p)) {
2619     // Given that we know that p is in the committed space,
2620     // heap_region_containing_raw() should successfully
2621     // return the containing region.
2622     HeapRegion* hr = heap_region_containing_raw(p);
2623     return hr->is_in(p);
2624   } else {
2625     return _perm_gen->as_gen()->is_in(p);
2626   }
2627 }
2628 
2629 // Iteration functions.
2630 
2631 // Iterates an OopClosure over all ref-containing fields of objects
2632 // within a HeapRegion.
2633 
2634 class IterateOopClosureRegionClosure: public HeapRegionClosure {
2635   MemRegion _mr;
2636   OopClosure* _cl;
2637 public:
2638   IterateOopClosureRegionClosure(MemRegion mr, OopClosure* cl)
2639     : _mr(mr), _cl(cl) {}
2640   bool doHeapRegion(HeapRegion* r) {
2641     if (!r->continuesHumongous()) {
2642       r->oop_iterate(_cl);
2643     }
2644     return false;
2645   }
2646 };
2647 
2648 void G1CollectedHeap::oop_iterate(OopClosure* cl, bool do_perm) {
2649   IterateOopClosureRegionClosure blk(_g1_committed, cl);
2650   heap_region_iterate(&blk);
2651   if (do_perm) {
2652     perm_gen()->oop_iterate(cl);
2653   }
2654 }
2655 
2656 void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl, bool do_perm) {
2657   IterateOopClosureRegionClosure blk(mr, cl);
2658   heap_region_iterate(&blk);
2659   if (do_perm) {
2660     perm_gen()->oop_iterate(cl);
2661   }
2662 }
2663 
2664 // Iterates an ObjectClosure over all objects within a HeapRegion.
2665 
2666 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2667   ObjectClosure* _cl;
2668 public:
2669   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2670   bool doHeapRegion(HeapRegion* r) {
2671     if (! r->continuesHumongous()) {
2672       r->object_iterate(_cl);
2673     }
2674     return false;
2675   }
2676 };
2677 
2678 void G1CollectedHeap::object_iterate(ObjectClosure* cl, bool do_perm) {
2679   IterateObjectClosureRegionClosure blk(cl);
2680   heap_region_iterate(&blk);
2681   if (do_perm) {
2682     perm_gen()->object_iterate(cl);
2683   }
2684 }
2685 
2686 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
2687   // FIXME: is this right?
2688   guarantee(false, "object_iterate_since_last_GC not supported by G1 heap");
2689 }
2690 
2691 // Calls a SpaceClosure on a HeapRegion.
2692 
2693 class SpaceClosureRegionClosure: public HeapRegionClosure {
2694   SpaceClosure* _cl;
2695 public:
2696   SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
2697   bool doHeapRegion(HeapRegion* r) {
2698     _cl->do_space(r);
2699     return false;
2700   }
2701 };
2702 
2703 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
2704   SpaceClosureRegionClosure blk(cl);
2705   heap_region_iterate(&blk);
2706 }
2707 
2708 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2709   _hrs.iterate(cl);
2710 }
2711 
2712 void
2713 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
2714                                                  uint worker_id,
2715                                                  uint no_of_par_workers,
2716                                                  jint claim_value) {
2717   const uint regions = n_regions();
2718   const uint max_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
2719                              no_of_par_workers :
2720                              1);
2721   assert(UseDynamicNumberOfGCThreads ||
2722          no_of_par_workers == workers()->total_workers(),
2723          "Non dynamic should use fixed number of workers");
2724   // try to spread out the starting points of the workers
2725   const HeapRegion* start_hr =
2726                         start_region_for_worker(worker_id, no_of_par_workers);
2727   const uint start_index = start_hr->hrs_index();
2728 
2729   // each worker will actually look at all regions
2730   for (uint count = 0; count < regions; ++count) {
2731     const uint index = (start_index + count) % regions;
2732     assert(0 <= index && index < regions, "sanity");
2733     HeapRegion* r = region_at(index);
2734     // we'll ignore "continues humongous" regions (we'll process them
2735     // when we come across their corresponding "start humongous"
2736     // region) and regions already claimed
2737     if (r->claim_value() == claim_value || r->continuesHumongous()) {
2738       continue;
2739     }
2740     // OK, try to claim it
2741     if (r->claimHeapRegion(claim_value)) {
2742       // success!
2743       assert(!r->continuesHumongous(), "sanity");
2744       if (r->startsHumongous()) {
2745         // If the region is "starts humongous" we'll iterate over its
2746         // "continues humongous" first; in fact we'll do them
2747         // first. The order is important. In on case, calling the
2748         // closure on the "starts humongous" region might de-allocate
2749         // and clear all its "continues humongous" regions and, as a
2750         // result, we might end up processing them twice. So, we'll do
2751         // them first (notice: most closures will ignore them anyway) and
2752         // then we'll do the "starts humongous" region.
2753         for (uint ch_index = index + 1; ch_index < regions; ++ch_index) {
2754           HeapRegion* chr = region_at(ch_index);
2755 
2756           // if the region has already been claimed or it's not
2757           // "continues humongous" we're done
2758           if (chr->claim_value() == claim_value ||
2759               !chr->continuesHumongous()) {
2760             break;
2761           }
2762 
2763           // Noone should have claimed it directly. We can given
2764           // that we claimed its "starts humongous" region.
2765           assert(chr->claim_value() != claim_value, "sanity");
2766           assert(chr->humongous_start_region() == r, "sanity");
2767 
2768           if (chr->claimHeapRegion(claim_value)) {
2769             // we should always be able to claim it; noone else should
2770             // be trying to claim this region
2771 
2772             bool res2 = cl->doHeapRegion(chr);
2773             assert(!res2, "Should not abort");
2774 
2775             // Right now, this holds (i.e., no closure that actually
2776             // does something with "continues humongous" regions
2777             // clears them). We might have to weaken it in the future,
2778             // but let's leave these two asserts here for extra safety.
2779             assert(chr->continuesHumongous(), "should still be the case");
2780             assert(chr->humongous_start_region() == r, "sanity");
2781           } else {
2782             guarantee(false, "we should not reach here");
2783           }
2784         }
2785       }
2786 
2787       assert(!r->continuesHumongous(), "sanity");
2788       bool res = cl->doHeapRegion(r);
2789       assert(!res, "Should not abort");
2790     }
2791   }
2792 }
2793 
2794 class ResetClaimValuesClosure: public HeapRegionClosure {
2795 public:
2796   bool doHeapRegion(HeapRegion* r) {
2797     r->set_claim_value(HeapRegion::InitialClaimValue);
2798     return false;
2799   }
2800 };
2801 
2802 void G1CollectedHeap::reset_heap_region_claim_values() {
2803   ResetClaimValuesClosure blk;
2804   heap_region_iterate(&blk);
2805 }
2806 
2807 void G1CollectedHeap::reset_cset_heap_region_claim_values() {
2808   ResetClaimValuesClosure blk;
2809   collection_set_iterate(&blk);
2810 }
2811 
2812 #ifdef ASSERT
2813 // This checks whether all regions in the heap have the correct claim
2814 // value. I also piggy-backed on this a check to ensure that the
2815 // humongous_start_region() information on "continues humongous"
2816 // regions is correct.
2817 
2818 class CheckClaimValuesClosure : public HeapRegionClosure {
2819 private:
2820   jint _claim_value;
2821   uint _failures;
2822   HeapRegion* _sh_region;
2823 
2824 public:
2825   CheckClaimValuesClosure(jint claim_value) :
2826     _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
2827   bool doHeapRegion(HeapRegion* r) {
2828     if (r->claim_value() != _claim_value) {
2829       gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2830                              "claim value = %d, should be %d",
2831                              HR_FORMAT_PARAMS(r),
2832                              r->claim_value(), _claim_value);
2833       ++_failures;
2834     }
2835     if (!r->isHumongous()) {
2836       _sh_region = NULL;
2837     } else if (r->startsHumongous()) {
2838       _sh_region = r;
2839     } else if (r->continuesHumongous()) {
2840       if (r->humongous_start_region() != _sh_region) {
2841         gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2842                                "HS = "PTR_FORMAT", should be "PTR_FORMAT,
2843                                HR_FORMAT_PARAMS(r),
2844                                r->humongous_start_region(),
2845                                _sh_region);
2846         ++_failures;
2847       }
2848     }
2849     return false;
2850   }
2851   uint failures() { return _failures; }
2852 };
2853 
2854 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
2855   CheckClaimValuesClosure cl(claim_value);
2856   heap_region_iterate(&cl);
2857   return cl.failures() == 0;
2858 }
2859 
2860 class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {
2861 private:
2862   jint _claim_value;
2863   uint _failures;
2864 
2865 public:
2866   CheckClaimValuesInCSetHRClosure(jint claim_value) :
2867     _claim_value(claim_value), _failures(0) { }
2868 
2869   uint failures() { return _failures; }
2870 
2871   bool doHeapRegion(HeapRegion* hr) {
2872     assert(hr->in_collection_set(), "how?");
2873     assert(!hr->isHumongous(), "H-region in CSet");
2874     if (hr->claim_value() != _claim_value) {
2875       gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "
2876                              "claim value = %d, should be %d",
2877                              HR_FORMAT_PARAMS(hr),
2878                              hr->claim_value(), _claim_value);
2879       _failures += 1;
2880     }
2881     return false;
2882   }
2883 };
2884 
2885 bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {
2886   CheckClaimValuesInCSetHRClosure cl(claim_value);
2887   collection_set_iterate(&cl);
2888   return cl.failures() == 0;
2889 }
2890 #endif // ASSERT
2891 
2892 // Clear the cached CSet starting regions and (more importantly)
2893 // the time stamps. Called when we reset the GC time stamp.
2894 void G1CollectedHeap::clear_cset_start_regions() {
2895   assert(_worker_cset_start_region != NULL, "sanity");
2896   assert(_worker_cset_start_region_time_stamp != NULL, "sanity");
2897 
2898   int n_queues = MAX2((int)ParallelGCThreads, 1);
2899   for (int i = 0; i < n_queues; i++) {
2900     _worker_cset_start_region[i] = NULL;
2901     _worker_cset_start_region_time_stamp[i] = 0;
2902   }
2903 }
2904 
2905 // Given the id of a worker, obtain or calculate a suitable
2906 // starting region for iterating over the current collection set.
2907 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(int worker_i) {
2908   assert(get_gc_time_stamp() > 0, "should have been updated by now");
2909 
2910   HeapRegion* result = NULL;
2911   unsigned gc_time_stamp = get_gc_time_stamp();
2912 
2913   if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) {
2914     // Cached starting region for current worker was set
2915     // during the current pause - so it's valid.
2916     // Note: the cached starting heap region may be NULL
2917     // (when the collection set is empty).
2918     result = _worker_cset_start_region[worker_i];
2919     assert(result == NULL || result->in_collection_set(), "sanity");
2920     return result;
2921   }
2922 
2923   // The cached entry was not valid so let's calculate
2924   // a suitable starting heap region for this worker.
2925 
2926   // We want the parallel threads to start their collection
2927   // set iteration at different collection set regions to
2928   // avoid contention.
2929   // If we have:
2930   //          n collection set regions
2931   //          p threads
2932   // Then thread t will start at region floor ((t * n) / p)
2933 
2934   result = g1_policy()->collection_set();
2935   if (G1CollectedHeap::use_parallel_gc_threads()) {
2936     uint cs_size = g1_policy()->cset_region_length();
2937     uint active_workers = workers()->active_workers();
2938     assert(UseDynamicNumberOfGCThreads ||
2939              active_workers == workers()->total_workers(),
2940              "Unless dynamic should use total workers");
2941 
2942     uint end_ind   = (cs_size * worker_i) / active_workers;
2943     uint start_ind = 0;
2944 
2945     if (worker_i > 0 &&
2946         _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) {
2947       // Previous workers starting region is valid
2948       // so let's iterate from there
2949       start_ind = (cs_size * (worker_i - 1)) / active_workers;
2950       result = _worker_cset_start_region[worker_i - 1];
2951     }
2952 
2953     for (uint i = start_ind; i < end_ind; i++) {
2954       result = result->next_in_collection_set();
2955     }
2956   }
2957 
2958   // Note: the calculated starting heap region may be NULL
2959   // (when the collection set is empty).
2960   assert(result == NULL || result->in_collection_set(), "sanity");
2961   assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp,
2962          "should be updated only once per pause");
2963   _worker_cset_start_region[worker_i] = result;
2964   OrderAccess::storestore();
2965   _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp;
2966   return result;
2967 }
2968 
2969 HeapRegion* G1CollectedHeap::start_region_for_worker(uint worker_i,
2970                                                      uint no_of_par_workers) {
2971   uint worker_num =
2972            G1CollectedHeap::use_parallel_gc_threads() ? no_of_par_workers : 1U;
2973   assert(UseDynamicNumberOfGCThreads ||
2974          no_of_par_workers == workers()->total_workers(),
2975          "Non dynamic should use fixed number of workers");
2976   const uint start_index = n_regions() * worker_i / worker_num;
2977   return region_at(start_index);
2978 }
2979 
2980 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
2981   HeapRegion* r = g1_policy()->collection_set();
2982   while (r != NULL) {
2983     HeapRegion* next = r->next_in_collection_set();
2984     if (cl->doHeapRegion(r)) {
2985       cl->incomplete();
2986       return;
2987     }
2988     r = next;
2989   }
2990 }
2991 
2992 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
2993                                                   HeapRegionClosure *cl) {
2994   if (r == NULL) {
2995     // The CSet is empty so there's nothing to do.
2996     return;
2997   }
2998 
2999   assert(r->in_collection_set(),
3000          "Start region must be a member of the collection set.");
3001   HeapRegion* cur = r;
3002   while (cur != NULL) {
3003     HeapRegion* next = cur->next_in_collection_set();
3004     if (cl->doHeapRegion(cur) && false) {
3005       cl->incomplete();
3006       return;
3007     }
3008     cur = next;
3009   }
3010   cur = g1_policy()->collection_set();
3011   while (cur != r) {
3012     HeapRegion* next = cur->next_in_collection_set();
3013     if (cl->doHeapRegion(cur) && false) {
3014       cl->incomplete();
3015       return;
3016     }
3017     cur = next;
3018   }
3019 }
3020 
3021 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
3022   return n_regions() > 0 ? region_at(0) : NULL;
3023 }
3024 
3025 
3026 Space* G1CollectedHeap::space_containing(const void* addr) const {
3027   Space* res = heap_region_containing(addr);
3028   if (res == NULL)
3029     res = perm_gen()->space_containing(addr);
3030   return res;
3031 }
3032 
3033 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
3034   Space* sp = space_containing(addr);
3035   if (sp != NULL) {
3036     return sp->block_start(addr);
3037   }
3038   return NULL;
3039 }
3040 
3041 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
3042   Space* sp = space_containing(addr);
3043   assert(sp != NULL, "block_size of address outside of heap");
3044   return sp->block_size(addr);
3045 }
3046 
3047 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
3048   Space* sp = space_containing(addr);
3049   return sp->block_is_obj(addr);
3050 }
3051 
3052 bool G1CollectedHeap::supports_tlab_allocation() const {
3053   return true;
3054 }
3055 
3056 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
3057   return HeapRegion::GrainBytes;
3058 }
3059 
3060 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
3061   // Return the remaining space in the cur alloc region, but not less than
3062   // the min TLAB size.
3063 
3064   // Also, this value can be at most the humongous object threshold,
3065   // since we can't allow tlabs to grow big enough to accommodate
3066   // humongous objects.
3067 
3068   HeapRegion* hr = _mutator_alloc_region.get();
3069   size_t max_tlab_size = _humongous_object_threshold_in_words * wordSize;
3070   if (hr == NULL) {
3071     return max_tlab_size;
3072   } else {
3073     return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab_size);
3074   }
3075 }
3076 
3077 size_t G1CollectedHeap::max_capacity() const {
3078   return _g1_reserved.byte_size();
3079 }
3080 
3081 jlong G1CollectedHeap::millis_since_last_gc() {
3082   // assert(false, "NYI");
3083   return 0;
3084 }
3085 
3086 void G1CollectedHeap::prepare_for_verify() {
3087   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
3088     ensure_parsability(false);
3089   }
3090   g1_rem_set()->prepare_for_verify();
3091 }
3092 
3093 bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr,
3094                                               VerifyOption vo) {
3095   switch (vo) {
3096   case VerifyOption_G1UsePrevMarking:
3097     return hr->obj_allocated_since_prev_marking(obj);
3098   case VerifyOption_G1UseNextMarking:
3099     return hr->obj_allocated_since_next_marking(obj);
3100   case VerifyOption_G1UseMarkWord:
3101     return false;
3102   default:
3103     ShouldNotReachHere();
3104   }
3105   return false; // keep some compilers happy
3106 }
3107 
3108 HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) {
3109   switch (vo) {
3110   case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start();
3111   case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start();
3112   case VerifyOption_G1UseMarkWord:    return NULL;
3113   default:                            ShouldNotReachHere();
3114   }
3115   return NULL; // keep some compilers happy
3116 }
3117 
3118 bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) {
3119   switch (vo) {
3120   case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj);
3121   case VerifyOption_G1UseNextMarking: return isMarkedNext(obj);
3122   case VerifyOption_G1UseMarkWord:    return obj->is_gc_marked();
3123   default:                            ShouldNotReachHere();
3124   }
3125   return false; // keep some compilers happy
3126 }
3127 
3128 const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) {
3129   switch (vo) {
3130   case VerifyOption_G1UsePrevMarking: return "PTAMS";
3131   case VerifyOption_G1UseNextMarking: return "NTAMS";
3132   case VerifyOption_G1UseMarkWord:    return "NONE";
3133   default:                            ShouldNotReachHere();
3134   }
3135   return NULL; // keep some compilers happy
3136 }
3137 
3138 // TODO: VerifyRootsClosure extends OopsInGenClosure so that we can
3139 //       pass it as the perm_blk to SharedHeap::process_strong_roots.
3140 //       When process_strong_roots stop calling perm_blk->younger_refs_iterate
3141 //       we can change this closure to extend the simpler OopClosure.
3142 class VerifyRootsClosure: public OopsInGenClosure {
3143 private:
3144   G1CollectedHeap* _g1h;
3145   VerifyOption     _vo;
3146   bool             _failures;
3147 public:
3148   // _vo == UsePrevMarking -> use "prev" marking information,
3149   // _vo == UseNextMarking -> use "next" marking information,
3150   // _vo == UseMarkWord    -> use mark word from object header.
3151   VerifyRootsClosure(VerifyOption vo) :
3152     _g1h(G1CollectedHeap::heap()),
3153     _vo(vo),
3154     _failures(false) { }
3155 
3156   bool failures() { return _failures; }
3157 
3158   template <class T> void do_oop_nv(T* p) {
3159     T heap_oop = oopDesc::load_heap_oop(p);
3160     if (!oopDesc::is_null(heap_oop)) {
3161       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3162       if (_g1h->is_obj_dead_cond(obj, _vo)) {
3163         gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
3164                               "points to dead obj "PTR_FORMAT, p, (void*) obj);
3165         if (_vo == VerifyOption_G1UseMarkWord) {
3166           gclog_or_tty->print_cr("  Mark word: "PTR_FORMAT, (void*)(obj->mark()));
3167         }
3168         obj->print_on(gclog_or_tty);
3169         _failures = true;
3170       }
3171     }
3172   }
3173 
3174   void do_oop(oop* p)       { do_oop_nv(p); }
3175   void do_oop(narrowOop* p) { do_oop_nv(p); }
3176 };
3177 
3178 class G1VerifyCodeRootOopClosure: public OopsInGenClosure {
3179   G1CollectedHeap* _g1h;
3180   OopClosure* _root_cl;
3181   nmethod* _nm;
3182   VerifyOption _vo;
3183   bool _failures;
3184 
3185   template <class T> void do_oop_work(T* p) {
3186     // First verify that this root is live
3187     _root_cl->do_oop(p);
3188 
3189     if (!G1VerifyHeapRegionCodeRoots) {
3190       // We're not verifying the code roots attached to heap region.
3191       return;
3192     }
3193 
3194     // Don't check the code roots during marking verification in a full GC
3195     if (_vo == VerifyOption_G1UseMarkWord) {
3196       return;
3197     }
3198 
3199     // Now verify that the current nmethod (which contains p) is
3200     // in the code root list of the heap region containing the
3201     // object referenced by p.
3202 
3203     T heap_oop = oopDesc::load_heap_oop(p);
3204     if (!oopDesc::is_null(heap_oop)) {
3205       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3206 
3207       if (_g1h->is_in_g1_reserved(obj)) {
3208         // Now fetch the region containing the object
3209         HeapRegion* hr = _g1h->heap_region_containing(obj);
3210         HeapRegionRemSet* hrrs = hr->rem_set();
3211         // Verify that the strong code root list for this region
3212         // contains the nmethod
3213         if (!hrrs->strong_code_roots_list_contains(_nm)) {
3214           gclog_or_tty->print_cr("Code root location "PTR_FORMAT" "
3215                                 "from nmethod "PTR_FORMAT" not in strong "
3216                                 "code roots for region ["PTR_FORMAT","PTR_FORMAT")",
3217                                 p, _nm, hr->bottom(), hr->end());
3218           _failures = true;
3219         }
3220       }
3221     }
3222   }
3223 
3224 public:
3225   G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
3226     _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}
3227 
3228   void do_oop(oop* p) { do_oop_work(p); }
3229   void do_oop(narrowOop* p) { do_oop_work(p); }
3230 
3231   void set_nmethod(nmethod* nm) { _nm = nm; }
3232   bool failures() { return _failures; }
3233 };
3234 
3235 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
3236   G1VerifyCodeRootOopClosure* _oop_cl;
3237 
3238 public:
3239   G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
3240     _oop_cl(oop_cl) {}
3241 
3242   void do_code_blob(CodeBlob* cb) {
3243     nmethod* nm = cb->as_nmethod_or_null();
3244     if (nm != NULL) {
3245       _oop_cl->set_nmethod(nm);
3246       nm->oops_do(_oop_cl);
3247     }
3248   }
3249 };
3250 
3251 class VerifyLivenessOopClosure: public OopClosure {
3252   G1CollectedHeap* _g1h;
3253   VerifyOption _vo;
3254 public:
3255   VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
3256     _g1h(g1h), _vo(vo)
3257   { }
3258   void do_oop(narrowOop *p) { do_oop_work(p); }
3259   void do_oop(      oop *p) { do_oop_work(p); }
3260 
3261   template <class T> void do_oop_work(T *p) {
3262     oop obj = oopDesc::load_decode_heap_oop(p);
3263     guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
3264               "Dead object referenced by a not dead object");
3265   }
3266 };
3267 
3268 class VerifyObjsInRegionClosure: public ObjectClosure {
3269 private:
3270   G1CollectedHeap* _g1h;
3271   size_t _live_bytes;
3272   HeapRegion *_hr;
3273   VerifyOption _vo;
3274 public:
3275   // _vo == UsePrevMarking -> use "prev" marking information,
3276   // _vo == UseNextMarking -> use "next" marking information,
3277   // _vo == UseMarkWord    -> use mark word from object header.
3278   VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
3279     : _live_bytes(0), _hr(hr), _vo(vo) {
3280     _g1h = G1CollectedHeap::heap();
3281   }
3282   void do_object(oop o) {
3283     VerifyLivenessOopClosure isLive(_g1h, _vo);
3284     assert(o != NULL, "Huh?");
3285     if (!_g1h->is_obj_dead_cond(o, _vo)) {
3286       // If the object is alive according to the mark word,
3287       // then verify that the marking information agrees.
3288       // Note we can't verify the contra-positive of the
3289       // above: if the object is dead (according to the mark
3290       // word), it may not be marked, or may have been marked
3291       // but has since became dead, or may have been allocated
3292       // since the last marking.
3293       if (_vo == VerifyOption_G1UseMarkWord) {
3294         guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
3295       }
3296 
3297       o->oop_iterate(&isLive);
3298       if (!_hr->obj_allocated_since_prev_marking(o)) {
3299         size_t obj_size = o->size();    // Make sure we don't overflow
3300         _live_bytes += (obj_size * HeapWordSize);
3301       }
3302     }
3303   }
3304   size_t live_bytes() { return _live_bytes; }
3305 };
3306 
3307 class PrintObjsInRegionClosure : public ObjectClosure {
3308   HeapRegion *_hr;
3309   G1CollectedHeap *_g1;
3310 public:
3311   PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
3312     _g1 = G1CollectedHeap::heap();
3313   };
3314 
3315   void do_object(oop o) {
3316     if (o != NULL) {
3317       HeapWord *start = (HeapWord *) o;
3318       size_t word_sz = o->size();
3319       gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
3320                           " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
3321                           (void*) o, word_sz,
3322                           _g1->isMarkedPrev(o),
3323                           _g1->isMarkedNext(o),
3324                           _hr->obj_allocated_since_prev_marking(o));
3325       HeapWord *end = start + word_sz;
3326       HeapWord *cur;
3327       int *val;
3328       for (cur = start; cur < end; cur++) {
3329         val = (int *) cur;
3330         gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
3331       }
3332     }
3333   }
3334 };
3335 
3336 class VerifyRegionClosure: public HeapRegionClosure {
3337 private:
3338   bool             _par;
3339   VerifyOption     _vo;
3340   bool             _failures;
3341 public:
3342   // _vo == UsePrevMarking -> use "prev" marking information,
3343   // _vo == UseNextMarking -> use "next" marking information,
3344   // _vo == UseMarkWord    -> use mark word from object header.
3345   VerifyRegionClosure(bool par, VerifyOption vo)
3346     : _par(par),
3347       _vo(vo),
3348       _failures(false) {}
3349 
3350   bool failures() {
3351     return _failures;
3352   }
3353 
3354   bool doHeapRegion(HeapRegion* r) {
3355     if (!r->continuesHumongous()) {
3356       bool failures = false;
3357       r->verify(_vo, &failures);
3358       if (failures) {
3359         _failures = true;
3360       } else {
3361         VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
3362         r->object_iterate(&not_dead_yet_cl);
3363         if (_vo != VerifyOption_G1UseNextMarking) {
3364           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
3365             gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
3366                                    "max_live_bytes "SIZE_FORMAT" "
3367                                    "< calculated "SIZE_FORMAT,
3368                                    r->bottom(), r->end(),
3369                                    r->max_live_bytes(),
3370                                  not_dead_yet_cl.live_bytes());
3371             _failures = true;
3372           }
3373         } else {
3374           // When vo == UseNextMarking we cannot currently do a sanity
3375           // check on the live bytes as the calculation has not been
3376           // finalized yet.
3377         }
3378       }
3379     }
3380     return false; // stop the region iteration if we hit a failure
3381   }
3382 };
3383 
3384 // This is the task used for parallel heap verification.
3385 
3386 class G1ParVerifyTask: public AbstractGangTask {
3387 private:
3388   G1CollectedHeap* _g1h;
3389   VerifyOption     _vo;
3390   bool             _failures;
3391 
3392 public:
3393   // _vo == UsePrevMarking -> use "prev" marking information,
3394   // _vo == UseNextMarking -> use "next" marking information,
3395   // _vo == UseMarkWord    -> use mark word from object header.
3396   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
3397     AbstractGangTask("Parallel verify task"),
3398     _g1h(g1h),
3399     _vo(vo),
3400     _failures(false) { }
3401 
3402   bool failures() {
3403     return _failures;
3404   }
3405 
3406   void work(uint worker_id) {
3407     HandleMark hm;
3408     VerifyRegionClosure blk(true, _vo);
3409     _g1h->heap_region_par_iterate_chunked(&blk, worker_id,
3410                                           _g1h->workers()->active_workers(),
3411                                           HeapRegion::ParVerifyClaimValue);
3412     if (blk.failures()) {
3413       _failures = true;
3414     }
3415   }
3416 };
3417 
3418 void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
3419   if (SafepointSynchronize::is_at_safepoint()) {
3420     assert(Thread::current()->is_VM_thread(),
3421            "Expected to be executed serially by the VM thread at this point");
3422 
3423     if (!silent) { gclog_or_tty->print("Roots (excluding permgen) "); }
3424     VerifyRootsClosure rootsCl(vo);
3425 
3426     G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);
3427     G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
3428     // We apply the relevant closures to all the oops in the
3429     // system dictionary, the string table and the code cache.
3430     const int so = SO_AllClasses | SO_Strings | SO_CodeCache;
3431 
3432     process_strong_roots(true,      // activate StrongRootsScope
3433                          true,      // we set "collecting perm gen" to true,
3434                                     // so we don't reset the dirty cards in the perm gen.
3435                          ScanningOption(so),  // roots scanning options
3436                          &rootsCl,
3437                          &blobsCl,
3438                          &rootsCl);
3439 
3440     // If we're verifying after the marking phase of a Full GC then we can't
3441     // treat the perm gen as roots into the G1 heap. Some of the objects in
3442     // the perm gen may be dead and hence not marked. If one of these dead
3443     // objects is considered to be a root then we may end up with a false
3444     // "Root location <x> points to dead ob <y>" failure.
3445     if (vo != VerifyOption_G1UseMarkWord) {
3446       // Since we used "collecting_perm_gen" == true above, we will not have
3447       // checked the refs from perm into the G1-collected heap. We check those
3448       // references explicitly below. Whether the relevant cards are dirty
3449       // is checked further below in the rem set verification.
3450       if (!silent) { gclog_or_tty->print("Permgen roots "); }
3451       perm_gen()->oop_iterate(&rootsCl);
3452     }
3453     bool failures = rootsCl.failures();
3454 
3455     if (vo != VerifyOption_G1UseMarkWord) {
3456       // If we're verifying during a full GC then the region sets
3457       // will have been torn down at the start of the GC. Therefore
3458       // verifying the region sets will fail. So we only verify
3459       // the region sets when not in a full GC.
3460       if (!silent) { gclog_or_tty->print("HeapRegionSets "); }
3461       verify_region_sets();
3462     }
3463 
3464     if (!silent) { gclog_or_tty->print("HeapRegions "); }
3465     if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
3466       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3467              "sanity check");
3468 
3469       G1ParVerifyTask task(this, vo);
3470       assert(UseDynamicNumberOfGCThreads ||
3471         workers()->active_workers() == workers()->total_workers(),
3472         "If not dynamic should be using all the workers");
3473       int n_workers = workers()->active_workers();
3474       set_par_threads(n_workers);
3475       workers()->run_task(&task);
3476       set_par_threads(0);
3477       if (task.failures()) {
3478         failures = true;
3479       }
3480 
3481       // Checks that the expected amount of parallel work was done.
3482       // The implication is that n_workers is > 0.
3483       assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
3484              "sanity check");
3485 
3486       reset_heap_region_claim_values();
3487 
3488       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3489              "sanity check");
3490     } else {
3491       VerifyRegionClosure blk(false, vo);
3492       heap_region_iterate(&blk);
3493       if (blk.failures()) {
3494         failures = true;
3495       }
3496     }
3497     if (!silent) gclog_or_tty->print("RemSet ");
3498     rem_set()->verify();
3499 
3500     if (failures) {
3501       gclog_or_tty->print_cr("Heap:");
3502       // It helps to have the per-region information in the output to
3503       // help us track down what went wrong. This is why we call
3504       // print_extended_on() instead of print_on().
3505       print_extended_on(gclog_or_tty);
3506       gclog_or_tty->print_cr("");
3507 #ifndef PRODUCT
3508       if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {
3509         concurrent_mark()->print_reachable("at-verification-failure",
3510                                            vo, false /* all */);
3511       }
3512 #endif
3513       gclog_or_tty->flush();
3514     }
3515     guarantee(!failures, "there should not have been any failures");
3516   } else {
3517     if (!silent)
3518       gclog_or_tty->print("(SKIPPING roots, heapRegionSets, heapRegions, remset) ");
3519   }
3520 }
3521 
3522 void G1CollectedHeap::verify(bool silent) {
3523   verify(silent, VerifyOption_G1UsePrevMarking);
3524 }
3525 
3526 double G1CollectedHeap::verify(bool guard, const char* msg) {
3527   double verify_time_ms = 0.0;
3528 
3529   if (guard && total_collections() >= VerifyGCStartAt) {
3530     double verify_start = os::elapsedTime();
3531     HandleMark hm;  // Discard invalid handles created during verification
3532     prepare_for_verify();
3533     Universe::verify(VerifyOption_G1UsePrevMarking, msg);
3534     verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
3535   }
3536 
3537   return verify_time_ms;
3538 }
3539 
3540 void G1CollectedHeap::verify_before_gc() {
3541   double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:");
3542   g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);
3543 }
3544 
3545 void G1CollectedHeap::verify_after_gc() {
3546   double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:");
3547   g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);
3548 }
3549 
3550 class PrintRegionClosure: public HeapRegionClosure {
3551   outputStream* _st;
3552 public:
3553   PrintRegionClosure(outputStream* st) : _st(st) {}
3554   bool doHeapRegion(HeapRegion* r) {
3555     r->print_on(_st);
3556     return false;
3557   }
3558 };
3559 
3560 void G1CollectedHeap::print_on(outputStream* st) const {
3561   st->print(" %-20s", "garbage-first heap");
3562   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
3563             capacity()/K, used_unlocked()/K);
3564   st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
3565             _g1_storage.low_boundary(),
3566             _g1_storage.high(),
3567             _g1_storage.high_boundary());
3568   st->cr();
3569   st->print("  region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
3570   uint young_regions = _young_list->length();
3571   st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
3572             (size_t) young_regions * HeapRegion::GrainBytes / K);
3573   uint survivor_regions = g1_policy()->recorded_survivor_regions();
3574   st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
3575             (size_t) survivor_regions * HeapRegion::GrainBytes / K);
3576   st->cr();
3577   perm()->as_gen()->print_on(st);
3578 }
3579 
3580 void G1CollectedHeap::print_extended_on(outputStream* st) const {
3581   print_on(st);
3582 
3583   // Print the per-region information.
3584   st->cr();
3585   st->print_cr("Heap Regions: (Y=young(eden), SU=young(survivor), "
3586                "HS=humongous(starts), HC=humongous(continues), "
3587                "CS=collection set, F=free, TS=gc time stamp, "
3588                "PTAMS=previous top-at-mark-start, "
3589                "NTAMS=next top-at-mark-start)");
3590   PrintRegionClosure blk(st);
3591   heap_region_iterate(&blk);
3592 }
3593 
3594 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
3595   if (G1CollectedHeap::use_parallel_gc_threads()) {
3596     workers()->print_worker_threads_on(st);
3597   }
3598   _cmThread->print_on(st);
3599   st->cr();
3600   _cm->print_worker_threads_on(st);
3601   _cg1r->print_worker_threads_on(st);
3602   st->cr();
3603 }
3604 
3605 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
3606   if (G1CollectedHeap::use_parallel_gc_threads()) {
3607     workers()->threads_do(tc);
3608   }
3609   tc->do_thread(_cmThread);
3610   _cg1r->threads_do(tc);
3611 }
3612 
3613 void G1CollectedHeap::print_tracing_info() const {
3614   // We'll overload this to mean "trace GC pause statistics."
3615   if (TraceGen0Time || TraceGen1Time) {
3616     // The "G1CollectorPolicy" is keeping track of these stats, so delegate
3617     // to that.
3618     g1_policy()->print_tracing_info();
3619   }
3620   if (G1SummarizeRSetStats) {
3621     g1_rem_set()->print_summary_info();
3622   }
3623   if (G1SummarizeConcMark) {
3624     concurrent_mark()->print_summary_info();
3625   }
3626   g1_policy()->print_yg_surv_rate_info();
3627   SpecializationStats::print();
3628 }
3629 
3630 #ifndef PRODUCT
3631 // Helpful for debugging RSet issues.
3632 
3633 class PrintRSetsClosure : public HeapRegionClosure {
3634 private:
3635   const char* _msg;
3636   size_t _occupied_sum;
3637 
3638 public:
3639   bool doHeapRegion(HeapRegion* r) {
3640     HeapRegionRemSet* hrrs = r->rem_set();
3641     size_t occupied = hrrs->occupied();
3642     _occupied_sum += occupied;
3643 
3644     gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT,
3645                            HR_FORMAT_PARAMS(r));
3646     if (occupied == 0) {
3647       gclog_or_tty->print_cr("  RSet is empty");
3648     } else {
3649       hrrs->print();
3650     }
3651     gclog_or_tty->print_cr("----------");
3652     return false;
3653   }
3654 
3655   PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
3656     gclog_or_tty->cr();
3657     gclog_or_tty->print_cr("========================================");
3658     gclog_or_tty->print_cr(msg);
3659     gclog_or_tty->cr();
3660   }
3661 
3662   ~PrintRSetsClosure() {
3663     gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum);
3664     gclog_or_tty->print_cr("========================================");
3665     gclog_or_tty->cr();
3666   }
3667 };
3668 
3669 void G1CollectedHeap::print_cset_rsets() {
3670   PrintRSetsClosure cl("Printing CSet RSets");
3671   collection_set_iterate(&cl);
3672 }
3673 
3674 void G1CollectedHeap::print_all_rsets() {
3675   PrintRSetsClosure cl("Printing All RSets");;
3676   heap_region_iterate(&cl);
3677 }
3678 #endif // PRODUCT
3679 
3680 G1CollectedHeap* G1CollectedHeap::heap() {
3681   assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
3682          "not a garbage-first heap");
3683   return _g1h;
3684 }
3685 
3686 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
3687   // always_do_update_barrier = false;
3688   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
3689   // Call allocation profiler
3690   AllocationProfiler::iterate_since_last_gc();
3691   // Fill TLAB's and such
3692   ensure_parsability(true);
3693 
3694   if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) &&
3695       (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
3696     g1_rem_set()->print_periodic_summary_info("Before GC RS summary");
3697   }
3698 }
3699 
3700 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
3701 
3702   if (G1SummarizeRSetStats &&
3703       (G1SummarizeRSetStatsPeriod > 0) &&
3704       // we are at the end of the GC. Total collections has already been increased.
3705       ((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) {
3706     g1_rem_set()->print_periodic_summary_info("After GC RS summary");
3707   }
3708 
3709   // FIXME: what is this about?
3710   // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
3711   // is set.
3712   COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
3713                         "derived pointer present"));
3714   // always_do_update_barrier = true;
3715 
3716   // We have just completed a GC. Update the soft reference
3717   // policy with the new heap occupancy
3718   Universe::update_heap_info_at_gc();
3719 }
3720 
3721 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
3722                                                unsigned int gc_count_before,
3723                                                bool* succeeded) {
3724   assert_heap_not_locked_and_not_at_safepoint();
3725   g1_policy()->record_stop_world_start();
3726   VM_G1IncCollectionPause op(gc_count_before,
3727                              word_size,
3728                              false, /* should_initiate_conc_mark */
3729                              g1_policy()->max_pause_time_ms(),
3730                              GCCause::_g1_inc_collection_pause);
3731   VMThread::execute(&op);
3732 
3733   HeapWord* result = op.result();
3734   bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
3735   assert(result == NULL || ret_succeeded,
3736          "the result should be NULL if the VM did not succeed");
3737   *succeeded = ret_succeeded;
3738 
3739   assert_heap_not_locked();
3740   return result;
3741 }
3742 
3743 void
3744 G1CollectedHeap::doConcurrentMark() {
3745   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
3746   if (!_cmThread->in_progress()) {
3747     _cmThread->set_started();
3748     CGC_lock->notify();
3749   }
3750 }
3751 
3752 size_t G1CollectedHeap::pending_card_num() {
3753   size_t extra_cards = 0;
3754   JavaThread *curr = Threads::first();
3755   while (curr != NULL) {
3756     DirtyCardQueue& dcq = curr->dirty_card_queue();
3757     extra_cards += dcq.size();
3758     curr = curr->next();
3759   }
3760   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
3761   size_t buffer_size = dcqs.buffer_size();
3762   size_t buffer_num = dcqs.completed_buffers_num();
3763 
3764   // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes
3765   // in bytes - not the number of 'entries'. We need to convert
3766   // into a number of cards.
3767   return (buffer_size * buffer_num + extra_cards) / oopSize;
3768 }
3769 
3770 size_t G1CollectedHeap::cards_scanned() {
3771   return g1_rem_set()->cardsScanned();
3772 }
3773 
3774 void
3775 G1CollectedHeap::setup_surviving_young_words() {
3776   assert(_surviving_young_words == NULL, "pre-condition");
3777   uint array_length = g1_policy()->young_cset_region_length();
3778   _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC);
3779   if (_surviving_young_words == NULL) {
3780     vm_exit_out_of_memory(sizeof(size_t) * array_length,
3781                           "Not enough space for young surv words summary.");
3782   }
3783   memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t));
3784 #ifdef ASSERT
3785   for (uint i = 0;  i < array_length; ++i) {
3786     assert( _surviving_young_words[i] == 0, "memset above" );
3787   }
3788 #endif // !ASSERT
3789 }
3790 
3791 void
3792 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
3793   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
3794   uint array_length = g1_policy()->young_cset_region_length();
3795   for (uint i = 0; i < array_length; ++i) {
3796     _surviving_young_words[i] += surv_young_words[i];
3797   }
3798 }
3799 
3800 void
3801 G1CollectedHeap::cleanup_surviving_young_words() {
3802   guarantee( _surviving_young_words != NULL, "pre-condition" );
3803   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words, mtGC);
3804   _surviving_young_words = NULL;
3805 }
3806 
3807 #ifdef ASSERT
3808 class VerifyCSetClosure: public HeapRegionClosure {
3809 public:
3810   bool doHeapRegion(HeapRegion* hr) {
3811     // Here we check that the CSet region's RSet is ready for parallel
3812     // iteration. The fields that we'll verify are only manipulated
3813     // when the region is part of a CSet and is collected. Afterwards,
3814     // we reset these fields when we clear the region's RSet (when the
3815     // region is freed) so they are ready when the region is
3816     // re-allocated. The only exception to this is if there's an
3817     // evacuation failure and instead of freeing the region we leave
3818     // it in the heap. In that case, we reset these fields during
3819     // evacuation failure handling.
3820     guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");
3821 
3822     // Here's a good place to add any other checks we'd like to
3823     // perform on CSet regions.
3824     return false;
3825   }
3826 };
3827 #endif // ASSERT
3828 
3829 #if TASKQUEUE_STATS
3830 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
3831   st->print_raw_cr("GC Task Stats");
3832   st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
3833   st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
3834 }
3835 
3836 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
3837   print_taskqueue_stats_hdr(st);
3838 
3839   TaskQueueStats totals;
3840   const int n = workers() != NULL ? workers()->total_workers() : 1;
3841   for (int i = 0; i < n; ++i) {
3842     st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();
3843     totals += task_queue(i)->stats;
3844   }
3845   st->print_raw("tot "); totals.print(st); st->cr();
3846 
3847   DEBUG_ONLY(totals.verify());
3848 }
3849 
3850 void G1CollectedHeap::reset_taskqueue_stats() {
3851   const int n = workers() != NULL ? workers()->total_workers() : 1;
3852   for (int i = 0; i < n; ++i) {
3853     task_queue(i)->stats.reset();
3854   }
3855 }
3856 #endif // TASKQUEUE_STATS
3857 
3858 void G1CollectedHeap::log_gc_header() {
3859   if (!G1Log::fine()) {
3860     return;
3861   }
3862 
3863   gclog_or_tty->date_stamp(PrintGCDateStamps);
3864   gclog_or_tty->stamp(PrintGCTimeStamps);
3865 
3866   GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
3867     .append(g1_policy()->gcs_are_young() ? " (young)" : " (mixed)")
3868     .append(g1_policy()->during_initial_mark_pause() ? " (initial-mark)" : "");
3869 
3870   gclog_or_tty->print("[%s", (const char*)gc_cause_str);
3871 }
3872 
3873 void G1CollectedHeap::log_gc_footer(double pause_time_sec) {
3874   if (!G1Log::fine()) {
3875     return;
3876   }
3877 
3878   if (G1Log::finer()) {
3879     if (evacuation_failed()) {
3880       gclog_or_tty->print(" (to-space exhausted)");
3881     }
3882     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3883     g1_policy()->phase_times()->note_gc_end();
3884     g1_policy()->phase_times()->print(pause_time_sec);
3885     g1_policy()->print_detailed_heap_transition();
3886   } else {
3887     if (evacuation_failed()) {
3888       gclog_or_tty->print("--");
3889     }
3890     g1_policy()->print_heap_transition();
3891     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3892   }
3893   gclog_or_tty->flush();
3894 }
3895 
3896 bool
3897 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
3898   assert_at_safepoint(true /* should_be_vm_thread */);
3899   guarantee(!is_gc_active(), "collection is not reentrant");
3900 
3901   if (GC_locker::check_active_before_gc()) {
3902     return false;
3903   }
3904 
3905   _gc_timer_stw->register_gc_start();
3906 
3907   _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
3908 
3909   SvcGCMarker sgcm(SvcGCMarker::MINOR);
3910   ResourceMark rm;
3911 
3912   print_heap_before_gc();
3913   trace_heap_before_gc(_gc_tracer_stw);
3914 
3915   HRSPhaseSetter x(HRSPhaseEvacuation);
3916   verify_region_sets_optional();
3917   verify_dirty_young_regions();
3918 
3919   // This call will decide whether this pause is an initial-mark
3920   // pause. If it is, during_initial_mark_pause() will return true
3921   // for the duration of this pause.
3922   g1_policy()->decide_on_conc_mark_initiation();
3923 
3924   // We do not allow initial-mark to be piggy-backed on a mixed GC.
3925   assert(!g1_policy()->during_initial_mark_pause() ||
3926           g1_policy()->gcs_are_young(), "sanity");
3927 
3928   // We also do not allow mixed GCs during marking.
3929   assert(!mark_in_progress() || g1_policy()->gcs_are_young(), "sanity");
3930 
3931   // Record whether this pause is an initial mark. When the current
3932   // thread has completed its logging output and it's safe to signal
3933   // the CM thread, the flag's value in the policy has been reset.
3934   bool should_start_conc_mark = g1_policy()->during_initial_mark_pause();
3935 
3936   // Inner scope for scope based logging, timers, and stats collection
3937   {
3938     EvacuationInfo evacuation_info;
3939 
3940     if (g1_policy()->during_initial_mark_pause()) {
3941       // We are about to start a marking cycle, so we increment the
3942       // full collection counter.
3943       increment_old_marking_cycles_started();
3944       register_concurrent_cycle_start(_gc_timer_stw->gc_start());
3945     }
3946 
3947     _gc_tracer_stw->report_yc_type(yc_type());
3948 
3949     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
3950 
3951     int active_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
3952                                 workers()->active_workers() : 1);
3953     double pause_start_sec = os::elapsedTime();
3954     g1_policy()->phase_times()->note_gc_start(active_workers);
3955     log_gc_header();
3956 
3957     TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
3958     TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
3959 
3960     // If the secondary_free_list is not empty, append it to the
3961     // free_list. No need to wait for the cleanup operation to finish;
3962     // the region allocation code will check the secondary_free_list
3963     // and wait if necessary. If the G1StressConcRegionFreeing flag is
3964     // set, skip this step so that the region allocation code has to
3965     // get entries from the secondary_free_list.
3966     if (!G1StressConcRegionFreeing) {
3967       append_secondary_free_list_if_not_empty_with_lock();
3968     }
3969 
3970     assert(check_young_list_well_formed(), "young list should be well formed");
3971     assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3972            "sanity check");
3973 
3974     // Don't dynamically change the number of GC threads this early.  A value of
3975     // 0 is used to indicate serial work.  When parallel work is done,
3976     // it will be set.
3977 
3978     { // Call to jvmpi::post_class_unload_events must occur outside of active GC
3979       IsGCActiveMark x;
3980 
3981       gc_prologue(false);
3982       increment_total_collections(false /* full gc */);
3983       increment_gc_time_stamp();
3984 
3985       verify_before_gc();
3986 
3987       COMPILER2_PRESENT(DerivedPointerTable::clear());
3988 
3989       // Please see comment in g1CollectedHeap.hpp and
3990       // G1CollectedHeap::ref_processing_init() to see how
3991       // reference processing currently works in G1.
3992 
3993       // Enable discovery in the STW reference processor
3994       ref_processor_stw()->enable_discovery(true /*verify_disabled*/,
3995                                             true /*verify_no_refs*/);
3996 
3997       {
3998         // We want to temporarily turn off discovery by the
3999         // CM ref processor, if necessary, and turn it back on
4000         // on again later if we do. Using a scoped
4001         // NoRefDiscovery object will do this.
4002         NoRefDiscovery no_cm_discovery(ref_processor_cm());
4003 
4004         // Forget the current alloc region (we might even choose it to be part
4005         // of the collection set!).
4006         release_mutator_alloc_region();
4007 
4008         // We should call this after we retire the mutator alloc
4009         // region(s) so that all the ALLOC / RETIRE events are generated
4010         // before the start GC event.
4011         _hr_printer.start_gc(false /* full */, (size_t) total_collections());
4012 
4013         // This timing is only used by the ergonomics to handle our pause target.
4014         // It is unclear why this should not include the full pause. We will
4015         // investigate this in CR 7178365.
4016         //
4017         // Preserving the old comment here if that helps the investigation:
4018         //
4019         // The elapsed time induced by the start time below deliberately elides
4020         // the possible verification above.
4021         double sample_start_time_sec = os::elapsedTime();
4022 
4023 #if YOUNG_LIST_VERBOSE
4024         gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
4025         _young_list->print();
4026         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4027 #endif // YOUNG_LIST_VERBOSE
4028 
4029         g1_policy()->record_collection_pause_start(sample_start_time_sec);
4030 
4031         double scan_wait_start = os::elapsedTime();
4032         // We have to wait until the CM threads finish scanning the
4033         // root regions as it's the only way to ensure that all the
4034         // objects on them have been correctly scanned before we start
4035         // moving them during the GC.
4036         bool waited = _cm->root_regions()->wait_until_scan_finished();
4037         double wait_time_ms = 0.0;
4038         if (waited) {
4039           double scan_wait_end = os::elapsedTime();
4040           wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
4041         }
4042         g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms);
4043 
4044 #if YOUNG_LIST_VERBOSE
4045         gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
4046         _young_list->print();
4047 #endif // YOUNG_LIST_VERBOSE
4048 
4049         if (g1_policy()->during_initial_mark_pause()) {
4050           concurrent_mark()->checkpointRootsInitialPre();
4051         }
4052         perm_gen()->save_marks();
4053 
4054 #if YOUNG_LIST_VERBOSE
4055         gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
4056         _young_list->print();
4057         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4058 #endif // YOUNG_LIST_VERBOSE
4059 
4060         g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info);
4061 
4062         _cm->note_start_of_gc();
4063         // We should not verify the per-thread SATB buffers given that
4064         // we have not filtered them yet (we'll do so during the
4065         // GC). We also call this after finalize_cset() to
4066         // ensure that the CSet has been finalized.
4067         _cm->verify_no_cset_oops(true  /* verify_stacks */,
4068                                  true  /* verify_enqueued_buffers */,
4069                                  false /* verify_thread_buffers */,
4070                                  true  /* verify_fingers */);
4071 
4072         if (_hr_printer.is_active()) {
4073           HeapRegion* hr = g1_policy()->collection_set();
4074           while (hr != NULL) {
4075             G1HRPrinter::RegionType type;
4076             if (!hr->is_young()) {
4077               type = G1HRPrinter::Old;
4078             } else if (hr->is_survivor()) {
4079               type = G1HRPrinter::Survivor;
4080             } else {
4081               type = G1HRPrinter::Eden;
4082             }
4083             _hr_printer.cset(hr);
4084             hr = hr->next_in_collection_set();
4085           }
4086         }
4087 
4088 #ifdef ASSERT
4089         VerifyCSetClosure cl;
4090         collection_set_iterate(&cl);
4091 #endif // ASSERT
4092 
4093         setup_surviving_young_words();
4094 
4095         // Initialize the GC alloc regions.
4096         init_gc_alloc_regions(evacuation_info);
4097 
4098         // Actually do the work...
4099         evacuate_collection_set(evacuation_info);
4100 
4101         // We do this to mainly verify the per-thread SATB buffers
4102         // (which have been filtered by now) since we didn't verify
4103         // them earlier. No point in re-checking the stacks / enqueued
4104         // buffers given that the CSet has not changed since last time
4105         // we checked.
4106         _cm->verify_no_cset_oops(false /* verify_stacks */,
4107                                  false /* verify_enqueued_buffers */,
4108                                  true  /* verify_thread_buffers */,
4109                                  true  /* verify_fingers */);
4110 
4111         free_collection_set(g1_policy()->collection_set(), evacuation_info);
4112         g1_policy()->clear_collection_set();
4113 
4114         cleanup_surviving_young_words();
4115 
4116         // Start a new incremental collection set for the next pause.
4117         g1_policy()->start_incremental_cset_building();
4118 
4119         // Clear the _cset_fast_test bitmap in anticipation of adding
4120         // regions to the incremental collection set for the next
4121         // evacuation pause.
4122         clear_cset_fast_test();
4123 
4124         _young_list->reset_sampled_info();
4125 
4126         // Don't check the whole heap at this point as the
4127         // GC alloc regions from this pause have been tagged
4128         // as survivors and moved on to the survivor list.
4129         // Survivor regions will fail the !is_young() check.
4130         assert(check_young_list_empty(false /* check_heap */),
4131           "young list should be empty");
4132 
4133 #if YOUNG_LIST_VERBOSE
4134         gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
4135         _young_list->print();
4136 #endif // YOUNG_LIST_VERBOSE
4137 
4138         g1_policy()->record_survivor_regions(_young_list->survivor_length(),
4139                                              _young_list->first_survivor_region(),
4140                                              _young_list->last_survivor_region());
4141 
4142         _young_list->reset_auxilary_lists();
4143 
4144         if (evacuation_failed()) {
4145           _summary_bytes_used = recalculate_used();
4146           uint n_queues = MAX2((int)ParallelGCThreads, 1);
4147           for (uint i = 0; i < n_queues; i++) {
4148             if (_evacuation_failed_info_array[i].has_failed()) {
4149               _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4150             }
4151           }
4152         } else {
4153           // The "used" of the the collection set have already been subtracted
4154           // when they were freed.  Add in the bytes evacuated.
4155           _summary_bytes_used += g1_policy()->bytes_copied_during_gc();
4156         }
4157 
4158         if (g1_policy()->during_initial_mark_pause()) {
4159           // We have to do this before we notify the CM threads that
4160           // they can start working to make sure that all the
4161           // appropriate initialization is done on the CM object.
4162           concurrent_mark()->checkpointRootsInitialPost();
4163           set_marking_started();
4164           // Note that we don't actually trigger the CM thread at
4165           // this point. We do that later when we're sure that
4166           // the current thread has completed its logging output.
4167         }
4168 
4169         allocate_dummy_regions();
4170 
4171 #if YOUNG_LIST_VERBOSE
4172         gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
4173         _young_list->print();
4174         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4175 #endif // YOUNG_LIST_VERBOSE
4176 
4177         init_mutator_alloc_region();
4178 
4179         {
4180           size_t expand_bytes = g1_policy()->expansion_amount();
4181           if (expand_bytes > 0) {
4182             size_t bytes_before = capacity();
4183             // No need for an ergo verbose message here,
4184             // expansion_amount() does this when it returns a value > 0.
4185             if (!expand(expand_bytes)) {
4186               // We failed to expand the heap so let's verify that
4187               // committed/uncommitted amount match the backing store
4188               assert(capacity() == _g1_storage.committed_size(), "committed size mismatch");
4189               assert(max_capacity() == _g1_storage.reserved_size(), "reserved size mismatch");
4190             }
4191           }
4192         }
4193 
4194         // We redo the verification but now wrt to the new CSet which
4195         // has just got initialized after the previous CSet was freed.
4196         _cm->verify_no_cset_oops(true  /* verify_stacks */,
4197                                  true  /* verify_enqueued_buffers */,
4198                                  true  /* verify_thread_buffers */,
4199                                  true  /* verify_fingers */);
4200         _cm->note_end_of_gc();
4201 
4202         // This timing is only used by the ergonomics to handle our pause target.
4203         // It is unclear why this should not include the full pause. We will
4204         // investigate this in CR 7178365.
4205         double sample_end_time_sec = os::elapsedTime();
4206         double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
4207         g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info);
4208 
4209         MemoryService::track_memory_usage();
4210 
4211         // In prepare_for_verify() below we'll need to scan the deferred
4212         // update buffers to bring the RSets up-to-date if
4213         // G1HRRSFlushLogBuffersOnVerify has been set. While scanning
4214         // the update buffers we'll probably need to scan cards on the
4215         // regions we just allocated to (i.e., the GC alloc
4216         // regions). However, during the last GC we called
4217         // set_saved_mark() on all the GC alloc regions, so card
4218         // scanning might skip the [saved_mark_word()...top()] area of
4219         // those regions (i.e., the area we allocated objects into
4220         // during the last GC). But it shouldn't. Given that
4221         // saved_mark_word() is conditional on whether the GC time stamp
4222         // on the region is current or not, by incrementing the GC time
4223         // stamp here we invalidate all the GC time stamps on all the
4224         // regions and saved_mark_word() will simply return top() for
4225         // all the regions. This is a nicer way of ensuring this rather
4226         // than iterating over the regions and fixing them. In fact, the
4227         // GC time stamp increment here also ensures that
4228         // saved_mark_word() will return top() between pauses, i.e.,
4229         // during concurrent refinement. So we don't need the
4230         // is_gc_active() check to decided which top to use when
4231         // scanning cards (see CR 7039627).
4232         increment_gc_time_stamp();
4233 
4234         verify_after_gc();
4235 
4236         assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
4237         ref_processor_stw()->verify_no_references_recorded();
4238 
4239         // CM reference discovery will be re-enabled if necessary.
4240       }
4241 
4242       // We should do this after we potentially expand the heap so
4243       // that all the COMMIT events are generated before the end GC
4244       // event, and after we retire the GC alloc regions so that all
4245       // RETIRE events are generated before the end GC event.
4246       _hr_printer.end_gc(false /* full */, (size_t) total_collections());
4247 
4248       if (mark_in_progress()) {
4249         concurrent_mark()->update_g1_committed();
4250       }
4251 
4252 #ifdef TRACESPINNING
4253       ParallelTaskTerminator::print_termination_counts();
4254 #endif
4255 
4256       gc_epilogue(false);
4257     }
4258 
4259     // Print the remainder of the GC log output.
4260     log_gc_footer(os::elapsedTime() - pause_start_sec);
4261 
4262     // It is not yet to safe to tell the concurrent mark to
4263     // start as we have some optional output below. We don't want the
4264     // output from the concurrent mark thread interfering with this
4265     // logging output either.
4266 
4267     _hrs.verify_optional();
4268     verify_region_sets_optional();
4269 
4270     TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());
4271     TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
4272 
4273     print_heap_after_gc();
4274     trace_heap_after_gc(_gc_tracer_stw);
4275 
4276     // We must call G1MonitoringSupport::update_sizes() in the same scoping level
4277     // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
4278     // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
4279     // before any GC notifications are raised.
4280     g1mm()->update_sizes();
4281 
4282     _gc_tracer_stw->report_evacuation_info(&evacuation_info);
4283     _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold());
4284     _gc_timer_stw->register_gc_end();
4285     _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());
4286   }
4287 
4288   // It should now be safe to tell the concurrent mark thread to start
4289   // without its logging output interfering with the logging output
4290   // that came from the pause.
4291 
4292   if (should_start_conc_mark) {
4293     // CAUTION: after the doConcurrentMark() call below,
4294     // the concurrent marking thread(s) could be running
4295     // concurrently with us. Make sure that anything after
4296     // this point does not assume that we are the only GC thread
4297     // running. Note: of course, the actual marking work will
4298     // not start until the safepoint itself is released in
4299     // ConcurrentGCThread::safepoint_desynchronize().
4300     doConcurrentMark();
4301   }
4302 
4303   return true;
4304 }
4305 
4306 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose)
4307 {
4308   size_t gclab_word_size;
4309   switch (purpose) {
4310     case GCAllocForSurvived:
4311       gclab_word_size = _survivor_plab_stats.desired_plab_sz();
4312       break;
4313     case GCAllocForTenured:
4314       gclab_word_size = _old_plab_stats.desired_plab_sz();
4315       break;
4316     default:
4317       assert(false, "unknown GCAllocPurpose");
4318       gclab_word_size = _old_plab_stats.desired_plab_sz();
4319       break;
4320   }
4321 
4322   // Prevent humongous PLAB sizes for two reasons:
4323   // * PLABs are allocated using a similar paths as oops, but should
4324   //   never be in a humongous region
4325   // * Allowing humongous PLABs needlessly churns the region free lists
4326   return MIN2(_humongous_object_threshold_in_words, gclab_word_size);
4327 }
4328 
4329 void G1CollectedHeap::init_mutator_alloc_region() {
4330   assert(_mutator_alloc_region.get() == NULL, "pre-condition");
4331   _mutator_alloc_region.init();
4332 }
4333 
4334 void G1CollectedHeap::release_mutator_alloc_region() {
4335   _mutator_alloc_region.release();
4336   assert(_mutator_alloc_region.get() == NULL, "post-condition");
4337 }
4338 
4339 void G1CollectedHeap::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
4340   assert_at_safepoint(true /* should_be_vm_thread */);
4341 
4342   _survivor_gc_alloc_region.init();
4343   _old_gc_alloc_region.init();
4344   HeapRegion* retained_region = _retained_old_gc_alloc_region;
4345   _retained_old_gc_alloc_region = NULL;
4346 
4347   // We will discard the current GC alloc region if:
4348   // a) it's in the collection set (it can happen!),
4349   // b) it's already full (no point in using it),
4350   // c) it's empty (this means that it was emptied during
4351   // a cleanup and it should be on the free list now), or
4352   // d) it's humongous (this means that it was emptied
4353   // during a cleanup and was added to the free list, but
4354   // has been subsequently used to allocate a humongous
4355   // object that may be less than the region size).
4356   if (retained_region != NULL &&
4357       !retained_region->in_collection_set() &&
4358       !(retained_region->top() == retained_region->end()) &&
4359       !retained_region->is_empty() &&
4360       !retained_region->isHumongous()) {
4361     retained_region->set_saved_mark();
4362     // The retained region was added to the old region set when it was
4363     // retired. We have to remove it now, since we don't allow regions
4364     // we allocate to in the region sets. We'll re-add it later, when
4365     // it's retired again.
4366     _old_set.remove(retained_region);
4367     bool during_im = g1_policy()->during_initial_mark_pause();
4368     retained_region->note_start_of_copying(during_im);
4369     _old_gc_alloc_region.set(retained_region);
4370     _hr_printer.reuse(retained_region);
4371     evacuation_info.set_alloc_regions_used_before(retained_region->used());
4372   }
4373 }
4374 
4375 void G1CollectedHeap::release_gc_alloc_regions(uint no_of_gc_workers, EvacuationInfo& evacuation_info) {
4376   evacuation_info.set_allocation_regions(_survivor_gc_alloc_region.count() +
4377                                          _old_gc_alloc_region.count());
4378   _survivor_gc_alloc_region.release();
4379   // If we have an old GC alloc region to release, we'll save it in
4380   // _retained_old_gc_alloc_region. If we don't
4381   // _retained_old_gc_alloc_region will become NULL. This is what we
4382   // want either way so no reason to check explicitly for either
4383   // condition.
4384   _retained_old_gc_alloc_region = _old_gc_alloc_region.release();
4385 
4386   if (ResizePLAB) {
4387     _survivor_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4388     _old_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4389   }
4390 }
4391 
4392 void G1CollectedHeap::abandon_gc_alloc_regions() {
4393   assert(_survivor_gc_alloc_region.get() == NULL, "pre-condition");
4394   assert(_old_gc_alloc_region.get() == NULL, "pre-condition");
4395   _retained_old_gc_alloc_region = NULL;
4396 }
4397 
4398 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
4399   _drain_in_progress = false;
4400   set_evac_failure_closure(cl);
4401   _evac_failure_scan_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true);
4402 }
4403 
4404 void G1CollectedHeap::finalize_for_evac_failure() {
4405   assert(_evac_failure_scan_stack != NULL &&
4406          _evac_failure_scan_stack->length() == 0,
4407          "Postcondition");
4408   assert(!_drain_in_progress, "Postcondition");
4409   delete _evac_failure_scan_stack;
4410   _evac_failure_scan_stack = NULL;
4411 }
4412 
4413 void G1CollectedHeap::remove_self_forwarding_pointers() {
4414   assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4415 
4416   G1ParRemoveSelfForwardPtrsTask rsfp_task(this);
4417 
4418   if (G1CollectedHeap::use_parallel_gc_threads()) {
4419     set_par_threads();
4420     workers()->run_task(&rsfp_task);
4421     set_par_threads(0);
4422   } else {
4423     rsfp_task.work(0);
4424   }
4425 
4426   assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");
4427 
4428   // Reset the claim values in the regions in the collection set.
4429   reset_cset_heap_region_claim_values();
4430 
4431   assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4432 
4433   // Now restore saved marks, if any.
4434   assert(_objs_with_preserved_marks.size() ==
4435             _preserved_marks_of_objs.size(), "Both or none.");
4436   while (!_objs_with_preserved_marks.is_empty()) {
4437     oop obj = _objs_with_preserved_marks.pop();
4438     markOop m = _preserved_marks_of_objs.pop();
4439     obj->set_mark(m);
4440   }
4441   _objs_with_preserved_marks.clear(true);
4442   _preserved_marks_of_objs.clear(true);
4443 }
4444 
4445 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
4446   _evac_failure_scan_stack->push(obj);
4447 }
4448 
4449 void G1CollectedHeap::drain_evac_failure_scan_stack() {
4450   assert(_evac_failure_scan_stack != NULL, "precondition");
4451 
4452   while (_evac_failure_scan_stack->length() > 0) {
4453      oop obj = _evac_failure_scan_stack->pop();
4454      _evac_failure_closure->set_region(heap_region_containing(obj));
4455      obj->oop_iterate_backwards(_evac_failure_closure);
4456   }
4457 }
4458 
4459 oop
4460 G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state,
4461                                                oop old) {
4462   assert(obj_in_cs(old),
4463          err_msg("obj: "PTR_FORMAT" should still be in the CSet",
4464                  (HeapWord*) old));
4465   markOop m = old->mark();
4466   oop forward_ptr = old->forward_to_atomic(old);
4467   if (forward_ptr == NULL) {
4468     // Forward-to-self succeeded.
4469     assert(_par_scan_state != NULL, "par scan state");
4470     OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
4471     uint queue_num = _par_scan_state->queue_num();
4472 
4473     _evacuation_failed = true;
4474     _evacuation_failed_info_array[queue_num].register_copy_failure(old->size());
4475     if (_evac_failure_closure != cl) {
4476       MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
4477       assert(!_drain_in_progress,
4478              "Should only be true while someone holds the lock.");
4479       // Set the global evac-failure closure to the current thread's.
4480       assert(_evac_failure_closure == NULL, "Or locking has failed.");
4481       set_evac_failure_closure(cl);
4482       // Now do the common part.
4483       handle_evacuation_failure_common(old, m);
4484       // Reset to NULL.
4485       set_evac_failure_closure(NULL);
4486     } else {
4487       // The lock is already held, and this is recursive.
4488       assert(_drain_in_progress, "This should only be the recursive case.");
4489       handle_evacuation_failure_common(old, m);
4490     }
4491     return old;
4492   } else {
4493     // Forward-to-self failed. Either someone else managed to allocate
4494     // space for this object (old != forward_ptr) or they beat us in
4495     // self-forwarding it (old == forward_ptr).
4496     assert(old == forward_ptr || !obj_in_cs(forward_ptr),
4497            err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" "
4498                    "should not be in the CSet",
4499                    (HeapWord*) old, (HeapWord*) forward_ptr));
4500     return forward_ptr;
4501   }
4502 }
4503 
4504 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
4505   preserve_mark_if_necessary(old, m);
4506 
4507   HeapRegion* r = heap_region_containing(old);
4508   if (!r->evacuation_failed()) {
4509     r->set_evacuation_failed(true);
4510     _hr_printer.evac_failure(r);
4511   }
4512 
4513   push_on_evac_failure_scan_stack(old);
4514 
4515   if (!_drain_in_progress) {
4516     // prevent recursion in copy_to_survivor_space()
4517     _drain_in_progress = true;
4518     drain_evac_failure_scan_stack();
4519     _drain_in_progress = false;
4520   }
4521 }
4522 
4523 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
4524   assert(evacuation_failed(), "Oversaving!");
4525   // We want to call the "for_promotion_failure" version only in the
4526   // case of a promotion failure.
4527   if (m->must_be_preserved_for_promotion_failure(obj)) {
4528     _objs_with_preserved_marks.push(obj);
4529     _preserved_marks_of_objs.push(m);
4530   }
4531 }
4532 
4533 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
4534                                                   size_t word_size) {
4535   if (purpose == GCAllocForSurvived) {
4536     HeapWord* result = survivor_attempt_allocation(word_size);
4537     if (result != NULL) {
4538       return result;
4539     } else {
4540       // Let's try to allocate in the old gen in case we can fit the
4541       // object there.
4542       return old_attempt_allocation(word_size);
4543     }
4544   } else {
4545     assert(purpose ==  GCAllocForTenured, "sanity");
4546     HeapWord* result = old_attempt_allocation(word_size);
4547     if (result != NULL) {
4548       return result;
4549     } else {
4550       // Let's try to allocate in the survivors in case we can fit the
4551       // object there.
4552       return survivor_attempt_allocation(word_size);
4553     }
4554   }
4555 
4556   ShouldNotReachHere();
4557   // Trying to keep some compilers happy.
4558   return NULL;
4559 }
4560 
4561 G1ParGCAllocBuffer::G1ParGCAllocBuffer(size_t gclab_word_size) :
4562   ParGCAllocBuffer(gclab_word_size), _retired(false) { }
4563 
4564 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num)
4565   : _g1h(g1h),
4566     _refs(g1h->task_queue(queue_num)),
4567     _dcq(&g1h->dirty_card_queue_set()),
4568     _ct_bs(g1h->g1_barrier_set()),
4569     _g1_rem(g1h->g1_rem_set()),
4570     _hash_seed(17), _queue_num(queue_num),
4571     _term_attempts(0),
4572     _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)),
4573     _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)),
4574     _age_table(false),
4575     _strong_roots_time(0), _term_time(0),
4576     _alloc_buffer_waste(0), _undo_waste(0) {
4577   // we allocate G1YoungSurvRateNumRegions plus one entries, since
4578   // we "sacrifice" entry 0 to keep track of surviving bytes for
4579   // non-young regions (where the age is -1)
4580   // We also add a few elements at the beginning and at the end in
4581   // an attempt to eliminate cache contention
4582   uint real_length = 1 + _g1h->g1_policy()->young_cset_region_length();
4583   uint array_length = PADDING_ELEM_NUM +
4584                       real_length +
4585                       PADDING_ELEM_NUM;
4586   _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length, mtGC);
4587   if (_surviving_young_words_base == NULL)
4588     vm_exit_out_of_memory(array_length * sizeof(size_t),
4589                           "Not enough space for young surv histo.");
4590   _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
4591   memset(_surviving_young_words, 0, (size_t) real_length * sizeof(size_t));
4592 
4593   _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer;
4594   _alloc_buffers[GCAllocForTenured]  = &_tenured_alloc_buffer;
4595 
4596   _start = os::elapsedTime();
4597 }
4598 
4599 void
4600 G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st)
4601 {
4602   st->print_raw_cr("GC Termination Stats");
4603   st->print_raw_cr("     elapsed  --strong roots-- -------termination-------"
4604                    " ------waste (KiB)------");
4605   st->print_raw_cr("thr     ms        ms      %        ms      %    attempts"
4606                    "  total   alloc    undo");
4607   st->print_raw_cr("--- --------- --------- ------ --------- ------ --------"
4608                    " ------- ------- -------");
4609 }
4610 
4611 void
4612 G1ParScanThreadState::print_termination_stats(int i,
4613                                               outputStream* const st) const
4614 {
4615   const double elapsed_ms = elapsed_time() * 1000.0;
4616   const double s_roots_ms = strong_roots_time() * 1000.0;
4617   const double term_ms    = term_time() * 1000.0;
4618   st->print_cr("%3d %9.2f %9.2f %6.2f "
4619                "%9.2f %6.2f " SIZE_FORMAT_W(8) " "
4620                SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7),
4621                i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
4622                term_ms, term_ms * 100 / elapsed_ms, term_attempts(),
4623                (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K,
4624                alloc_buffer_waste() * HeapWordSize / K,
4625                undo_waste() * HeapWordSize / K);
4626 }
4627 
4628 #ifdef ASSERT
4629 bool G1ParScanThreadState::verify_ref(narrowOop* ref) const {
4630   assert(ref != NULL, "invariant");
4631   assert(UseCompressedOops, "sanity");
4632   assert(!has_partial_array_mask(ref), err_msg("ref=" PTR_FORMAT, ref));
4633   oop p = oopDesc::load_decode_heap_oop(ref);
4634   assert(_g1h->is_in_g1_reserved(p),
4635          err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p)));
4636   return true;
4637 }
4638 
4639 bool G1ParScanThreadState::verify_ref(oop* ref) const {
4640   assert(ref != NULL, "invariant");
4641   if (has_partial_array_mask(ref)) {
4642     // Must be in the collection set--it's already been copied.
4643     oop p = clear_partial_array_mask(ref);
4644     assert(_g1h->obj_in_cs(p),
4645            err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p)));
4646   } else {
4647     oop p = oopDesc::load_decode_heap_oop(ref);
4648     assert(_g1h->is_in_g1_reserved(p),
4649            err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p)));
4650   }
4651   return true;
4652 }
4653 
4654 bool G1ParScanThreadState::verify_task(StarTask ref) const {
4655   if (ref.is_narrow()) {
4656     return verify_ref((narrowOop*) ref);
4657   } else {
4658     return verify_ref((oop*) ref);
4659   }
4660 }
4661 #endif // ASSERT
4662 
4663 void G1ParScanThreadState::trim_queue() {
4664   assert(_evac_cl != NULL, "not set");
4665   assert(_evac_failure_cl != NULL, "not set");
4666   assert(_partial_scan_cl != NULL, "not set");
4667 
4668   StarTask ref;
4669   do {
4670     // Drain the overflow stack first, so other threads can steal.
4671     while (refs()->pop_overflow(ref)) {
4672       deal_with_reference(ref);
4673     }
4674 
4675     while (refs()->pop_local(ref)) {
4676       deal_with_reference(ref);
4677     }
4678   } while (!refs()->is_empty());
4679 }
4680 
4681 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1,
4682                                      G1ParScanThreadState* par_scan_state) :
4683   _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()),
4684   _par_scan_state(par_scan_state),
4685   _worker_id(par_scan_state->queue_num()),
4686   _during_initial_mark(_g1->g1_policy()->during_initial_mark_pause()),
4687   _mark_in_progress(_g1->mark_in_progress()) { }
4688 
4689 template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_object>
4690 void G1ParCopyClosure<do_gen_barrier, barrier, do_mark_object>::mark_object(oop obj) {
4691 #ifdef ASSERT
4692   HeapRegion* hr = _g1->heap_region_containing(obj);
4693   assert(hr != NULL, "sanity");
4694   assert(!hr->in_collection_set(), "should not mark objects in the CSet");
4695 #endif // ASSERT
4696 
4697   // We know that the object is not moving so it's safe to read its size.
4698   _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
4699 }
4700 
4701 template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_object>
4702 void G1ParCopyClosure<do_gen_barrier, barrier, do_mark_object>
4703   ::mark_forwarded_object(oop from_obj, oop to_obj) {
4704 #ifdef ASSERT
4705   assert(from_obj->is_forwarded(), "from obj should be forwarded");
4706   assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");
4707   assert(from_obj != to_obj, "should not be self-forwarded");
4708 
4709   HeapRegion* from_hr = _g1->heap_region_containing(from_obj);
4710   assert(from_hr != NULL, "sanity");
4711   assert(from_hr->in_collection_set(), "from obj should be in the CSet");
4712 
4713   HeapRegion* to_hr = _g1->heap_region_containing(to_obj);
4714   assert(to_hr != NULL, "sanity");
4715   assert(!to_hr->in_collection_set(), "should not mark objects in the CSet");
4716 #endif // ASSERT
4717 
4718   // The object might be in the process of being copied by another
4719   // worker so we cannot trust that its to-space image is
4720   // well-formed. So we have to read its size from its from-space
4721   // image which we know should not be changing.
4722   _cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);
4723 }
4724 
4725 template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_object>
4726 oop G1ParCopyClosure<do_gen_barrier, barrier, do_mark_object>
4727   ::copy_to_survivor_space(oop old) {
4728   size_t word_sz = old->size();
4729   HeapRegion* from_region = _g1->heap_region_containing_raw(old);
4730   // +1 to make the -1 indexes valid...
4731   int       young_index = from_region->young_index_in_cset()+1;
4732   assert( (from_region->is_young() && young_index >  0) ||
4733          (!from_region->is_young() && young_index == 0), "invariant" );
4734   G1CollectorPolicy* g1p = _g1->g1_policy();
4735   markOop m = old->mark();
4736   int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
4737                                            : m->age();
4738   GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
4739                                                              word_sz);
4740   HeapWord* obj_ptr = _par_scan_state->allocate(alloc_purpose, word_sz);
4741 #ifndef PRODUCT
4742   // Should this evacuation fail?
4743   if (_g1->evacuation_should_fail()) {
4744     if (obj_ptr != NULL) {
4745       _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz);
4746       obj_ptr = NULL;
4747     }
4748   }
4749 #endif // !PRODUCT
4750 
4751   if (obj_ptr == NULL) {
4752     // This will either forward-to-self, or detect that someone else has
4753     // installed a forwarding pointer.
4754     return _g1->handle_evacuation_failure_par(_par_scan_state, old);
4755   }
4756 
4757   oop obj = oop(obj_ptr);
4758 
4759   // We're going to allocate linearly, so might as well prefetch ahead.
4760   Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
4761 
4762   oop forward_ptr = old->forward_to_atomic(obj);
4763   if (forward_ptr == NULL) {
4764     Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
4765     if (g1p->track_object_age(alloc_purpose)) {
4766       // We could simply do obj->incr_age(). However, this causes a
4767       // performance issue. obj->incr_age() will first check whether
4768       // the object has a displaced mark by checking its mark word;
4769       // getting the mark word from the new location of the object
4770       // stalls. So, given that we already have the mark word and we
4771       // are about to install it anyway, it's better to increase the
4772       // age on the mark word, when the object does not have a
4773       // displaced mark word. We're not expecting many objects to have
4774       // a displaced marked word, so that case is not optimized
4775       // further (it could be...) and we simply call obj->incr_age().
4776 
4777       if (m->has_displaced_mark_helper()) {
4778         // in this case, we have to install the mark word first,
4779         // otherwise obj looks to be forwarded (the old mark word,
4780         // which contains the forward pointer, was copied)
4781         obj->set_mark(m);
4782         obj->incr_age();
4783       } else {
4784         m = m->incr_age();
4785         obj->set_mark(m);
4786       }
4787       _par_scan_state->age_table()->add(obj, word_sz);
4788     } else {
4789       obj->set_mark(m);
4790     }
4791 
4792     size_t* surv_young_words = _par_scan_state->surviving_young_words();
4793     surv_young_words[young_index] += word_sz;
4794 
4795     if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
4796       // We keep track of the next start index in the length field of
4797       // the to-space object. The actual length can be found in the
4798       // length field of the from-space object.
4799       arrayOop(obj)->set_length(0);
4800       oop* old_p = set_partial_array_mask(old);
4801       _par_scan_state->push_on_queue(old_p);
4802     } else {
4803       // No point in using the slower heap_region_containing() method,
4804       // given that we know obj is in the heap.
4805       _scanner.set_region(_g1->heap_region_containing_raw(obj));
4806       obj->oop_iterate_backwards(&_scanner);
4807     }
4808   } else {
4809     _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz);
4810     obj = forward_ptr;
4811   }
4812   return obj;
4813 }
4814 
4815 template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_object>
4816 template <class T>
4817 void G1ParCopyClosure<do_gen_barrier, barrier, do_mark_object>
4818 ::do_oop_work(T* p) {
4819   oop obj = oopDesc::load_decode_heap_oop(p);
4820   assert(barrier != G1BarrierRS || obj != NULL,
4821          "Precondition: G1BarrierRS implies obj is non-NULL");
4822 
4823   assert(_worker_id == _par_scan_state->queue_num(), "sanity");
4824 
4825   // here the null check is implicit in the cset_fast_test() test
4826   if (_g1->in_cset_fast_test(obj)) {
4827     oop forwardee;
4828     if (obj->is_forwarded()) {
4829       forwardee = obj->forwardee();
4830     } else {
4831       forwardee = copy_to_survivor_space(obj);
4832     }
4833     assert(forwardee != NULL, "forwardee should not be NULL");
4834     oopDesc::encode_store_heap_oop(p, forwardee);
4835     if (do_mark_object && forwardee != obj) {
4836       // If the object is self-forwarded we don't need to explicitly
4837       // mark it, the evacuation failure protocol will do so.
4838       mark_forwarded_object(obj, forwardee);
4839     }
4840 
4841     // When scanning the RS, we only care about objs in CS.
4842     if (barrier == G1BarrierRS) {
4843       _par_scan_state->update_rs(_from, p, _worker_id);
4844     }
4845   } else {
4846     // The object is not in collection set. If we're a root scanning
4847     // closure during an initial mark pause (i.e. do_mark_object will
4848     // be true) then attempt to mark the object.
4849     if (do_mark_object && _g1->is_in_g1_reserved(obj)) {
4850       mark_object(obj);
4851     }
4852   }
4853 
4854   if (barrier == G1BarrierEvac && obj != NULL) {
4855     _par_scan_state->update_rs(_from, p, _worker_id);
4856   }
4857 
4858   if (do_gen_barrier && obj != NULL) {
4859     par_do_barrier(p);
4860   }
4861 }
4862 
4863 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(oop* p);
4864 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(narrowOop* p);
4865 
4866 template <class T> void G1ParScanPartialArrayClosure::do_oop_nv(T* p) {
4867   assert(has_partial_array_mask(p), "invariant");
4868   oop from_obj = clear_partial_array_mask(p);
4869 
4870   assert(Universe::heap()->is_in_reserved(from_obj), "must be in heap.");
4871   assert(from_obj->is_objArray(), "must be obj array");
4872   objArrayOop from_obj_array = objArrayOop(from_obj);
4873   // The from-space object contains the real length.
4874   int length                 = from_obj_array->length();
4875 
4876   assert(from_obj->is_forwarded(), "must be forwarded");
4877   oop to_obj                 = from_obj->forwardee();
4878   assert(from_obj != to_obj, "should not be chunking self-forwarded objects");
4879   objArrayOop to_obj_array   = objArrayOop(to_obj);
4880   // We keep track of the next start index in the length field of the
4881   // to-space object.
4882   int next_index             = to_obj_array->length();
4883   assert(0 <= next_index && next_index < length,
4884          err_msg("invariant, next index: %d, length: %d", next_index, length));
4885 
4886   int start                  = next_index;
4887   int end                    = length;
4888   int remainder              = end - start;
4889   // We'll try not to push a range that's smaller than ParGCArrayScanChunk.
4890   if (remainder > 2 * ParGCArrayScanChunk) {
4891     end = start + ParGCArrayScanChunk;
4892     to_obj_array->set_length(end);
4893     // Push the remainder before we process the range in case another
4894     // worker has run out of things to do and can steal it.
4895     oop* from_obj_p = set_partial_array_mask(from_obj);
4896     _par_scan_state->push_on_queue(from_obj_p);
4897   } else {
4898     assert(length == end, "sanity");
4899     // We'll process the final range for this object. Restore the length
4900     // so that the heap remains parsable in case of evacuation failure.
4901     to_obj_array->set_length(end);
4902   }
4903   _scanner.set_region(_g1->heap_region_containing_raw(to_obj));
4904   // Process indexes [start,end). It will also process the header
4905   // along with the first chunk (i.e., the chunk with start == 0).
4906   // Note that at this point the length field of to_obj_array is not
4907   // correct given that we are using it to keep track of the next
4908   // start index. oop_iterate_range() (thankfully!) ignores the length
4909   // field and only relies on the start / end parameters.  It does
4910   // however return the size of the object which will be incorrect. So
4911   // we have to ignore it even if we wanted to use it.
4912   to_obj_array->oop_iterate_range(&_scanner, start, end);
4913 }
4914 
4915 class G1ParEvacuateFollowersClosure : public VoidClosure {
4916 protected:
4917   G1CollectedHeap*              _g1h;
4918   G1ParScanThreadState*         _par_scan_state;
4919   RefToScanQueueSet*            _queues;
4920   ParallelTaskTerminator*       _terminator;
4921 
4922   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
4923   RefToScanQueueSet*      queues()         { return _queues; }
4924   ParallelTaskTerminator* terminator()     { return _terminator; }
4925 
4926 public:
4927   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4928                                 G1ParScanThreadState* par_scan_state,
4929                                 RefToScanQueueSet* queues,
4930                                 ParallelTaskTerminator* terminator)
4931     : _g1h(g1h), _par_scan_state(par_scan_state),
4932       _queues(queues), _terminator(terminator) {}
4933 
4934   void do_void();
4935 
4936 private:
4937   inline bool offer_termination();
4938 };
4939 
4940 bool G1ParEvacuateFollowersClosure::offer_termination() {
4941   G1ParScanThreadState* const pss = par_scan_state();
4942   pss->start_term_time();
4943   const bool res = terminator()->offer_termination();
4944   pss->end_term_time();
4945   return res;
4946 }
4947 
4948 void G1ParEvacuateFollowersClosure::do_void() {
4949   StarTask stolen_task;
4950   G1ParScanThreadState* const pss = par_scan_state();
4951   pss->trim_queue();
4952 
4953   do {
4954     while (queues()->steal(pss->queue_num(), pss->hash_seed(), stolen_task)) {
4955       assert(pss->verify_task(stolen_task), "sanity");
4956       if (stolen_task.is_narrow()) {
4957         pss->deal_with_reference((narrowOop*) stolen_task);
4958       } else {
4959         pss->deal_with_reference((oop*) stolen_task);
4960       }
4961 
4962       // We've just processed a reference and we might have made
4963       // available new entries on the queues. So we have to make sure
4964       // we drain the queues as necessary.
4965       pss->trim_queue();
4966     }
4967   } while (!offer_termination());
4968 
4969   pss->retire_alloc_buffers();
4970 }
4971 
4972 class G1ParTask : public AbstractGangTask {
4973 protected:
4974   G1CollectedHeap*       _g1h;
4975   RefToScanQueueSet      *_queues;
4976   ParallelTaskTerminator _terminator;
4977   uint _n_workers;
4978 
4979   Mutex _stats_lock;
4980   Mutex* stats_lock() { return &_stats_lock; }
4981 
4982   size_t getNCards() {
4983     return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
4984       / G1BlockOffsetSharedArray::N_bytes;
4985   }
4986 
4987 public:
4988   G1ParTask(G1CollectedHeap* g1h,
4989             RefToScanQueueSet *task_queues)
4990     : AbstractGangTask("G1 collection"),
4991       _g1h(g1h),
4992       _queues(task_queues),
4993       _terminator(0, _queues),
4994       _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
4995   {}
4996 
4997   RefToScanQueueSet* queues() { return _queues; }
4998 
4999   RefToScanQueue *work_queue(int i) {
5000     return queues()->queue(i);
5001   }
5002 
5003   ParallelTaskTerminator* terminator() { return &_terminator; }
5004 
5005   virtual void set_for_termination(int active_workers) {
5006     // This task calls set_n_termination() in par_non_clean_card_iterate_work()
5007     // in the young space (_par_seq_tasks) in the G1 heap
5008     // for SequentialSubTasksDone.
5009     // This task also uses SubTasksDone in SharedHeap and G1CollectedHeap
5010     // both of which need setting by set_n_termination().
5011     _g1h->SharedHeap::set_n_termination(active_workers);
5012     _g1h->set_n_termination(active_workers);
5013     terminator()->reset_for_reuse(active_workers);
5014     _n_workers = active_workers;
5015   }
5016 
5017   void work(uint worker_id) {
5018     if (worker_id >= _n_workers) return;  // no work needed this round
5019 
5020     double start_time_ms = os::elapsedTime() * 1000.0;
5021     _g1h->g1_policy()->phase_times()->record_gc_worker_start_time(worker_id, start_time_ms);
5022 
5023     {
5024       ResourceMark rm;
5025       HandleMark   hm;
5026 
5027       ReferenceProcessor*             rp = _g1h->ref_processor_stw();
5028 
5029       G1ParScanThreadState            pss(_g1h, worker_id);
5030       G1ParScanHeapEvacClosure        scan_evac_cl(_g1h, &pss, rp);
5031       G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, rp);
5032       G1ParScanPartialArrayClosure    partial_scan_cl(_g1h, &pss, rp);
5033 
5034       pss.set_evac_closure(&scan_evac_cl);
5035       pss.set_evac_failure_closure(&evac_failure_cl);
5036       pss.set_partial_scan_closure(&partial_scan_cl);
5037 
5038       G1ParScanExtRootClosure        only_scan_root_cl(_g1h, &pss, rp);
5039       G1ParScanPermClosure           only_scan_perm_cl(_g1h, &pss, rp);
5040 
5041       G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss, rp);
5042       G1ParScanAndMarkPermClosure    scan_mark_perm_cl(_g1h, &pss, rp);
5043 
5044       OopClosure*                    scan_root_cl = &only_scan_root_cl;
5045       OopsInHeapRegionClosure*       scan_perm_cl = &only_scan_perm_cl;
5046 
5047       if (_g1h->g1_policy()->during_initial_mark_pause()) {
5048         // We also need to mark copied objects.
5049         scan_root_cl = &scan_mark_root_cl;
5050         scan_perm_cl = &scan_mark_perm_cl;
5051       }
5052 
5053       G1ParPushHeapRSClosure          push_heap_rs_cl(_g1h, &pss);
5054 
5055       pss.start_strong_roots();
5056       _g1h->g1_process_strong_roots(/* not collecting perm */ false,
5057                                     SharedHeap::SO_AllClasses,
5058                                     scan_root_cl,
5059                                     &push_heap_rs_cl,
5060                                     scan_perm_cl,
5061                                     worker_id,
5062                                     /* manages_code_roots */ true);
5063       pss.end_strong_roots();
5064 
5065       {
5066         double start = os::elapsedTime();
5067         G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
5068         evac.do_void();
5069         double elapsed_ms = (os::elapsedTime()-start)*1000.0;
5070         double term_ms = pss.term_time()*1000.0;
5071         _g1h->g1_policy()->phase_times()->add_obj_copy_time(worker_id, elapsed_ms-term_ms);
5072         _g1h->g1_policy()->phase_times()->record_termination(worker_id, term_ms, pss.term_attempts());
5073       }
5074       _g1h->g1_policy()->record_thread_age_table(pss.age_table());
5075       _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
5076 
5077       if (ParallelGCVerbose) {
5078         MutexLocker x(stats_lock());
5079         pss.print_termination_stats(worker_id);
5080       }
5081 
5082       assert(pss.refs()->is_empty(), "should be empty");
5083 
5084       // Close the inner scope so that the ResourceMark and HandleMark
5085       // destructors are executed here and are included as part of the
5086       // "GC Worker Time".
5087     }
5088 
5089     double end_time_ms = os::elapsedTime() * 1000.0;
5090     _g1h->g1_policy()->phase_times()->record_gc_worker_end_time(worker_id, end_time_ms);
5091   }
5092 };
5093 
5094 // *** Common G1 Evacuation Stuff
5095 
5096 // This method is run in a GC worker.
5097 
5098 void
5099 G1CollectedHeap::
5100 g1_process_strong_roots(bool collecting_perm_gen,
5101                         ScanningOption so,
5102                         OopClosure* scan_non_heap_roots,
5103                         OopsInHeapRegionClosure* scan_rs,
5104                         OopsInGenClosure* scan_perm,
5105                         int worker_i,
5106                         bool manages_code_roots) {
5107 
5108   // First scan the strong roots, including the perm gen.
5109   double ext_roots_start = os::elapsedTime();
5110   double closure_app_time_sec = 0.0;
5111 
5112   BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
5113   BufferingOopsInGenClosure buf_scan_perm(scan_perm);
5114   buf_scan_perm.set_generation(perm_gen());
5115 
5116   assert(so & SO_CodeCache || scan_rs != NULL, "must scan code roots somehow");
5117   // Walk the code cache/strong code roots w/o buffering, because StarTask
5118   // cannot handle unaligned oop locations.
5119   CodeBlobToOopClosure eager_scan_code_roots(scan_non_heap_roots, true /* do_marking */);
5120 
5121   process_strong_roots(false, // no scoping; this is parallel code
5122                        collecting_perm_gen, so,
5123                        &buf_scan_non_heap_roots,
5124                        &eager_scan_code_roots,
5125                        &buf_scan_perm,
5126                        manages_code_roots);
5127 
5128   // Now the CM ref_processor roots.
5129   if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
5130     // We need to treat the discovered reference lists of the
5131     // concurrent mark ref processor as roots and keep entries
5132     // (which are added by the marking threads) on them live
5133     // until they can be processed at the end of marking.
5134     ref_processor_cm()->weak_oops_do(&buf_scan_non_heap_roots);
5135   }
5136 
5137   // Finish up any enqueued closure apps (attributed as object copy time).
5138   buf_scan_non_heap_roots.done();
5139   buf_scan_perm.done();
5140 
5141   double obj_copy_time_sec = buf_scan_perm.closure_app_seconds() +
5142                                 buf_scan_non_heap_roots.closure_app_seconds();
5143   g1_policy()->phase_times()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
5144 
5145   double ext_root_time_ms =
5146     ((os::elapsedTime() - ext_roots_start) - obj_copy_time_sec) * 1000.0;
5147 
5148   g1_policy()->phase_times()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
5149 
5150   // During conc marking we have to filter the per-thread SATB buffers
5151   // to make sure we remove any oops into the CSet (which will show up
5152   // as implicitly live).
5153   double satb_filtering_ms = 0.0;
5154   if (!_process_strong_tasks->is_task_claimed(G1H_PS_filter_satb_buffers)) {
5155     if (mark_in_progress()) {
5156       double satb_filter_start = os::elapsedTime();
5157 
5158       JavaThread::satb_mark_queue_set().filter_thread_buffers();
5159 
5160       satb_filtering_ms = (os::elapsedTime() - satb_filter_start) * 1000.0;
5161     }
5162   }
5163   g1_policy()->phase_times()->record_satb_filtering_time(worker_i, satb_filtering_ms);
5164 
5165   // If this is an initial mark pause, and we're not scanning
5166   // the entire code cache, we need to mark the oops in the
5167   // strong code root lists for the regions that are not in
5168   // the collection set.
5169   // Note all threads participate in this set of root tasks.
5170   double mark_strong_code_roots_ms = 0.0;
5171   if (g1_policy()->during_initial_mark_pause() && !(so & SO_CodeCache)) {
5172     double mark_strong_roots_start = os::elapsedTime();
5173     mark_strong_code_roots(worker_i);
5174     mark_strong_code_roots_ms = (os::elapsedTime() - mark_strong_roots_start) * 1000.0;
5175   }
5176   g1_policy()->phase_times()->record_strong_code_root_mark_time(worker_i, mark_strong_code_roots_ms);
5177 
5178   // Now scan the complement of the collection set.
5179   if (scan_rs != NULL) {
5180     g1_rem_set()->oops_into_collection_set_do(scan_rs, &eager_scan_code_roots, worker_i);
5181   }
5182 
5183   _process_strong_tasks->all_tasks_completed();
5184 }
5185 
5186 void
5187 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure,
5188                                        OopClosure* non_root_closure) {
5189   CodeBlobToOopClosure roots_in_blobs(root_closure, /*do_marking=*/ false);
5190   SharedHeap::process_weak_roots(root_closure, &roots_in_blobs, non_root_closure);
5191 }
5192 
5193 class G1StringSymbolTableUnlinkTask : public AbstractGangTask {
5194 private:
5195   BoolObjectClosure* _is_alive;
5196   int _initial_string_table_size;
5197   int _initial_symbol_table_size;
5198 
5199   bool  _process_strings;
5200   int _strings_processed;
5201   int _strings_removed;
5202 
5203   bool  _process_symbols;
5204   int _symbols_processed;
5205   int _symbols_removed;
5206 
5207   bool _do_in_parallel;
5208 public:
5209   G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :
5210     AbstractGangTask("Par String/Symbol table unlink"), _is_alive(is_alive),
5211     _do_in_parallel(G1CollectedHeap::use_parallel_gc_threads()),
5212     _process_strings(process_strings), _strings_processed(0), _strings_removed(0),
5213     _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {
5214 
5215     _initial_string_table_size = StringTable::the_table()->table_size();
5216     _initial_symbol_table_size = SymbolTable::the_table()->table_size();
5217     if (process_strings) {
5218       StringTable::clear_parallel_claimed_index();
5219     }
5220     if (process_symbols) {
5221       SymbolTable::clear_parallel_claimed_index();
5222     }
5223   }
5224 
5225   ~G1StringSymbolTableUnlinkTask() {
5226     guarantee(!_process_strings || !_do_in_parallel || StringTable::parallel_claimed_index() >= _initial_string_table_size,
5227               err_msg("claim value "INT32_FORMAT" after unlink less than initial string table size "INT32_FORMAT,
5228                       StringTable::parallel_claimed_index(), _initial_string_table_size));
5229     guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
5230               err_msg("claim value "INT32_FORMAT" after unlink less than initial symbol table size "INT32_FORMAT,
5231                       SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
5232   }
5233 
5234   void work(uint worker_id) {
5235     if (_do_in_parallel) {
5236       int strings_processed = 0;
5237       int strings_removed = 0;
5238       int symbols_processed = 0;
5239       int symbols_removed = 0;
5240       if (_process_strings) {
5241         StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed);
5242         Atomic::add(strings_processed, &_strings_processed);
5243         Atomic::add(strings_removed, &_strings_removed);
5244       }
5245       if (_process_symbols) {
5246         SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed);
5247         Atomic::add(symbols_processed, &_symbols_processed);
5248         Atomic::add(symbols_removed, &_symbols_removed);
5249       }
5250     } else {
5251       if (_process_strings) {
5252         StringTable::unlink(_is_alive, &_strings_processed, &_strings_removed);
5253       }
5254       if (_process_symbols) {
5255         SymbolTable::unlink(&_symbols_processed, &_symbols_removed);
5256       }
5257     }
5258   }
5259 
5260   size_t strings_processed() const { return (size_t)_strings_processed; }
5261   size_t strings_removed()   const { return (size_t)_strings_removed; }
5262 
5263   size_t symbols_processed() const { return (size_t)_symbols_processed; }
5264   size_t symbols_removed()   const { return (size_t)_symbols_removed; }
5265 };
5266 
5267 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
5268                                                      bool process_strings, bool process_symbols) {
5269   uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5270                    _g1h->workers()->active_workers() : 1);
5271 
5272   G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
5273   if (G1CollectedHeap::use_parallel_gc_threads()) {
5274     set_par_threads(n_workers);
5275     workers()->run_task(&g1_unlink_task);
5276     set_par_threads(0);
5277   } else {
5278     g1_unlink_task.work(0);
5279   }
5280   if (G1TraceStringSymbolTableScrubbing) {
5281     gclog_or_tty->print_cr("Cleaned string and symbol table, "
5282                            "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
5283                            "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
5284                            g1_unlink_task.strings_processed(), g1_unlink_task.strings_removed(),
5285                            g1_unlink_task.symbols_processed(), g1_unlink_task.symbols_removed());
5286   }
5287 }
5288 
5289 // Weak Reference Processing support
5290 
5291 // An always "is_alive" closure that is used to preserve referents.
5292 // If the object is non-null then it's alive.  Used in the preservation
5293 // of referent objects that are pointed to by reference objects
5294 // discovered by the CM ref processor.
5295 class G1AlwaysAliveClosure: public BoolObjectClosure {
5296   G1CollectedHeap* _g1;
5297 public:
5298   G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5299   void do_object(oop p) { assert(false, "Do not call."); }
5300   bool do_object_b(oop p) {
5301     if (p != NULL) {
5302       return true;
5303     }
5304     return false;
5305   }
5306 };
5307 
5308 bool G1STWIsAliveClosure::do_object_b(oop p) {
5309   // An object is reachable if it is outside the collection set,
5310   // or is inside and copied.
5311   return !_g1->obj_in_cs(p) || p->is_forwarded();
5312 }
5313 
5314 // Non Copying Keep Alive closure
5315 class G1KeepAliveClosure: public OopClosure {
5316   G1CollectedHeap* _g1;
5317 public:
5318   G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5319   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
5320   void do_oop(      oop* p) {
5321     oop obj = *p;
5322 
5323     if (_g1->obj_in_cs(obj)) {
5324       assert( obj->is_forwarded(), "invariant" );
5325       *p = obj->forwardee();
5326     }
5327   }
5328 };
5329 
5330 // Copying Keep Alive closure - can be called from both
5331 // serial and parallel code as long as different worker
5332 // threads utilize different G1ParScanThreadState instances
5333 // and different queues.
5334 
5335 class G1CopyingKeepAliveClosure: public OopClosure {
5336   G1CollectedHeap*         _g1h;
5337   OopClosure*              _copy_non_heap_obj_cl;
5338   OopsInHeapRegionClosure* _copy_perm_obj_cl;
5339   G1ParScanThreadState*    _par_scan_state;
5340 
5341 public:
5342   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
5343                             OopClosure* non_heap_obj_cl,
5344                             OopsInHeapRegionClosure* perm_obj_cl,
5345                             G1ParScanThreadState* pss):
5346     _g1h(g1h),
5347     _copy_non_heap_obj_cl(non_heap_obj_cl),
5348     _copy_perm_obj_cl(perm_obj_cl),
5349     _par_scan_state(pss)
5350   {}
5351 
5352   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
5353   virtual void do_oop(      oop* p) { do_oop_work(p); }
5354 
5355   template <class T> void do_oop_work(T* p) {
5356     oop obj = oopDesc::load_decode_heap_oop(p);
5357 
5358     if (_g1h->obj_in_cs(obj)) {
5359       // If the referent object has been forwarded (either copied
5360       // to a new location or to itself in the event of an
5361       // evacuation failure) then we need to update the reference
5362       // field and, if both reference and referent are in the G1
5363       // heap, update the RSet for the referent.
5364       //
5365       // If the referent has not been forwarded then we have to keep
5366       // it alive by policy. Therefore we have copy the referent.
5367       //
5368       // If the reference field is in the G1 heap then we can push
5369       // on the PSS queue. When the queue is drained (after each
5370       // phase of reference processing) the object and it's followers
5371       // will be copied, the reference field set to point to the
5372       // new location, and the RSet updated. Otherwise we need to
5373       // use the the non-heap or perm closures directly to copy
5374       // the referent object and update the pointer, while avoiding
5375       // updating the RSet.
5376 
5377       if (_g1h->is_in_g1_reserved(p)) {
5378         _par_scan_state->push_on_queue(p);
5379       } else {
5380         // The reference field is not in the G1 heap.
5381         if (_g1h->perm_gen()->is_in(p)) {
5382           _copy_perm_obj_cl->do_oop(p);
5383         } else {
5384           _copy_non_heap_obj_cl->do_oop(p);
5385         }
5386       }
5387     }
5388   }
5389 };
5390 
5391 // Serial drain queue closure. Called as the 'complete_gc'
5392 // closure for each discovered list in some of the
5393 // reference processing phases.
5394 
5395 class G1STWDrainQueueClosure: public VoidClosure {
5396 protected:
5397   G1CollectedHeap* _g1h;
5398   G1ParScanThreadState* _par_scan_state;
5399 
5400   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
5401 
5402 public:
5403   G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
5404     _g1h(g1h),
5405     _par_scan_state(pss)
5406   { }
5407 
5408   void do_void() {
5409     G1ParScanThreadState* const pss = par_scan_state();
5410     pss->trim_queue();
5411   }
5412 };
5413 
5414 // Parallel Reference Processing closures
5415 
5416 // Implementation of AbstractRefProcTaskExecutor for parallel reference
5417 // processing during G1 evacuation pauses.
5418 
5419 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
5420 private:
5421   G1CollectedHeap*   _g1h;
5422   RefToScanQueueSet* _queues;
5423   FlexibleWorkGang*  _workers;
5424   int                _active_workers;
5425 
5426 public:
5427   G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
5428                         FlexibleWorkGang* workers,
5429                         RefToScanQueueSet *task_queues,
5430                         int n_workers) :
5431     _g1h(g1h),
5432     _queues(task_queues),
5433     _workers(workers),
5434     _active_workers(n_workers)
5435   {
5436     assert(n_workers > 0, "shouldn't call this otherwise");
5437   }
5438 
5439   // Executes the given task using concurrent marking worker threads.
5440   virtual void execute(ProcessTask& task);
5441   virtual void execute(EnqueueTask& task);
5442 };
5443 
5444 // Gang task for possibly parallel reference processing
5445 
5446 class G1STWRefProcTaskProxy: public AbstractGangTask {
5447   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
5448   ProcessTask&     _proc_task;
5449   G1CollectedHeap* _g1h;
5450   RefToScanQueueSet *_task_queues;
5451   ParallelTaskTerminator* _terminator;
5452 
5453 public:
5454   G1STWRefProcTaskProxy(ProcessTask& proc_task,
5455                      G1CollectedHeap* g1h,
5456                      RefToScanQueueSet *task_queues,
5457                      ParallelTaskTerminator* terminator) :
5458     AbstractGangTask("Process reference objects in parallel"),
5459     _proc_task(proc_task),
5460     _g1h(g1h),
5461     _task_queues(task_queues),
5462     _terminator(terminator)
5463   {}
5464 
5465   virtual void work(uint worker_id) {
5466     // The reference processing task executed by a single worker.
5467     ResourceMark rm;
5468     HandleMark   hm;
5469 
5470     G1STWIsAliveClosure is_alive(_g1h);
5471 
5472     G1ParScanThreadState pss(_g1h, worker_id);
5473 
5474     G1ParScanHeapEvacClosure        scan_evac_cl(_g1h, &pss, NULL);
5475     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5476     G1ParScanPartialArrayClosure    partial_scan_cl(_g1h, &pss, NULL);
5477 
5478     pss.set_evac_closure(&scan_evac_cl);
5479     pss.set_evac_failure_closure(&evac_failure_cl);
5480     pss.set_partial_scan_closure(&partial_scan_cl);
5481 
5482     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
5483     G1ParScanPermClosure           only_copy_perm_cl(_g1h, &pss, NULL);
5484 
5485     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5486     G1ParScanAndMarkPermClosure    copy_mark_perm_cl(_g1h, &pss, NULL);
5487 
5488     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5489     OopsInHeapRegionClosure*       copy_perm_cl = &only_copy_perm_cl;
5490 
5491     if (_g1h->g1_policy()->during_initial_mark_pause()) {
5492       // We also need to mark copied objects.
5493       copy_non_heap_cl = &copy_mark_non_heap_cl;
5494       copy_perm_cl = &copy_mark_perm_cl;
5495     }
5496 
5497     // Keep alive closure.
5498     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_perm_cl, &pss);
5499 
5500     // Complete GC closure
5501     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);
5502 
5503     // Call the reference processing task's work routine.
5504     _proc_task.work(worker_id, is_alive, keep_alive, drain_queue);
5505 
5506     // Note we cannot assert that the refs array is empty here as not all
5507     // of the processing tasks (specifically phase2 - pp2_work) execute
5508     // the complete_gc closure (which ordinarily would drain the queue) so
5509     // the queue may not be empty.
5510   }
5511 };
5512 
5513 // Driver routine for parallel reference processing.
5514 // Creates an instance of the ref processing gang
5515 // task and has the worker threads execute it.
5516 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {
5517   assert(_workers != NULL, "Need parallel worker threads.");
5518 
5519   ParallelTaskTerminator terminator(_active_workers, _queues);
5520   G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator);
5521 
5522   _g1h->set_par_threads(_active_workers);
5523   _workers->run_task(&proc_task_proxy);
5524   _g1h->set_par_threads(0);
5525 }
5526 
5527 // Gang task for parallel reference enqueueing.
5528 
5529 class G1STWRefEnqueueTaskProxy: public AbstractGangTask {
5530   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
5531   EnqueueTask& _enq_task;
5532 
5533 public:
5534   G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) :
5535     AbstractGangTask("Enqueue reference objects in parallel"),
5536     _enq_task(enq_task)
5537   { }
5538 
5539   virtual void work(uint worker_id) {
5540     _enq_task.work(worker_id);
5541   }
5542 };
5543 
5544 // Driver routine for parallel reference enqueueing.
5545 // Creates an instance of the ref enqueueing gang
5546 // task and has the worker threads execute it.
5547 
5548 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
5549   assert(_workers != NULL, "Need parallel worker threads.");
5550 
5551   G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task);
5552 
5553   _g1h->set_par_threads(_active_workers);
5554   _workers->run_task(&enq_task_proxy);
5555   _g1h->set_par_threads(0);
5556 }
5557 
5558 // End of weak reference support closures
5559 
5560 // Abstract task used to preserve (i.e. copy) any referent objects
5561 // that are in the collection set and are pointed to by reference
5562 // objects discovered by the CM ref processor.
5563 
5564 class G1ParPreserveCMReferentsTask: public AbstractGangTask {
5565 protected:
5566   G1CollectedHeap* _g1h;
5567   RefToScanQueueSet      *_queues;
5568   ParallelTaskTerminator _terminator;
5569   uint _n_workers;
5570 
5571 public:
5572   G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h,int workers, RefToScanQueueSet *task_queues) :
5573     AbstractGangTask("ParPreserveCMReferents"),
5574     _g1h(g1h),
5575     _queues(task_queues),
5576     _terminator(workers, _queues),
5577     _n_workers(workers)
5578   { }
5579 
5580   void work(uint worker_id) {
5581     ResourceMark rm;
5582     HandleMark   hm;
5583 
5584     G1ParScanThreadState            pss(_g1h, worker_id);
5585     G1ParScanHeapEvacClosure        scan_evac_cl(_g1h, &pss, NULL);
5586     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5587     G1ParScanPartialArrayClosure    partial_scan_cl(_g1h, &pss, NULL);
5588 
5589     pss.set_evac_closure(&scan_evac_cl);
5590     pss.set_evac_failure_closure(&evac_failure_cl);
5591     pss.set_partial_scan_closure(&partial_scan_cl);
5592 
5593     assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
5594 
5595 
5596     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
5597     G1ParScanPermClosure           only_copy_perm_cl(_g1h, &pss, NULL);
5598 
5599     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5600     G1ParScanAndMarkPermClosure    copy_mark_perm_cl(_g1h, &pss, NULL);
5601 
5602     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5603     OopsInHeapRegionClosure*       copy_perm_cl = &only_copy_perm_cl;
5604 
5605     if (_g1h->g1_policy()->during_initial_mark_pause()) {
5606       // We also need to mark copied objects.
5607       copy_non_heap_cl = &copy_mark_non_heap_cl;
5608       copy_perm_cl = &copy_mark_perm_cl;
5609     }
5610 
5611     // Is alive closure
5612     G1AlwaysAliveClosure always_alive(_g1h);
5613 
5614     // Copying keep alive closure. Applied to referent objects that need
5615     // to be copied.
5616     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_perm_cl, &pss);
5617 
5618     ReferenceProcessor* rp = _g1h->ref_processor_cm();
5619 
5620     uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q();
5621     uint stride = MIN2(MAX2(_n_workers, 1U), limit);
5622 
5623     // limit is set using max_num_q() - which was set using ParallelGCThreads.
5624     // So this must be true - but assert just in case someone decides to
5625     // change the worker ids.
5626     assert(0 <= worker_id && worker_id < limit, "sanity");
5627     assert(!rp->discovery_is_atomic(), "check this code");
5628 
5629     // Select discovered lists [i, i+stride, i+2*stride,...,limit)
5630     for (uint idx = worker_id; idx < limit; idx += stride) {
5631       DiscoveredList& ref_list = rp->discovered_refs()[idx];
5632 
5633       DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive);
5634       while (iter.has_next()) {
5635         // Since discovery is not atomic for the CM ref processor, we
5636         // can see some null referent objects.
5637         iter.load_ptrs(DEBUG_ONLY(true));
5638         oop ref = iter.obj();
5639 
5640         // This will filter nulls.
5641         if (iter.is_referent_alive()) {
5642           iter.make_referent_alive();
5643         }
5644         iter.move_to_next();
5645       }
5646     }
5647 
5648     // Drain the queue - which may cause stealing
5649     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);
5650     drain_queue.do_void();
5651     // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure
5652     assert(pss.refs()->is_empty(), "should be");
5653   }
5654 };
5655 
5656 // Weak Reference processing during an evacuation pause (part 1).
5657 void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
5658   double ref_proc_start = os::elapsedTime();
5659 
5660   ReferenceProcessor* rp = _ref_processor_stw;
5661   assert(rp->discovery_enabled(), "should have been enabled");
5662 
5663   // Any reference objects, in the collection set, that were 'discovered'
5664   // by the CM ref processor should have already been copied (either by
5665   // applying the external root copy closure to the discovered lists, or
5666   // by following an RSet entry).
5667   //
5668   // But some of the referents, that are in the collection set, that these
5669   // reference objects point to may not have been copied: the STW ref
5670   // processor would have seen that the reference object had already
5671   // been 'discovered' and would have skipped discovering the reference,
5672   // but would not have treated the reference object as a regular oop.
5673   // As a result the copy closure would not have been applied to the
5674   // referent object.
5675   //
5676   // We need to explicitly copy these referent objects - the references
5677   // will be processed at the end of remarking.
5678   //
5679   // We also need to do this copying before we process the reference
5680   // objects discovered by the STW ref processor in case one of these
5681   // referents points to another object which is also referenced by an
5682   // object discovered by the STW ref processor.
5683 
5684   assert(!G1CollectedHeap::use_parallel_gc_threads() ||
5685            no_of_gc_workers == workers()->active_workers(),
5686            "Need to reset active GC workers");
5687 
5688   set_par_threads(no_of_gc_workers);
5689   G1ParPreserveCMReferentsTask keep_cm_referents(this,
5690                                                  no_of_gc_workers,
5691                                                  _task_queues);
5692 
5693   if (G1CollectedHeap::use_parallel_gc_threads()) {
5694     workers()->run_task(&keep_cm_referents);
5695   } else {
5696     keep_cm_referents.work(0);
5697   }
5698 
5699   set_par_threads(0);
5700 
5701   // Closure to test whether a referent is alive.
5702   G1STWIsAliveClosure is_alive(this);
5703 
5704   // Even when parallel reference processing is enabled, the processing
5705   // of JNI refs is serial and performed serially by the current thread
5706   // rather than by a worker. The following PSS will be used for processing
5707   // JNI refs.
5708 
5709   // Use only a single queue for this PSS.
5710   G1ParScanThreadState pss(this, 0);
5711 
5712   // We do not embed a reference processor in the copying/scanning
5713   // closures while we're actually processing the discovered
5714   // reference objects.
5715   G1ParScanHeapEvacClosure        scan_evac_cl(this, &pss, NULL);
5716   G1ParScanHeapEvacFailureClosure evac_failure_cl(this, &pss, NULL);
5717   G1ParScanPartialArrayClosure    partial_scan_cl(this, &pss, NULL);
5718 
5719   pss.set_evac_closure(&scan_evac_cl);
5720   pss.set_evac_failure_closure(&evac_failure_cl);
5721   pss.set_partial_scan_closure(&partial_scan_cl);
5722 
5723   assert(pss.refs()->is_empty(), "pre-condition");
5724 
5725   G1ParScanExtRootClosure        only_copy_non_heap_cl(this, &pss, NULL);
5726   G1ParScanPermClosure           only_copy_perm_cl(this, &pss, NULL);
5727 
5728   G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);
5729   G1ParScanAndMarkPermClosure    copy_mark_perm_cl(this, &pss, NULL);
5730 
5731   OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5732   OopsInHeapRegionClosure*       copy_perm_cl = &only_copy_perm_cl;
5733 
5734   if (_g1h->g1_policy()->during_initial_mark_pause()) {
5735     // We also need to mark copied objects.
5736     copy_non_heap_cl = &copy_mark_non_heap_cl;
5737     copy_perm_cl = &copy_mark_perm_cl;
5738   }
5739 
5740   // Keep alive closure.
5741   G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, copy_perm_cl, &pss);
5742 
5743   // Serial Complete GC closure
5744   G1STWDrainQueueClosure drain_queue(this, &pss);
5745 
5746   // Setup the soft refs policy...
5747   rp->setup_policy(false);
5748 
5749   ReferenceProcessorStats stats;
5750   if (!rp->processing_is_mt()) {
5751     // Serial reference processing...
5752     stats = rp->process_discovered_references(&is_alive,
5753                                               &keep_alive,
5754                                               &drain_queue,
5755                                               NULL,
5756                                               _gc_timer_stw);
5757   } else {
5758     // Parallel reference processing
5759     assert(rp->num_q() == no_of_gc_workers, "sanity");
5760     assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5761 
5762     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5763     stats = rp->process_discovered_references(&is_alive,
5764                                               &keep_alive,
5765                                               &drain_queue,
5766                                               &par_task_executor,
5767                                               _gc_timer_stw);
5768   }
5769 
5770   _gc_tracer_stw->report_gc_reference_stats(stats);
5771   // We have completed copying any necessary live referent objects
5772   // (that were not copied during the actual pause) so we can
5773   // retire any active alloc buffers
5774   pss.retire_alloc_buffers();
5775   assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
5776 
5777   double ref_proc_time = os::elapsedTime() - ref_proc_start;
5778   g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
5779 }
5780 
5781 // Weak Reference processing during an evacuation pause (part 2).
5782 void G1CollectedHeap::enqueue_discovered_references(uint no_of_gc_workers) {
5783   double ref_enq_start = os::elapsedTime();
5784 
5785   ReferenceProcessor* rp = _ref_processor_stw;
5786   assert(!rp->discovery_enabled(), "should have been disabled as part of processing");
5787 
5788   // Now enqueue any remaining on the discovered lists on to
5789   // the pending list.
5790   if (!rp->processing_is_mt()) {
5791     // Serial reference processing...
5792     rp->enqueue_discovered_references();
5793   } else {
5794     // Parallel reference enqueueing
5795 
5796     assert(no_of_gc_workers == workers()->active_workers(),
5797            "Need to reset active workers");
5798     assert(rp->num_q() == no_of_gc_workers, "sanity");
5799     assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5800 
5801     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5802     rp->enqueue_discovered_references(&par_task_executor);
5803   }
5804 
5805   rp->verify_no_references_recorded();
5806   assert(!rp->discovery_enabled(), "should have been disabled");
5807 
5808   // FIXME
5809   // CM's reference processing also cleans up the string and symbol tables.
5810   // Should we do that here also? We could, but it is a serial operation
5811   // and could significantly increase the pause time.
5812 
5813   double ref_enq_time = os::elapsedTime() - ref_enq_start;
5814   g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0);
5815 }
5816 
5817 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {
5818   _expand_heap_after_alloc_failure = true;
5819   _evacuation_failed = false;
5820 
5821   // Should G1EvacuationFailureALot be in effect for this GC?
5822   NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
5823 
5824   g1_rem_set()->prepare_for_oops_into_collection_set_do();
5825 
5826   // Disable the hot card cache.
5827   G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
5828   hot_card_cache->reset_hot_cache_claimed_index();
5829   hot_card_cache->set_use_cache(false);
5830 
5831   uint n_workers;
5832   if (G1CollectedHeap::use_parallel_gc_threads()) {
5833     n_workers =
5834       AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
5835                                      workers()->active_workers(),
5836                                      Threads::number_of_non_daemon_threads());
5837     assert(UseDynamicNumberOfGCThreads ||
5838            n_workers == workers()->total_workers(),
5839            "If not dynamic should be using all the  workers");
5840     workers()->set_active_workers(n_workers);
5841     set_par_threads(n_workers);
5842   } else {
5843     assert(n_par_threads() == 0,
5844            "Should be the original non-parallel value");
5845     n_workers = 1;
5846   }
5847 
5848   G1ParTask g1_par_task(this, _task_queues);
5849 
5850   init_for_evac_failure(NULL);
5851 
5852   rem_set()->prepare_for_younger_refs_iterate(true);
5853 
5854   assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
5855   double start_par_time_sec = os::elapsedTime();
5856   double end_par_time_sec;
5857 
5858   {
5859     StrongRootsScope srs(this);
5860 
5861     if (G1CollectedHeap::use_parallel_gc_threads()) {
5862       // The individual threads will set their evac-failure closures.
5863       if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();
5864       // These tasks use ShareHeap::_process_strong_tasks
5865       assert(UseDynamicNumberOfGCThreads ||
5866              workers()->active_workers() == workers()->total_workers(),
5867              "If not dynamic should be using all the  workers");
5868       workers()->run_task(&g1_par_task);
5869     } else {
5870       g1_par_task.set_for_termination(n_workers);
5871       g1_par_task.work(0);
5872     }
5873     end_par_time_sec = os::elapsedTime();
5874 
5875     // Closing the inner scope will execute the destructor
5876     // for the StrongRootsScope object. We record the current
5877     // elapsed time before closing the scope so that time
5878     // taken for the SRS destructor is NOT included in the
5879     // reported parallel time.
5880   }
5881 
5882   double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0;
5883   g1_policy()->phase_times()->record_par_time(par_time_ms);
5884 
5885   double code_root_fixup_time_ms =
5886         (os::elapsedTime() - end_par_time_sec) * 1000.0;
5887   g1_policy()->phase_times()->record_code_root_fixup_time(code_root_fixup_time_ms);
5888 
5889   set_par_threads(0);
5890 
5891   // Process any discovered reference objects - we have
5892   // to do this _before_ we retire the GC alloc regions
5893   // as we may have to copy some 'reachable' referent
5894   // objects (and their reachable sub-graphs) that were
5895   // not copied during the pause.
5896   process_discovered_references(n_workers);
5897 
5898   // Weak root processing.
5899   {
5900     G1STWIsAliveClosure is_alive(this);
5901     G1KeepAliveClosure keep_alive(this);
5902     JNIHandles::weak_oops_do(&is_alive, &keep_alive);
5903   }
5904 
5905   release_gc_alloc_regions(n_workers, evacuation_info);
5906   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
5907 
5908   // Reset and re-enable the hot card cache.
5909   // Note the counts for the cards in the regions in the
5910   // collection set are reset when the collection set is freed.
5911   hot_card_cache->reset_hot_cache();
5912   hot_card_cache->set_use_cache(true);
5913 
5914   // Migrate the strong code roots attached to each region in
5915   // the collection set. Ideally we would like to do this
5916   // after we have finished the scanning/evacuation of the
5917   // strong code roots for a particular heap region.
5918   migrate_strong_code_roots();
5919 
5920   if (g1_policy()->during_initial_mark_pause()) {
5921     // Reset the claim values set during marking the strong code roots
5922     reset_heap_region_claim_values();
5923   }
5924 
5925   finalize_for_evac_failure();
5926 
5927   if (evacuation_failed()) {
5928     remove_self_forwarding_pointers();
5929 
5930     // Reset the G1EvacuationFailureALot counters and flags
5931     // Note: the values are reset only when an actual
5932     // evacuation failure occurs.
5933     NOT_PRODUCT(reset_evacuation_should_fail();)
5934   }
5935 
5936   // Enqueue any remaining references remaining on the STW
5937   // reference processor's discovered lists. We need to do
5938   // this after the card table is cleaned (and verified) as
5939   // the act of enqueueing entries on to the pending list
5940   // will log these updates (and dirty their associated
5941   // cards). We need these updates logged to update any
5942   // RSets.
5943   enqueue_discovered_references(n_workers);
5944 
5945   if (G1DeferredRSUpdate) {
5946     RedirtyLoggedCardTableEntryFastClosure redirty;
5947     dirty_card_queue_set().set_closure(&redirty);
5948     dirty_card_queue_set().apply_closure_to_all_completed_buffers();
5949 
5950     DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
5951     dcq.merge_bufferlists(&dirty_card_queue_set());
5952     assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
5953   }
5954   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
5955 }
5956 
5957 void G1CollectedHeap::free_region_if_empty(HeapRegion* hr,
5958                                      size_t* pre_used,
5959                                      FreeRegionList* free_list,
5960                                      OldRegionSet* old_proxy_set,
5961                                      HumongousRegionSet* humongous_proxy_set,
5962                                      HRRSCleanupTask* hrrs_cleanup_task,
5963                                      bool par) {
5964   if (hr->used() > 0 && hr->max_live_bytes() == 0 && !hr->is_young()) {
5965     if (hr->isHumongous()) {
5966       assert(hr->startsHumongous(), "we should only see starts humongous");
5967       free_humongous_region(hr, pre_used, free_list, humongous_proxy_set, par);
5968     } else {
5969       _old_set.remove_with_proxy(hr, old_proxy_set);
5970       free_region(hr, pre_used, free_list, par);
5971     }
5972   } else {
5973     hr->rem_set()->do_cleanup_work(hrrs_cleanup_task);
5974   }
5975 }
5976 
5977 void G1CollectedHeap::free_region(HeapRegion* hr,
5978                                   size_t* pre_used,
5979                                   FreeRegionList* free_list,
5980                                   bool par) {
5981   assert(!hr->isHumongous(), "this is only for non-humongous regions");
5982   assert(!hr->is_empty(), "the region should not be empty");
5983   assert(free_list != NULL, "pre-condition");
5984 
5985   // Clear the card counts for this region.
5986   // Note: we only need to do this if the region is not young
5987   // (since we don't refine cards in young regions).
5988   if (!hr->is_young()) {
5989     _cg1r->hot_card_cache()->reset_card_counts(hr);
5990   }
5991   *pre_used += hr->used();
5992   hr->hr_clear(par, true /* clear_space */);
5993   free_list->add_as_head(hr);
5994 }
5995 
5996 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
5997                                      size_t* pre_used,
5998                                      FreeRegionList* free_list,
5999                                      HumongousRegionSet* humongous_proxy_set,
6000                                      bool par) {
6001   assert(hr->startsHumongous(), "this is only for starts humongous regions");
6002   assert(free_list != NULL, "pre-condition");
6003   assert(humongous_proxy_set != NULL, "pre-condition");
6004 
6005   size_t hr_used = hr->used();
6006   size_t hr_capacity = hr->capacity();
6007   size_t hr_pre_used = 0;
6008   _humongous_set.remove_with_proxy(hr, humongous_proxy_set);
6009   // We need to read this before we make the region non-humongous,
6010   // otherwise the information will be gone.
6011   uint last_index = hr->last_hc_index();
6012   hr->set_notHumongous();
6013   free_region(hr, &hr_pre_used, free_list, par);
6014 
6015   uint i = hr->hrs_index() + 1;
6016   while (i < last_index) {
6017     HeapRegion* curr_hr = region_at(i);
6018     assert(curr_hr->continuesHumongous(), "invariant");
6019     curr_hr->set_notHumongous();
6020     free_region(curr_hr, &hr_pre_used, free_list, par);
6021     i += 1;
6022   }
6023   assert(hr_pre_used == hr_used,
6024          err_msg("hr_pre_used: "SIZE_FORMAT" and hr_used: "SIZE_FORMAT" "
6025                  "should be the same", hr_pre_used, hr_used));
6026   *pre_used += hr_pre_used;
6027 }
6028 
6029 void G1CollectedHeap::update_sets_after_freeing_regions(size_t pre_used,
6030                                        FreeRegionList* free_list,
6031                                        OldRegionSet* old_proxy_set,
6032                                        HumongousRegionSet* humongous_proxy_set,
6033                                        bool par) {
6034   if (pre_used > 0) {
6035     Mutex* lock = (par) ? ParGCRareEvent_lock : NULL;
6036     MutexLockerEx x(lock, Mutex::_no_safepoint_check_flag);
6037     assert(_summary_bytes_used >= pre_used,
6038            err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" "
6039                    "should be >= pre_used: "SIZE_FORMAT,
6040                    _summary_bytes_used, pre_used));
6041     _summary_bytes_used -= pre_used;
6042   }
6043   if (free_list != NULL && !free_list->is_empty()) {
6044     MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
6045     _free_list.add_as_head(free_list);
6046   }
6047   if (old_proxy_set != NULL && !old_proxy_set->is_empty()) {
6048     MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
6049     _old_set.update_from_proxy(old_proxy_set);
6050   }
6051   if (humongous_proxy_set != NULL && !humongous_proxy_set->is_empty()) {
6052     MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
6053     _humongous_set.update_from_proxy(humongous_proxy_set);
6054   }
6055 }
6056 
6057 class G1ParCleanupCTTask : public AbstractGangTask {
6058   G1SATBCardTableModRefBS* _ct_bs;
6059   G1CollectedHeap* _g1h;
6060   HeapRegion* volatile _su_head;
6061 public:
6062   G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs,
6063                      G1CollectedHeap* g1h) :
6064     AbstractGangTask("G1 Par Cleanup CT Task"),
6065     _ct_bs(ct_bs), _g1h(g1h) { }
6066 
6067   void work(uint worker_id) {
6068     HeapRegion* r;
6069     while (r = _g1h->pop_dirty_cards_region()) {
6070       clear_cards(r);
6071     }
6072   }
6073 
6074   void clear_cards(HeapRegion* r) {
6075     // Cards of the survivors should have already been dirtied.
6076     if (!r->is_survivor()) {
6077       _ct_bs->clear(MemRegion(r->bottom(), r->end()));
6078     }
6079   }
6080 };
6081 
6082 #ifndef PRODUCT
6083 class G1VerifyCardTableCleanup: public HeapRegionClosure {
6084   G1CollectedHeap* _g1h;
6085   G1SATBCardTableModRefBS* _ct_bs;
6086 public:
6087   G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs)
6088     : _g1h(g1h), _ct_bs(ct_bs) { }
6089   virtual bool doHeapRegion(HeapRegion* r) {
6090     if (r->is_survivor()) {
6091       _g1h->verify_dirty_region(r);
6092     } else {
6093       _g1h->verify_not_dirty_region(r);
6094     }
6095     return false;
6096   }
6097 };
6098 
6099 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {
6100   // All of the region should be clean.
6101   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6102   MemRegion mr(hr->bottom(), hr->end());
6103   ct_bs->verify_not_dirty_region(mr);
6104 }
6105 
6106 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {
6107   // We cannot guarantee that [bottom(),end()] is dirty.  Threads
6108   // dirty allocated blocks as they allocate them. The thread that
6109   // retires each region and replaces it with a new one will do a
6110   // maximal allocation to fill in [pre_dummy_top(),end()] but will
6111   // not dirty that area (one less thing to have to do while holding
6112   // a lock). So we can only verify that [bottom(),pre_dummy_top()]
6113   // is dirty.
6114   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6115   MemRegion mr(hr->bottom(), hr->pre_dummy_top());
6116   if (hr->is_young()) {
6117     ct_bs->verify_g1_young_region(mr);
6118   } else {
6119     ct_bs->verify_dirty_region(mr);
6120   }
6121 }
6122 
6123 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {
6124   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6125   for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {
6126     verify_dirty_region(hr);
6127   }
6128 }
6129 
6130 void G1CollectedHeap::verify_dirty_young_regions() {
6131   verify_dirty_young_list(_young_list->first_region());
6132 }
6133 #endif
6134 
6135 void G1CollectedHeap::cleanUpCardTable() {
6136   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6137   double start = os::elapsedTime();
6138 
6139   {
6140     // Iterate over the dirty cards region list.
6141     G1ParCleanupCTTask cleanup_task(ct_bs, this);
6142 
6143     if (G1CollectedHeap::use_parallel_gc_threads()) {
6144       set_par_threads();
6145       workers()->run_task(&cleanup_task);
6146       set_par_threads(0);
6147     } else {
6148       while (_dirty_cards_region_list) {
6149         HeapRegion* r = _dirty_cards_region_list;
6150         cleanup_task.clear_cards(r);
6151         _dirty_cards_region_list = r->get_next_dirty_cards_region();
6152         if (_dirty_cards_region_list == r) {
6153           // The last region.
6154           _dirty_cards_region_list = NULL;
6155         }
6156         r->set_next_dirty_cards_region(NULL);
6157       }
6158     }
6159 #ifndef PRODUCT
6160     if (G1VerifyCTCleanup || VerifyAfterGC) {
6161       G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
6162       heap_region_iterate(&cleanup_verifier);
6163     }
6164 #endif
6165   }
6166 
6167   double elapsed = os::elapsedTime() - start;
6168   g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0);
6169 }
6170 
6171 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) {
6172   size_t pre_used = 0;
6173   FreeRegionList local_free_list("Local List for CSet Freeing");
6174 
6175   double young_time_ms     = 0.0;
6176   double non_young_time_ms = 0.0;
6177 
6178   // Since the collection set is a superset of the the young list,
6179   // all we need to do to clear the young list is clear its
6180   // head and length, and unlink any young regions in the code below
6181   _young_list->clear();
6182 
6183   G1CollectorPolicy* policy = g1_policy();
6184 
6185   double start_sec = os::elapsedTime();
6186   bool non_young = true;
6187 
6188   HeapRegion* cur = cs_head;
6189   int age_bound = -1;
6190   size_t rs_lengths = 0;
6191 
6192   while (cur != NULL) {
6193     assert(!is_on_master_free_list(cur), "sanity");
6194     if (non_young) {
6195       if (cur->is_young()) {
6196         double end_sec = os::elapsedTime();
6197         double elapsed_ms = (end_sec - start_sec) * 1000.0;
6198         non_young_time_ms += elapsed_ms;
6199 
6200         start_sec = os::elapsedTime();
6201         non_young = false;
6202       }
6203     } else {
6204       if (!cur->is_young()) {
6205         double end_sec = os::elapsedTime();
6206         double elapsed_ms = (end_sec - start_sec) * 1000.0;
6207         young_time_ms += elapsed_ms;
6208 
6209         start_sec = os::elapsedTime();
6210         non_young = true;
6211       }
6212     }
6213 
6214     rs_lengths += cur->rem_set()->occupied();
6215 
6216     HeapRegion* next = cur->next_in_collection_set();
6217     assert(cur->in_collection_set(), "bad CS");
6218     cur->set_next_in_collection_set(NULL);
6219     cur->set_in_collection_set(false);
6220 
6221     if (cur->is_young()) {
6222       int index = cur->young_index_in_cset();
6223       assert(index != -1, "invariant");
6224       assert((uint) index < policy->young_cset_region_length(), "invariant");
6225       size_t words_survived = _surviving_young_words[index];
6226       cur->record_surv_words_in_group(words_survived);
6227 
6228       // At this point the we have 'popped' cur from the collection set
6229       // (linked via next_in_collection_set()) but it is still in the
6230       // young list (linked via next_young_region()). Clear the
6231       // _next_young_region field.
6232       cur->set_next_young_region(NULL);
6233     } else {
6234       int index = cur->young_index_in_cset();
6235       assert(index == -1, "invariant");
6236     }
6237 
6238     assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
6239             (!cur->is_young() && cur->young_index_in_cset() == -1),
6240             "invariant" );
6241 
6242     if (!cur->evacuation_failed()) {
6243       MemRegion used_mr = cur->used_region();
6244 
6245       // And the region is empty.
6246       assert(!used_mr.is_empty(), "Should not have empty regions in a CS.");
6247       free_region(cur, &pre_used, &local_free_list, false /* par */);
6248     } else {
6249       cur->uninstall_surv_rate_group();
6250       if (cur->is_young()) {
6251         cur->set_young_index_in_cset(-1);
6252       }
6253       cur->set_not_young();
6254       cur->set_evacuation_failed(false);
6255       // The region is now considered to be old.
6256       _old_set.add(cur);
6257       evacuation_info.increment_collectionset_used_after(cur->used());
6258     }
6259     cur = next;
6260   }
6261 
6262   evacuation_info.set_regions_freed(local_free_list.length());
6263   policy->record_max_rs_lengths(rs_lengths);
6264   policy->cset_regions_freed();
6265 
6266   double end_sec = os::elapsedTime();
6267   double elapsed_ms = (end_sec - start_sec) * 1000.0;
6268 
6269   if (non_young) {
6270     non_young_time_ms += elapsed_ms;
6271   } else {
6272     young_time_ms += elapsed_ms;
6273   }
6274 
6275   update_sets_after_freeing_regions(pre_used, &local_free_list,
6276                                     NULL /* old_proxy_set */,
6277                                     NULL /* humongous_proxy_set */,
6278                                     false /* par */);
6279   policy->phase_times()->record_young_free_cset_time_ms(young_time_ms);
6280   policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms);
6281 }
6282 
6283 // This routine is similar to the above but does not record
6284 // any policy statistics or update free lists; we are abandoning
6285 // the current incremental collection set in preparation of a
6286 // full collection. After the full GC we will start to build up
6287 // the incremental collection set again.
6288 // This is only called when we're doing a full collection
6289 // and is immediately followed by the tearing down of the young list.
6290 
6291 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
6292   HeapRegion* cur = cs_head;
6293 
6294   while (cur != NULL) {
6295     HeapRegion* next = cur->next_in_collection_set();
6296     assert(cur->in_collection_set(), "bad CS");
6297     cur->set_next_in_collection_set(NULL);
6298     cur->set_in_collection_set(false);
6299     cur->set_young_index_in_cset(-1);
6300     cur = next;
6301   }
6302 }
6303 
6304 void G1CollectedHeap::set_free_regions_coming() {
6305   if (G1ConcRegionFreeingVerbose) {
6306     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6307                            "setting free regions coming");
6308   }
6309 
6310   assert(!free_regions_coming(), "pre-condition");
6311   _free_regions_coming = true;
6312 }
6313 
6314 void G1CollectedHeap::reset_free_regions_coming() {
6315   assert(free_regions_coming(), "pre-condition");
6316 
6317   {
6318     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6319     _free_regions_coming = false;
6320     SecondaryFreeList_lock->notify_all();
6321   }
6322 
6323   if (G1ConcRegionFreeingVerbose) {
6324     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6325                            "reset free regions coming");
6326   }
6327 }
6328 
6329 void G1CollectedHeap::wait_while_free_regions_coming() {
6330   // Most of the time we won't have to wait, so let's do a quick test
6331   // first before we take the lock.
6332   if (!free_regions_coming()) {
6333     return;
6334   }
6335 
6336   if (G1ConcRegionFreeingVerbose) {
6337     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6338                            "waiting for free regions");
6339   }
6340 
6341   {
6342     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6343     while (free_regions_coming()) {
6344       SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
6345     }
6346   }
6347 
6348   if (G1ConcRegionFreeingVerbose) {
6349     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6350                            "done waiting for free regions");
6351   }
6352 }
6353 
6354 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
6355   assert(heap_lock_held_for_gc(),
6356               "the heap lock should already be held by or for this thread");
6357   _young_list->push_region(hr);
6358 }
6359 
6360 class NoYoungRegionsClosure: public HeapRegionClosure {
6361 private:
6362   bool _success;
6363 public:
6364   NoYoungRegionsClosure() : _success(true) { }
6365   bool doHeapRegion(HeapRegion* r) {
6366     if (r->is_young()) {
6367       gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
6368                              r->bottom(), r->end());
6369       _success = false;
6370     }
6371     return false;
6372   }
6373   bool success() { return _success; }
6374 };
6375 
6376 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
6377   bool ret = _young_list->check_list_empty(check_sample);
6378 
6379   if (check_heap) {
6380     NoYoungRegionsClosure closure;
6381     heap_region_iterate(&closure);
6382     ret = ret && closure.success();
6383   }
6384 
6385   return ret;
6386 }
6387 
6388 class TearDownRegionSetsClosure : public HeapRegionClosure {
6389 private:
6390   OldRegionSet *_old_set;
6391 
6392 public:
6393   TearDownRegionSetsClosure(OldRegionSet* old_set) : _old_set(old_set) { }
6394 
6395   bool doHeapRegion(HeapRegion* r) {
6396     if (r->is_empty()) {
6397       // We ignore empty regions, we'll empty the free list afterwards
6398     } else if (r->is_young()) {
6399       // We ignore young regions, we'll empty the young list afterwards
6400     } else if (r->isHumongous()) {
6401       // We ignore humongous regions, we're not tearing down the
6402       // humongous region set
6403     } else {
6404       // The rest should be old
6405       _old_set->remove(r);
6406     }
6407     return false;
6408   }
6409 
6410   ~TearDownRegionSetsClosure() {
6411     assert(_old_set->is_empty(), "post-condition");
6412   }
6413 };
6414 
6415 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {
6416   assert_at_safepoint(true /* should_be_vm_thread */);
6417 
6418   if (!free_list_only) {
6419     TearDownRegionSetsClosure cl(&_old_set);
6420     heap_region_iterate(&cl);
6421 
6422     // Need to do this after the heap iteration to be able to
6423     // recognize the young regions and ignore them during the iteration.
6424     _young_list->empty_list();
6425   }
6426   _free_list.remove_all();
6427 }
6428 
6429 class RebuildRegionSetsClosure : public HeapRegionClosure {
6430 private:
6431   bool            _free_list_only;
6432   OldRegionSet*   _old_set;
6433   FreeRegionList* _free_list;
6434   size_t          _total_used;
6435 
6436 public:
6437   RebuildRegionSetsClosure(bool free_list_only,
6438                            OldRegionSet* old_set, FreeRegionList* free_list) :
6439     _free_list_only(free_list_only),
6440     _old_set(old_set), _free_list(free_list), _total_used(0) {
6441     assert(_free_list->is_empty(), "pre-condition");
6442     if (!free_list_only) {
6443       assert(_old_set->is_empty(), "pre-condition");
6444     }
6445   }
6446 
6447   bool doHeapRegion(HeapRegion* r) {
6448     if (r->continuesHumongous()) {
6449       return false;
6450     }
6451 
6452     if (r->is_empty()) {
6453       // Add free regions to the free list
6454       _free_list->add_as_tail(r);
6455     } else if (!_free_list_only) {
6456       assert(!r->is_young(), "we should not come across young regions");
6457 
6458       if (r->isHumongous()) {
6459         // We ignore humongous regions, we left the humongous set unchanged
6460       } else {
6461         // The rest should be old, add them to the old set
6462         _old_set->add(r);
6463       }
6464       _total_used += r->used();
6465     }
6466 
6467     return false;
6468   }
6469 
6470   size_t total_used() {
6471     return _total_used;
6472   }
6473 };
6474 
6475 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
6476   assert_at_safepoint(true /* should_be_vm_thread */);
6477 
6478   RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_free_list);
6479   heap_region_iterate(&cl);
6480 
6481   if (!free_list_only) {
6482     _summary_bytes_used = cl.total_used();
6483   }
6484   assert(_summary_bytes_used == recalculate_used(),
6485          err_msg("inconsistent _summary_bytes_used, "
6486                  "value: "SIZE_FORMAT" recalculated: "SIZE_FORMAT,
6487                  _summary_bytes_used, recalculate_used()));
6488 }
6489 
6490 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
6491   _refine_cte_cl->set_concurrent(concurrent);
6492 }
6493 
6494 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
6495   HeapRegion* hr = heap_region_containing(p);
6496   if (hr == NULL) {
6497     return is_in_permanent(p);
6498   } else {
6499     return hr->is_in(p);
6500   }
6501 }
6502 
6503 // Methods for the mutator alloc region
6504 
6505 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
6506                                                       bool force) {
6507   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6508   assert(!force || g1_policy()->can_expand_young_list(),
6509          "if force is true we should be able to expand the young list");
6510   bool young_list_full = g1_policy()->is_young_list_full();
6511   if (force || !young_list_full) {
6512     HeapRegion* new_alloc_region = new_region(word_size,
6513                                               false /* do_expand */);
6514     if (new_alloc_region != NULL) {
6515       set_region_short_lived_locked(new_alloc_region);
6516       _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
6517       return new_alloc_region;
6518     }
6519   }
6520   return NULL;
6521 }
6522 
6523 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
6524                                                   size_t allocated_bytes) {
6525   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6526   assert(alloc_region->is_young(), "all mutator alloc regions should be young");
6527 
6528   g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
6529   _summary_bytes_used += allocated_bytes;
6530   _hr_printer.retire(alloc_region);
6531   // We update the eden sizes here, when the region is retired,
6532   // instead of when it's allocated, since this is the point that its
6533   // used space has been recored in _summary_bytes_used.
6534   g1mm()->update_eden_size();
6535 }
6536 
6537 HeapRegion* MutatorAllocRegion::allocate_new_region(size_t word_size,
6538                                                     bool force) {
6539   return _g1h->new_mutator_alloc_region(word_size, force);
6540 }
6541 
6542 void G1CollectedHeap::set_par_threads() {
6543   // Don't change the number of workers.  Use the value previously set
6544   // in the workgroup.
6545   assert(G1CollectedHeap::use_parallel_gc_threads(), "shouldn't be here otherwise");
6546   uint n_workers = workers()->active_workers();
6547   assert(UseDynamicNumberOfGCThreads ||
6548            n_workers == workers()->total_workers(),
6549       "Otherwise should be using the total number of workers");
6550   if (n_workers == 0) {
6551     assert(false, "Should have been set in prior evacuation pause.");
6552     n_workers = ParallelGCThreads;
6553     workers()->set_active_workers(n_workers);
6554   }
6555   set_par_threads(n_workers);
6556 }
6557 
6558 void MutatorAllocRegion::retire_region(HeapRegion* alloc_region,
6559                                        size_t allocated_bytes) {
6560   _g1h->retire_mutator_alloc_region(alloc_region, allocated_bytes);
6561 }
6562 
6563 // Methods for the GC alloc regions
6564 
6565 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,
6566                                                  uint count,
6567                                                  GCAllocPurpose ap) {
6568   assert(FreeList_lock->owned_by_self(), "pre-condition");
6569 
6570   if (count < g1_policy()->max_regions(ap)) {
6571     HeapRegion* new_alloc_region = new_region(word_size,
6572                                               true /* do_expand */);
6573     if (new_alloc_region != NULL) {
6574       // We really only need to do this for old regions given that we
6575       // should never scan survivors. But it doesn't hurt to do it
6576       // for survivors too.
6577       new_alloc_region->set_saved_mark();
6578       if (ap == GCAllocForSurvived) {
6579         new_alloc_region->set_survivor();
6580         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
6581       } else {
6582         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
6583       }
6584       bool during_im = g1_policy()->during_initial_mark_pause();
6585       new_alloc_region->note_start_of_copying(during_im);
6586       return new_alloc_region;
6587     } else {
6588       g1_policy()->note_alloc_region_limit_reached(ap);
6589     }
6590   }
6591   return NULL;
6592 }
6593 
6594 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
6595                                              size_t allocated_bytes,
6596                                              GCAllocPurpose ap) {
6597   bool during_im = g1_policy()->during_initial_mark_pause();
6598   alloc_region->note_end_of_copying(during_im);
6599   g1_policy()->record_bytes_copied_during_gc(allocated_bytes);
6600   if (ap == GCAllocForSurvived) {
6601     young_list()->add_survivor_region(alloc_region);
6602   } else {
6603     _old_set.add(alloc_region);
6604   }
6605   _hr_printer.retire(alloc_region);
6606 }
6607 
6608 HeapRegion* SurvivorGCAllocRegion::allocate_new_region(size_t word_size,
6609                                                        bool force) {
6610   assert(!force, "not supported for GC alloc regions");
6611   return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForSurvived);
6612 }
6613 
6614 void SurvivorGCAllocRegion::retire_region(HeapRegion* alloc_region,
6615                                           size_t allocated_bytes) {
6616   _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6617                                GCAllocForSurvived);
6618 }
6619 
6620 HeapRegion* OldGCAllocRegion::allocate_new_region(size_t word_size,
6621                                                   bool force) {
6622   assert(!force, "not supported for GC alloc regions");
6623   return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForTenured);
6624 }
6625 
6626 void OldGCAllocRegion::retire_region(HeapRegion* alloc_region,
6627                                      size_t allocated_bytes) {
6628   _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6629                                GCAllocForTenured);
6630 }
6631 // Heap region set verification
6632 
6633 class VerifyRegionListsClosure : public HeapRegionClosure {
6634 private:
6635   FreeRegionList*     _free_list;
6636   OldRegionSet*       _old_set;
6637   HumongousRegionSet* _humongous_set;
6638   uint                _region_count;
6639 
6640 public:
6641   VerifyRegionListsClosure(OldRegionSet* old_set,
6642                            HumongousRegionSet* humongous_set,
6643                            FreeRegionList* free_list) :
6644     _old_set(old_set), _humongous_set(humongous_set),
6645     _free_list(free_list), _region_count(0) { }
6646 
6647   uint region_count() { return _region_count; }
6648 
6649   bool doHeapRegion(HeapRegion* hr) {
6650     _region_count += 1;
6651 
6652     if (hr->continuesHumongous()) {
6653       return false;
6654     }
6655 
6656     if (hr->is_young()) {
6657       // TODO
6658     } else if (hr->startsHumongous()) {
6659       _humongous_set->verify_next_region(hr);
6660     } else if (hr->is_empty()) {
6661       _free_list->verify_next_region(hr);
6662     } else {
6663       _old_set->verify_next_region(hr);
6664     }
6665     return false;
6666   }
6667 };
6668 
6669 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
6670                                              HeapWord* bottom) {
6671   HeapWord* end = bottom + HeapRegion::GrainWords;
6672   MemRegion mr(bottom, end);
6673   assert(_g1_reserved.contains(mr), "invariant");
6674   // This might return NULL if the allocation fails
6675   return new HeapRegion(hrs_index, _bot_shared, mr, true /* is_zeroed */);
6676 }
6677 
6678 void G1CollectedHeap::verify_region_sets() {
6679   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6680 
6681   // First, check the explicit lists.
6682   _free_list.verify();
6683   {
6684     // Given that a concurrent operation might be adding regions to
6685     // the secondary free list we have to take the lock before
6686     // verifying it.
6687     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6688     _secondary_free_list.verify();
6689   }
6690   _old_set.verify();
6691   _humongous_set.verify();
6692 
6693   // If a concurrent region freeing operation is in progress it will
6694   // be difficult to correctly attributed any free regions we come
6695   // across to the correct free list given that they might belong to
6696   // one of several (free_list, secondary_free_list, any local lists,
6697   // etc.). So, if that's the case we will skip the rest of the
6698   // verification operation. Alternatively, waiting for the concurrent
6699   // operation to complete will have a non-trivial effect on the GC's
6700   // operation (no concurrent operation will last longer than the
6701   // interval between two calls to verification) and it might hide
6702   // any issues that we would like to catch during testing.
6703   if (free_regions_coming()) {
6704     return;
6705   }
6706 
6707   // Make sure we append the secondary_free_list on the free_list so
6708   // that all free regions we will come across can be safely
6709   // attributed to the free_list.
6710   append_secondary_free_list_if_not_empty_with_lock();
6711 
6712   // Finally, make sure that the region accounting in the lists is
6713   // consistent with what we see in the heap.
6714   _old_set.verify_start();
6715   _humongous_set.verify_start();
6716   _free_list.verify_start();
6717 
6718   VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_free_list);
6719   heap_region_iterate(&cl);
6720 
6721   _old_set.verify_end();
6722   _humongous_set.verify_end();
6723   _free_list.verify_end();
6724 }
6725 
6726 // Optimized nmethod scanning
6727 
6728 class RegisterNMethodOopClosure: public OopClosure {
6729   G1CollectedHeap* _g1h;
6730   nmethod* _nm;
6731 
6732   template <class T> void do_oop_work(T* p) {
6733     T heap_oop = oopDesc::load_heap_oop(p);
6734     if (!oopDesc::is_null(heap_oop)) {
6735       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6736       HeapRegion* hr = _g1h->heap_region_containing(obj);
6737       if (hr == NULL) {
6738         // reference into perm gen - ignore.
6739         assert(_g1h->is_in_permanent(obj), "must be a reference into perm gen");
6740         return;
6741       }
6742       assert(!hr->continuesHumongous(),
6743              err_msg("trying to add code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
6744                      " starting at "HR_FORMAT,
6745                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
6746 
6747       // HeapRegion::add_strong_code_root() avoids adding duplicate
6748       // entries but having duplicates is  OK since we "mark" nmethods
6749       // as visited when we scan the strong code root lists during the GC.
6750       hr->add_strong_code_root(_nm);
6751       assert(hr->rem_set()->strong_code_roots_list_contains(_nm),
6752              err_msg("failed to add code root "PTR_FORMAT" to remembered set of region "HR_FORMAT,
6753                      _nm, HR_FORMAT_PARAMS(hr)));
6754     }
6755   }
6756 
6757 public:
6758   RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
6759     _g1h(g1h), _nm(nm) {}
6760 
6761   void do_oop(oop* p)       { do_oop_work(p); }
6762   void do_oop(narrowOop* p) { do_oop_work(p); }
6763 };
6764 
6765 class UnregisterNMethodOopClosure: public OopClosure {
6766   G1CollectedHeap* _g1h;
6767   nmethod* _nm;
6768 
6769   template <class T> void do_oop_work(T* p) {
6770     T heap_oop = oopDesc::load_heap_oop(p);
6771     if (!oopDesc::is_null(heap_oop)) {
6772       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6773       HeapRegion* hr = _g1h->heap_region_containing(obj);
6774       if (hr == NULL) {
6775         // reference into perm gen - ignore.
6776         assert(_g1h->is_in_permanent(obj), "must be a reference into perm gen");
6777         return;
6778       }
6779       assert(!hr->continuesHumongous(),
6780              err_msg("trying to remove code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
6781                      " starting at "HR_FORMAT,
6782                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
6783 
6784       hr->remove_strong_code_root(_nm);
6785       assert(!hr->rem_set()->strong_code_roots_list_contains(_nm),
6786              err_msg("failed to remove code root "PTR_FORMAT" of region "HR_FORMAT,
6787                      _nm, HR_FORMAT_PARAMS(hr)));    }
6788   }
6789 
6790 public:
6791   UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
6792     _g1h(g1h), _nm(nm) {}
6793 
6794   void do_oop(oop* p)       { do_oop_work(p); }
6795   void do_oop(narrowOop* p) { do_oop_work(p); }
6796 };
6797 
6798 void G1CollectedHeap::register_nmethod(nmethod* nm) {
6799   CollectedHeap::register_nmethod(nm);
6800 
6801   guarantee(nm != NULL, "sanity");
6802   RegisterNMethodOopClosure reg_cl(this, nm);
6803   nm->oops_do(&reg_cl);
6804 }
6805 
6806 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
6807   CollectedHeap::unregister_nmethod(nm);
6808 
6809   guarantee(nm != NULL, "sanity");
6810   UnregisterNMethodOopClosure reg_cl(this, nm);
6811   nm->oops_do(&reg_cl, false, true);
6812 }
6813 
6814 class MigrateCodeRootsHeapRegionClosure: public HeapRegionClosure {
6815 public:
6816   bool doHeapRegion(HeapRegion *hr) {
6817     assert(!hr->isHumongous(),
6818            err_msg("humongous region "HR_FORMAT" should not have been added to collection set",
6819                    HR_FORMAT_PARAMS(hr)));
6820     hr->migrate_strong_code_roots();
6821     return false;
6822   }
6823 };
6824 
6825 void G1CollectedHeap::migrate_strong_code_roots() {
6826   MigrateCodeRootsHeapRegionClosure cl;
6827   double migrate_start = os::elapsedTime();
6828   collection_set_iterate(&cl);
6829   double migration_time_ms = (os::elapsedTime() - migrate_start) * 1000.0;
6830   g1_policy()->phase_times()->record_strong_code_root_migration_time(migration_time_ms);
6831 }
6832 
6833 // Mark all the code roots that point into regions *not* in the
6834 // collection set.
6835 //
6836 // Note we do not want to use a "marking" CodeBlobToOopClosure while
6837 // walking the the code roots lists of regions not in the collection
6838 // set. Suppose we have an nmethod (M) that points to objects in two
6839 // separate regions - one in the collection set (R1) and one not (R2).
6840 // Using a "marking" CodeBlobToOopClosure here would result in "marking"
6841 // nmethod M when walking the code roots for R1. When we come to scan
6842 // the code roots for R2, we would see that M is already marked and it
6843 // would be skipped and the objects in R2 that are referenced from M
6844 // would not be evacuated.
6845 
6846 class MarkStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
6847 
6848   class MarkStrongCodeRootOopClosure: public OopClosure {
6849     ConcurrentMark* _cm;
6850     HeapRegion* _hr;
6851     uint _worker_id;
6852 
6853     template <class T> void do_oop_work(T* p) {
6854       T heap_oop = oopDesc::load_heap_oop(p);
6855       if (!oopDesc::is_null(heap_oop)) {
6856         oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6857         // Only mark objects in the region (which is assumed
6858         // to be not in the collection set).
6859         if (_hr->is_in(obj)) {
6860           _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
6861         }
6862       }
6863     }
6864 
6865   public:
6866     MarkStrongCodeRootOopClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id) :
6867       _cm(cm), _hr(hr), _worker_id(worker_id) {
6868       assert(!_hr->in_collection_set(), "sanity");
6869     }
6870 
6871     void do_oop(narrowOop* p) { do_oop_work(p); }
6872     void do_oop(oop* p)       { do_oop_work(p); }
6873   };
6874 
6875   MarkStrongCodeRootOopClosure _oop_cl;
6876 
6877 public:
6878   MarkStrongCodeRootCodeBlobClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id):
6879     _oop_cl(cm, hr, worker_id) {}
6880 
6881   void do_code_blob(CodeBlob* cb) {
6882     nmethod* nm = (cb == NULL) ? NULL : cb->as_nmethod_or_null();
6883     if (nm != NULL) {
6884       nm->oops_do(&_oop_cl);
6885     }
6886   }
6887 };
6888 
6889 class MarkStrongCodeRootsHRClosure: public HeapRegionClosure {
6890   G1CollectedHeap* _g1h;
6891   uint _worker_id;
6892 
6893 public:
6894   MarkStrongCodeRootsHRClosure(G1CollectedHeap* g1h, uint worker_id) :
6895     _g1h(g1h), _worker_id(worker_id) {}
6896 
6897   bool doHeapRegion(HeapRegion *hr) {
6898     HeapRegionRemSet* hrrs = hr->rem_set();
6899     if (hr->continuesHumongous()) {
6900       // Code roots should never be attached to a continuation of a humongous region
6901       assert(hrrs->strong_code_roots_list_length() == 0,
6902              err_msg("code roots should never be attached to continuations of humongous region "HR_FORMAT
6903                      " starting at "HR_FORMAT", but has "INT32_FORMAT,
6904                      HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()),
6905                      hrrs->strong_code_roots_list_length()));
6906       return false;
6907     }
6908 
6909     if (hr->in_collection_set()) {
6910       // Don't mark code roots into regions in the collection set here.
6911       // They will be marked when we scan them.
6912       return false;
6913     }
6914 
6915     MarkStrongCodeRootCodeBlobClosure cb_cl(_g1h->concurrent_mark(), hr, _worker_id);
6916     hr->strong_code_roots_do(&cb_cl);
6917     return false;
6918   }
6919 };
6920 
6921 void G1CollectedHeap::mark_strong_code_roots(uint worker_id) {
6922   MarkStrongCodeRootsHRClosure cl(this, worker_id);
6923   if (G1CollectedHeap::use_parallel_gc_threads()) {
6924     heap_region_par_iterate_chunked(&cl,
6925                                     worker_id,
6926                                     workers()->active_workers(),
6927                                     HeapRegion::ParMarkRootClaimValue);
6928   } else {
6929     heap_region_iterate(&cl);
6930   }
6931 }
6932 
6933 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
6934   G1CollectedHeap* _g1h;
6935 
6936 public:
6937   RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
6938     _g1h(g1h) {}
6939 
6940   void do_code_blob(CodeBlob* cb) {
6941     nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
6942     if (nm == NULL) {
6943       return;
6944     }
6945 
6946     if (ScavengeRootsInCode && nm->detect_scavenge_root_oops()) {
6947       _g1h->register_nmethod(nm);
6948     }
6949   }
6950 };
6951 
6952 void G1CollectedHeap::rebuild_strong_code_roots() {
6953   RebuildStrongCodeRootClosure blob_cl(this);
6954   CodeCache::blobs_do(&blob_cl);
6955 }