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