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