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