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