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