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