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