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