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