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 void
2633 G1CollectedHeap::heap_region_iterate_range(HeapRegionClosure* cl, uint start, uint end) const {
2634   _hrs.iterate_range(cl, start, end);
2635 }
2636 
2637 class ResetClaimValuesClosure: public HeapRegionClosure {
2638 public:
2639   bool doHeapRegion(HeapRegion* r) {
2640     r->set_claim_value(HeapRegion::InitialClaimValue);
2641     return false;
2642   }
2643 };
2644 
2645 void G1CollectedHeap::reset_heap_region_claim_values() {
2646   ResetClaimValuesClosure blk;
2647   heap_region_iterate(&blk);
2648 }
2649 
2650 void G1CollectedHeap::reset_cset_heap_region_claim_values() {
2651   ResetClaimValuesClosure blk;
2652   collection_set_iterate(&blk);
2653 }
2654 
2655 #ifdef ASSERT
2656 // This checks whether all regions in the heap have the correct claim
2657 // value. I also piggy-backed on this a check to ensure that the
2658 // humongous_start_region() information on "continues humongous"
2659 // regions is correct.
2660 
2661 class CheckClaimValuesClosure : public HeapRegionClosure {
2662 private:
2663   jint _claim_value;
2664   uint _failures;
2665   HeapRegion* _sh_region;
2666 
2667 public:
2668   CheckClaimValuesClosure(jint claim_value) :
2669     _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
2670   bool doHeapRegion(HeapRegion* r) {
2671     if (r->claim_value() != _claim_value) {
2672       gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2673                              "claim value = %d, should be %d",
2674                              HR_FORMAT_PARAMS(r),
2675                              r->claim_value(), _claim_value);
2676       ++_failures;
2677     }
2678     if (!r->isHumongous()) {
2679       _sh_region = NULL;
2680     } else if (r->startsHumongous()) {
2681       _sh_region = r;
2682     } else if (r->continuesHumongous()) {
2683       if (r->humongous_start_region() != _sh_region) {
2684         gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2685                                "HS = "PTR_FORMAT", should be "PTR_FORMAT,
2686                                HR_FORMAT_PARAMS(r),
2687                                r->humongous_start_region(),
2688                                _sh_region);
2689         ++_failures;
2690       }
2691     }
2692     return false;
2693   }
2694   uint failures() { return _failures; }
2695 };
2696 
2697 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
2698   CheckClaimValuesClosure cl(claim_value);
2699   heap_region_iterate(&cl);
2700   return cl.failures() == 0;
2701 }
2702 
2703 class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {
2704 private:
2705   jint _claim_value;
2706   uint _failures;
2707 
2708 public:
2709   CheckClaimValuesInCSetHRClosure(jint claim_value) :
2710     _claim_value(claim_value), _failures(0) { }
2711 
2712   uint failures() { return _failures; }
2713 
2714   bool doHeapRegion(HeapRegion* hr) {
2715     assert(hr->in_collection_set(), "how?");
2716     assert(!hr->isHumongous(), "H-region in CSet");
2717     if (hr->claim_value() != _claim_value) {
2718       gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "
2719                              "claim value = %d, should be %d",
2720                              HR_FORMAT_PARAMS(hr),
2721                              hr->claim_value(), _claim_value);
2722       _failures += 1;
2723     }
2724     return false;
2725   }
2726 };
2727 
2728 bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {
2729   CheckClaimValuesInCSetHRClosure cl(claim_value);
2730   collection_set_iterate(&cl);
2731   return cl.failures() == 0;
2732 }
2733 #endif // ASSERT
2734 
2735 // Clear the cached CSet starting regions and (more importantly)
2736 // the time stamps. Called when we reset the GC time stamp.
2737 void G1CollectedHeap::clear_cset_start_regions() {
2738   assert(_worker_cset_start_region != NULL, "sanity");
2739   assert(_worker_cset_start_region_time_stamp != NULL, "sanity");
2740 
2741   int n_queues = MAX2((int)ParallelGCThreads, 1);
2742   for (int i = 0; i < n_queues; i++) {
2743     _worker_cset_start_region[i] = NULL;
2744     _worker_cset_start_region_time_stamp[i] = 0;
2745   }
2746 }
2747 
2748 // Given the id of a worker, obtain or calculate a suitable
2749 // starting region for iterating over the current collection set.
2750 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(uint worker_i) {
2751   assert(get_gc_time_stamp() > 0, "should have been updated by now");
2752 
2753   HeapRegion* result = NULL;
2754   unsigned gc_time_stamp = get_gc_time_stamp();
2755 
2756   if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) {
2757     // Cached starting region for current worker was set
2758     // during the current pause - so it's valid.
2759     // Note: the cached starting heap region may be NULL
2760     // (when the collection set is empty).
2761     result = _worker_cset_start_region[worker_i];
2762     assert(result == NULL || result->in_collection_set(), "sanity");
2763     return result;
2764   }
2765 
2766   // The cached entry was not valid so let's calculate
2767   // a suitable starting heap region for this worker.
2768 
2769   // We want the parallel threads to start their collection
2770   // set iteration at different collection set regions to
2771   // avoid contention.
2772   // If we have:
2773   //          n collection set regions
2774   //          p threads
2775   // Then thread t will start at region floor ((t * n) / p)
2776 
2777   result = g1_policy()->collection_set();
2778   if (G1CollectedHeap::use_parallel_gc_threads()) {
2779     uint cs_size = g1_policy()->cset_region_length();
2780     uint active_workers = workers()->active_workers();
2781     assert(UseDynamicNumberOfGCThreads ||
2782              active_workers == workers()->total_workers(),
2783              "Unless dynamic should use total workers");
2784 
2785     uint end_ind   = (cs_size * worker_i) / active_workers;
2786     uint start_ind = 0;
2787 
2788     if (worker_i > 0 &&
2789         _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) {
2790       // Previous workers starting region is valid
2791       // so let's iterate from there
2792       start_ind = (cs_size * (worker_i - 1)) / active_workers;
2793       result = _worker_cset_start_region[worker_i - 1];
2794     }
2795 
2796     for (uint i = start_ind; i < end_ind; i++) {
2797       result = result->next_in_collection_set();
2798     }
2799   }
2800 
2801   // Note: the calculated starting heap region may be NULL
2802   // (when the collection set is empty).
2803   assert(result == NULL || result->in_collection_set(), "sanity");
2804   assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp,
2805          "should be updated only once per pause");
2806   _worker_cset_start_region[worker_i] = result;
2807   OrderAccess::storestore();
2808   _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp;
2809   return result;
2810 }
2811 
2812 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
2813   HeapRegion* r = g1_policy()->collection_set();
2814   while (r != NULL) {
2815     HeapRegion* next = r->next_in_collection_set();
2816     if (cl->doHeapRegion(r)) {
2817       cl->incomplete();
2818       return;
2819     }
2820     r = next;
2821   }
2822 }
2823 
2824 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
2825                                                   HeapRegionClosure *cl) {
2826   if (r == NULL) {
2827     // The CSet is empty so there's nothing to do.
2828     return;
2829   }
2830 
2831   assert(r->in_collection_set(),
2832          "Start region must be a member of the collection set.");
2833   HeapRegion* cur = r;
2834   while (cur != NULL) {
2835     HeapRegion* next = cur->next_in_collection_set();
2836     if (cl->doHeapRegion(cur) && false) {
2837       cl->incomplete();
2838       return;
2839     }
2840     cur = next;
2841   }
2842   cur = g1_policy()->collection_set();
2843   while (cur != r) {
2844     HeapRegion* next = cur->next_in_collection_set();
2845     if (cl->doHeapRegion(cur) && false) {
2846       cl->incomplete();
2847       return;
2848     }
2849     cur = next;
2850   }
2851 }
2852 
2853 HeapRegion* G1CollectedHeap::next_compaction_region(const HeapRegion* from) const {
2854   HeapRegion* result = _hrs.next_region_in_heap(from);
2855   while (result != NULL && result->isHumongous()) {
2856     result = _hrs.next_region_in_heap(result);
2857   }
2858   return result;
2859 }
2860 
2861 Space* G1CollectedHeap::space_containing(const void* addr) const {
2862   return heap_region_containing(addr);
2863 }
2864 
2865 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2866   Space* sp = space_containing(addr);
2867   return sp->block_start(addr);
2868 }
2869 
2870 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
2871   Space* sp = space_containing(addr);
2872   return sp->block_size(addr);
2873 }
2874 
2875 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2876   Space* sp = space_containing(addr);
2877   return sp->block_is_obj(addr);
2878 }
2879 
2880 bool G1CollectedHeap::supports_tlab_allocation() const {
2881   return true;
2882 }
2883 
2884 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2885   return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes;
2886 }
2887 
2888 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
2889   return young_list()->eden_used_bytes();
2890 }
2891 
2892 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2893 // must be smaller than the humongous object limit.
2894 size_t G1CollectedHeap::max_tlab_size() const {
2895   return align_size_down(_humongous_object_threshold_in_words - 1, MinObjAlignment);
2896 }
2897 
2898 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2899   // Return the remaining space in the cur alloc region, but not less than
2900   // the min TLAB size.
2901 
2902   // Also, this value can be at most the humongous object threshold,
2903   // since we can't allow tlabs to grow big enough to accommodate
2904   // humongous objects.
2905 
2906   HeapRegion* hr = _mutator_alloc_region.get();
2907   size_t max_tlab = max_tlab_size() * wordSize;
2908   if (hr == NULL) {
2909     return max_tlab;
2910   } else {
2911     return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab);
2912   }
2913 }
2914 
2915 size_t G1CollectedHeap::max_capacity() const {
2916   return _hrs.reserved().byte_size();
2917 }
2918 
2919 jlong G1CollectedHeap::millis_since_last_gc() {
2920   // assert(false, "NYI");
2921   return 0;
2922 }
2923 
2924 void G1CollectedHeap::prepare_for_verify() {
2925   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2926     ensure_parsability(false);
2927   }
2928   g1_rem_set()->prepare_for_verify();
2929 }
2930 
2931 bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr,
2932                                               VerifyOption vo) {
2933   switch (vo) {
2934   case VerifyOption_G1UsePrevMarking:
2935     return hr->obj_allocated_since_prev_marking(obj);
2936   case VerifyOption_G1UseNextMarking:
2937     return hr->obj_allocated_since_next_marking(obj);
2938   case VerifyOption_G1UseMarkWord:
2939     return false;
2940   default:
2941     ShouldNotReachHere();
2942   }
2943   return false; // keep some compilers happy
2944 }
2945 
2946 HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) {
2947   switch (vo) {
2948   case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start();
2949   case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start();
2950   case VerifyOption_G1UseMarkWord:    return NULL;
2951   default:                            ShouldNotReachHere();
2952   }
2953   return NULL; // keep some compilers happy
2954 }
2955 
2956 bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) {
2957   switch (vo) {
2958   case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj);
2959   case VerifyOption_G1UseNextMarking: return isMarkedNext(obj);
2960   case VerifyOption_G1UseMarkWord:    return obj->is_gc_marked();
2961   default:                            ShouldNotReachHere();
2962   }
2963   return false; // keep some compilers happy
2964 }
2965 
2966 const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) {
2967   switch (vo) {
2968   case VerifyOption_G1UsePrevMarking: return "PTAMS";
2969   case VerifyOption_G1UseNextMarking: return "NTAMS";
2970   case VerifyOption_G1UseMarkWord:    return "NONE";
2971   default:                            ShouldNotReachHere();
2972   }
2973   return NULL; // keep some compilers happy
2974 }
2975 
2976 class VerifyRootsClosure: public OopClosure {
2977 private:
2978   G1CollectedHeap* _g1h;
2979   VerifyOption     _vo;
2980   bool             _failures;
2981 public:
2982   // _vo == UsePrevMarking -> use "prev" marking information,
2983   // _vo == UseNextMarking -> use "next" marking information,
2984   // _vo == UseMarkWord    -> use mark word from object header.
2985   VerifyRootsClosure(VerifyOption vo) :
2986     _g1h(G1CollectedHeap::heap()),
2987     _vo(vo),
2988     _failures(false) { }
2989 
2990   bool failures() { return _failures; }
2991 
2992   template <class T> void do_oop_nv(T* p) {
2993     T heap_oop = oopDesc::load_heap_oop(p);
2994     if (!oopDesc::is_null(heap_oop)) {
2995       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
2996       if (_g1h->is_obj_dead_cond(obj, _vo)) {
2997         gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
2998                               "points to dead obj "PTR_FORMAT, p, (void*) obj);
2999         if (_vo == VerifyOption_G1UseMarkWord) {
3000           gclog_or_tty->print_cr("  Mark word: "PTR_FORMAT, (void*)(obj->mark()));
3001         }
3002         obj->print_on(gclog_or_tty);
3003         _failures = true;
3004       }
3005     }
3006   }
3007 
3008   void do_oop(oop* p)       { do_oop_nv(p); }
3009   void do_oop(narrowOop* p) { do_oop_nv(p); }
3010 };
3011 
3012 class G1VerifyCodeRootOopClosure: public OopClosure {
3013   G1CollectedHeap* _g1h;
3014   OopClosure* _root_cl;
3015   nmethod* _nm;
3016   VerifyOption _vo;
3017   bool _failures;
3018 
3019   template <class T> void do_oop_work(T* p) {
3020     // First verify that this root is live
3021     _root_cl->do_oop(p);
3022 
3023     if (!G1VerifyHeapRegionCodeRoots) {
3024       // We're not verifying the code roots attached to heap region.
3025       return;
3026     }
3027 
3028     // Don't check the code roots during marking verification in a full GC
3029     if (_vo == VerifyOption_G1UseMarkWord) {
3030       return;
3031     }
3032 
3033     // Now verify that the current nmethod (which contains p) is
3034     // in the code root list of the heap region containing the
3035     // object referenced by p.
3036 
3037     T heap_oop = oopDesc::load_heap_oop(p);
3038     if (!oopDesc::is_null(heap_oop)) {
3039       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3040 
3041       // Now fetch the region containing the object
3042       HeapRegion* hr = _g1h->heap_region_containing(obj);
3043       HeapRegionRemSet* hrrs = hr->rem_set();
3044       // Verify that the strong code root list for this region
3045       // contains the nmethod
3046       if (!hrrs->strong_code_roots_list_contains(_nm)) {
3047         gclog_or_tty->print_cr("Code root location "PTR_FORMAT" "
3048                               "from nmethod "PTR_FORMAT" not in strong "
3049                               "code roots for region ["PTR_FORMAT","PTR_FORMAT")",
3050                               p, _nm, hr->bottom(), hr->end());
3051         _failures = true;
3052       }
3053     }
3054   }
3055 
3056 public:
3057   G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
3058     _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}
3059 
3060   void do_oop(oop* p) { do_oop_work(p); }
3061   void do_oop(narrowOop* p) { do_oop_work(p); }
3062 
3063   void set_nmethod(nmethod* nm) { _nm = nm; }
3064   bool failures() { return _failures; }
3065 };
3066 
3067 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
3068   G1VerifyCodeRootOopClosure* _oop_cl;
3069 
3070 public:
3071   G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
3072     _oop_cl(oop_cl) {}
3073 
3074   void do_code_blob(CodeBlob* cb) {
3075     nmethod* nm = cb->as_nmethod_or_null();
3076     if (nm != NULL) {
3077       _oop_cl->set_nmethod(nm);
3078       nm->oops_do(_oop_cl);
3079     }
3080   }
3081 };
3082 
3083 class YoungRefCounterClosure : public OopClosure {
3084   G1CollectedHeap* _g1h;
3085   int              _count;
3086  public:
3087   YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
3088   void do_oop(oop* p)       { if (_g1h->is_in_young(*p)) { _count++; } }
3089   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3090 
3091   int count() { return _count; }
3092   void reset_count() { _count = 0; };
3093 };
3094 
3095 class VerifyKlassClosure: public KlassClosure {
3096   YoungRefCounterClosure _young_ref_counter_closure;
3097   OopClosure *_oop_closure;
3098  public:
3099   VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
3100   void do_klass(Klass* k) {
3101     k->oops_do(_oop_closure);
3102 
3103     _young_ref_counter_closure.reset_count();
3104     k->oops_do(&_young_ref_counter_closure);
3105     if (_young_ref_counter_closure.count() > 0) {
3106       guarantee(k->has_modified_oops(), err_msg("Klass " PTR_FORMAT ", has young refs but is not dirty.", k));
3107     }
3108   }
3109 };
3110 
3111 class VerifyLivenessOopClosure: public OopClosure {
3112   G1CollectedHeap* _g1h;
3113   VerifyOption _vo;
3114 public:
3115   VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
3116     _g1h(g1h), _vo(vo)
3117   { }
3118   void do_oop(narrowOop *p) { do_oop_work(p); }
3119   void do_oop(      oop *p) { do_oop_work(p); }
3120 
3121   template <class T> void do_oop_work(T *p) {
3122     oop obj = oopDesc::load_decode_heap_oop(p);
3123     guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
3124               "Dead object referenced by a not dead object");
3125   }
3126 };
3127 
3128 class VerifyObjsInRegionClosure: public ObjectClosure {
3129 private:
3130   G1CollectedHeap* _g1h;
3131   size_t _live_bytes;
3132   HeapRegion *_hr;
3133   VerifyOption _vo;
3134 public:
3135   // _vo == UsePrevMarking -> use "prev" marking information,
3136   // _vo == UseNextMarking -> use "next" marking information,
3137   // _vo == UseMarkWord    -> use mark word from object header.
3138   VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
3139     : _live_bytes(0), _hr(hr), _vo(vo) {
3140     _g1h = G1CollectedHeap::heap();
3141   }
3142   void do_object(oop o) {
3143     VerifyLivenessOopClosure isLive(_g1h, _vo);
3144     assert(o != NULL, "Huh?");
3145     if (!_g1h->is_obj_dead_cond(o, _vo)) {
3146       // If the object is alive according to the mark word,
3147       // then verify that the marking information agrees.
3148       // Note we can't verify the contra-positive of the
3149       // above: if the object is dead (according to the mark
3150       // word), it may not be marked, or may have been marked
3151       // but has since became dead, or may have been allocated
3152       // since the last marking.
3153       if (_vo == VerifyOption_G1UseMarkWord) {
3154         guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
3155       }
3156 
3157       o->oop_iterate_no_header(&isLive);
3158       if (!_hr->obj_allocated_since_prev_marking(o)) {
3159         size_t obj_size = o->size();    // Make sure we don't overflow
3160         _live_bytes += (obj_size * HeapWordSize);
3161       }
3162     }
3163   }
3164   size_t live_bytes() { return _live_bytes; }
3165 };
3166 
3167 class PrintObjsInRegionClosure : public ObjectClosure {
3168   HeapRegion *_hr;
3169   G1CollectedHeap *_g1;
3170 public:
3171   PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
3172     _g1 = G1CollectedHeap::heap();
3173   };
3174 
3175   void do_object(oop o) {
3176     if (o != NULL) {
3177       HeapWord *start = (HeapWord *) o;
3178       size_t word_sz = o->size();
3179       gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
3180                           " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
3181                           (void*) o, word_sz,
3182                           _g1->isMarkedPrev(o),
3183                           _g1->isMarkedNext(o),
3184                           _hr->obj_allocated_since_prev_marking(o));
3185       HeapWord *end = start + word_sz;
3186       HeapWord *cur;
3187       int *val;
3188       for (cur = start; cur < end; cur++) {
3189         val = (int *) cur;
3190         gclog_or_tty->print("\t "PTR_FORMAT":%d\n", val, *val);
3191       }
3192     }
3193   }
3194 };
3195 
3196 class VerifyRegionClosure: public HeapRegionClosure {
3197 private:
3198   bool             _par;
3199   VerifyOption     _vo;
3200   bool             _failures;
3201 public:
3202   // _vo == UsePrevMarking -> use "prev" marking information,
3203   // _vo == UseNextMarking -> use "next" marking information,
3204   // _vo == UseMarkWord    -> use mark word from object header.
3205   VerifyRegionClosure(bool par, VerifyOption vo)
3206     : _par(par),
3207       _vo(vo),
3208       _failures(false) {}
3209 
3210   bool failures() {
3211     return _failures;
3212   }
3213 
3214   bool doHeapRegion(HeapRegion* r) {
3215     if (!r->continuesHumongous()) {
3216       bool failures = false;
3217       r->verify(_vo, &failures);
3218       if (failures) {
3219         _failures = true;
3220       } else {
3221         VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
3222         r->object_iterate(&not_dead_yet_cl);
3223         if (_vo != VerifyOption_G1UseNextMarking) {
3224           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
3225             gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
3226                                    "max_live_bytes "SIZE_FORMAT" "
3227                                    "< calculated "SIZE_FORMAT,
3228                                    r->bottom(), r->end(),
3229                                    r->max_live_bytes(),
3230                                  not_dead_yet_cl.live_bytes());
3231             _failures = true;
3232           }
3233         } else {
3234           // When vo == UseNextMarking we cannot currently do a sanity
3235           // check on the live bytes as the calculation has not been
3236           // finalized yet.
3237         }
3238       }
3239     }
3240     return false; // stop the region iteration if we hit a failure
3241   }
3242 };
3243 
3244 // This is the task used for parallel verification of the heap regions
3245 
3246 class G1ParVerifyTask: public AbstractGangTask {
3247 private:
3248   G1CollectedHeap* _g1h;
3249   VerifyOption     _vo;
3250   bool             _failures;
3251 
3252 public:
3253   // _vo == UsePrevMarking -> use "prev" marking information,
3254   // _vo == UseNextMarking -> use "next" marking information,
3255   // _vo == UseMarkWord    -> use mark word from object header.
3256   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
3257     AbstractGangTask("Parallel verify task"),
3258     _g1h(g1h),
3259     _vo(vo),
3260     _failures(false) { }
3261 
3262   bool failures() {
3263     return _failures;
3264   }
3265 
3266   void work(uint worker_id) {
3267     HandleMark hm;
3268     VerifyRegionClosure blk(true, _vo);
3269     _g1h->heap_region_par_iterate_chunked(&blk, worker_id,
3270                                           _g1h->workers()->active_workers(),
3271                                           HeapRegion::ParVerifyClaimValue);
3272     if (blk.failures()) {
3273       _failures = true;
3274     }
3275   }
3276 };
3277 
3278 void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
3279   if (SafepointSynchronize::is_at_safepoint()) {
3280     assert(Thread::current()->is_VM_thread(),
3281            "Expected to be executed serially by the VM thread at this point");
3282 
3283     if (!silent) { gclog_or_tty->print("Roots "); }
3284     VerifyRootsClosure rootsCl(vo);
3285     VerifyKlassClosure klassCl(this, &rootsCl);
3286     CLDToKlassAndOopClosure cldCl(&klassCl, &rootsCl, false);
3287 
3288     // We apply the relevant closures to all the oops in the
3289     // system dictionary, class loader data graph, the string table
3290     // and the nmethods in the code cache.
3291     G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);
3292     G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
3293 
3294     process_all_roots(true,            // activate StrongRootsScope
3295                       SO_AllCodeCache, // roots scanning options
3296                       &rootsCl,
3297                       &cldCl,
3298                       &blobsCl);
3299 
3300     bool failures = rootsCl.failures() || codeRootsCl.failures();
3301 
3302     if (vo != VerifyOption_G1UseMarkWord) {
3303       // If we're verifying during a full GC then the region sets
3304       // will have been torn down at the start of the GC. Therefore
3305       // verifying the region sets will fail. So we only verify
3306       // the region sets when not in a full GC.
3307       if (!silent) { gclog_or_tty->print("HeapRegionSets "); }
3308       verify_region_sets();
3309     }
3310 
3311     if (!silent) { gclog_or_tty->print("HeapRegions "); }
3312     if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
3313       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3314              "sanity check");
3315 
3316       G1ParVerifyTask task(this, vo);
3317       assert(UseDynamicNumberOfGCThreads ||
3318         workers()->active_workers() == workers()->total_workers(),
3319         "If not dynamic should be using all the workers");
3320       int n_workers = workers()->active_workers();
3321       set_par_threads(n_workers);
3322       workers()->run_task(&task);
3323       set_par_threads(0);
3324       if (task.failures()) {
3325         failures = true;
3326       }
3327 
3328       // Checks that the expected amount of parallel work was done.
3329       // The implication is that n_workers is > 0.
3330       assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
3331              "sanity check");
3332 
3333       reset_heap_region_claim_values();
3334 
3335       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3336              "sanity check");
3337     } else {
3338       VerifyRegionClosure blk(false, vo);
3339       heap_region_iterate(&blk);
3340       if (blk.failures()) {
3341         failures = true;
3342       }
3343     }
3344     if (!silent) gclog_or_tty->print("RemSet ");
3345     rem_set()->verify();
3346 
3347     if (G1StringDedup::is_enabled()) {
3348       if (!silent) gclog_or_tty->print("StrDedup ");
3349       G1StringDedup::verify();
3350     }
3351 
3352     if (failures) {
3353       gclog_or_tty->print_cr("Heap:");
3354       // It helps to have the per-region information in the output to
3355       // help us track down what went wrong. This is why we call
3356       // print_extended_on() instead of print_on().
3357       print_extended_on(gclog_or_tty);
3358       gclog_or_tty->cr();
3359 #ifndef PRODUCT
3360       if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {
3361         concurrent_mark()->print_reachable("at-verification-failure",
3362                                            vo, false /* all */);
3363       }
3364 #endif
3365       gclog_or_tty->flush();
3366     }
3367     guarantee(!failures, "there should not have been any failures");
3368   } else {
3369     if (!silent) {
3370       gclog_or_tty->print("(SKIPPING Roots, HeapRegionSets, HeapRegions, RemSet");
3371       if (G1StringDedup::is_enabled()) {
3372         gclog_or_tty->print(", StrDedup");
3373       }
3374       gclog_or_tty->print(") ");
3375     }
3376   }
3377 }
3378 
3379 void G1CollectedHeap::verify(bool silent) {
3380   verify(silent, VerifyOption_G1UsePrevMarking);
3381 }
3382 
3383 double G1CollectedHeap::verify(bool guard, const char* msg) {
3384   double verify_time_ms = 0.0;
3385 
3386   if (guard && total_collections() >= VerifyGCStartAt) {
3387     double verify_start = os::elapsedTime();
3388     HandleMark hm;  // Discard invalid handles created during verification
3389     prepare_for_verify();
3390     Universe::verify(VerifyOption_G1UsePrevMarking, msg);
3391     verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
3392   }
3393 
3394   return verify_time_ms;
3395 }
3396 
3397 void G1CollectedHeap::verify_before_gc() {
3398   double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:");
3399   g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);
3400 }
3401 
3402 void G1CollectedHeap::verify_after_gc() {
3403   double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:");
3404   g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);
3405 }
3406 
3407 class PrintRegionClosure: public HeapRegionClosure {
3408   outputStream* _st;
3409 public:
3410   PrintRegionClosure(outputStream* st) : _st(st) {}
3411   bool doHeapRegion(HeapRegion* r) {
3412     r->print_on(_st);
3413     return false;
3414   }
3415 };
3416 
3417 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
3418                                        const HeapRegion* hr,
3419                                        const VerifyOption vo) const {
3420   switch (vo) {
3421   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
3422   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
3423   case VerifyOption_G1UseMarkWord:    return !obj->is_gc_marked();
3424   default:                            ShouldNotReachHere();
3425   }
3426   return false; // keep some compilers happy
3427 }
3428 
3429 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
3430                                        const VerifyOption vo) const {
3431   switch (vo) {
3432   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
3433   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
3434   case VerifyOption_G1UseMarkWord:    return !obj->is_gc_marked();
3435   default:                            ShouldNotReachHere();
3436   }
3437   return false; // keep some compilers happy
3438 }
3439 
3440 void G1CollectedHeap::print_on(outputStream* st) const {
3441   st->print(" %-20s", "garbage-first heap");
3442   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
3443             capacity()/K, used_unlocked()/K);
3444   st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
3445             _hrs.reserved().start(),
3446             _hrs.reserved().start() + _hrs.length() + HeapRegion::GrainWords,
3447             _hrs.reserved().end());
3448   st->cr();
3449   st->print("  region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
3450   uint young_regions = _young_list->length();
3451   st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
3452             (size_t) young_regions * HeapRegion::GrainBytes / K);
3453   uint survivor_regions = g1_policy()->recorded_survivor_regions();
3454   st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
3455             (size_t) survivor_regions * HeapRegion::GrainBytes / K);
3456   st->cr();
3457   MetaspaceAux::print_on(st);
3458 }
3459 
3460 void G1CollectedHeap::print_extended_on(outputStream* st) const {
3461   print_on(st);
3462 
3463   // Print the per-region information.
3464   st->cr();
3465   st->print_cr("Heap Regions: (Y=young(eden), SU=young(survivor), "
3466                "HS=humongous(starts), HC=humongous(continues), "
3467                "CS=collection set, F=free, TS=gc time stamp, "
3468                "PTAMS=previous top-at-mark-start, "
3469                "NTAMS=next top-at-mark-start)");
3470   PrintRegionClosure blk(st);
3471   heap_region_iterate(&blk);
3472 }
3473 
3474 void G1CollectedHeap::print_on_error(outputStream* st) const {
3475   this->CollectedHeap::print_on_error(st);
3476 
3477   if (_cm != NULL) {
3478     st->cr();
3479     _cm->print_on_error(st);
3480   }
3481 }
3482 
3483 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
3484   if (G1CollectedHeap::use_parallel_gc_threads()) {
3485     workers()->print_worker_threads_on(st);
3486   }
3487   _cmThread->print_on(st);
3488   st->cr();
3489   _cm->print_worker_threads_on(st);
3490   _cg1r->print_worker_threads_on(st);
3491   if (G1StringDedup::is_enabled()) {
3492     G1StringDedup::print_worker_threads_on(st);
3493   }
3494 }
3495 
3496 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
3497   if (G1CollectedHeap::use_parallel_gc_threads()) {
3498     workers()->threads_do(tc);
3499   }
3500   tc->do_thread(_cmThread);
3501   _cg1r->threads_do(tc);
3502   if (G1StringDedup::is_enabled()) {
3503     G1StringDedup::threads_do(tc);
3504   }
3505 }
3506 
3507 void G1CollectedHeap::print_tracing_info() const {
3508   // We'll overload this to mean "trace GC pause statistics."
3509   if (TraceYoungGenTime || TraceOldGenTime) {
3510     // The "G1CollectorPolicy" is keeping track of these stats, so delegate
3511     // to that.
3512     g1_policy()->print_tracing_info();
3513   }
3514   if (G1SummarizeRSetStats) {
3515     g1_rem_set()->print_summary_info();
3516   }
3517   if (G1SummarizeConcMark) {
3518     concurrent_mark()->print_summary_info();
3519   }
3520   g1_policy()->print_yg_surv_rate_info();
3521   SpecializationStats::print();
3522 }
3523 
3524 #ifndef PRODUCT
3525 // Helpful for debugging RSet issues.
3526 
3527 class PrintRSetsClosure : public HeapRegionClosure {
3528 private:
3529   const char* _msg;
3530   size_t _occupied_sum;
3531 
3532 public:
3533   bool doHeapRegion(HeapRegion* r) {
3534     HeapRegionRemSet* hrrs = r->rem_set();
3535     size_t occupied = hrrs->occupied();
3536     _occupied_sum += occupied;
3537 
3538     gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT,
3539                            HR_FORMAT_PARAMS(r));
3540     if (occupied == 0) {
3541       gclog_or_tty->print_cr("  RSet is empty");
3542     } else {
3543       hrrs->print();
3544     }
3545     gclog_or_tty->print_cr("----------");
3546     return false;
3547   }
3548 
3549   PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
3550     gclog_or_tty->cr();
3551     gclog_or_tty->print_cr("========================================");
3552     gclog_or_tty->print_cr("%s", msg);
3553     gclog_or_tty->cr();
3554   }
3555 
3556   ~PrintRSetsClosure() {
3557     gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum);
3558     gclog_or_tty->print_cr("========================================");
3559     gclog_or_tty->cr();
3560   }
3561 };
3562 
3563 void G1CollectedHeap::print_cset_rsets() {
3564   PrintRSetsClosure cl("Printing CSet RSets");
3565   collection_set_iterate(&cl);
3566 }
3567 
3568 void G1CollectedHeap::print_all_rsets() {
3569   PrintRSetsClosure cl("Printing All RSets");;
3570   heap_region_iterate(&cl);
3571 }
3572 #endif // PRODUCT
3573 
3574 G1CollectedHeap* G1CollectedHeap::heap() {
3575   assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
3576          "not a garbage-first heap");
3577   return _g1h;
3578 }
3579 
3580 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
3581   // always_do_update_barrier = false;
3582   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
3583   // Fill TLAB's and such
3584   accumulate_statistics_all_tlabs();
3585   ensure_parsability(true);
3586 
3587   if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) &&
3588       (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
3589     g1_rem_set()->print_periodic_summary_info("Before GC RS summary");
3590   }
3591 }
3592 
3593 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
3594 
3595   if (G1SummarizeRSetStats &&
3596       (G1SummarizeRSetStatsPeriod > 0) &&
3597       // we are at the end of the GC. Total collections has already been increased.
3598       ((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) {
3599     g1_rem_set()->print_periodic_summary_info("After GC RS summary");
3600   }
3601 
3602   // FIXME: what is this about?
3603   // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
3604   // is set.
3605   COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
3606                         "derived pointer present"));
3607   // always_do_update_barrier = true;
3608 
3609   resize_all_tlabs();
3610 
3611   // We have just completed a GC. Update the soft reference
3612   // policy with the new heap occupancy
3613   Universe::update_heap_info_at_gc();
3614 }
3615 
3616 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
3617                                                unsigned int gc_count_before,
3618                                                bool* succeeded,
3619                                                GCCause::Cause gc_cause) {
3620   assert_heap_not_locked_and_not_at_safepoint();
3621   g1_policy()->record_stop_world_start();
3622   VM_G1IncCollectionPause op(gc_count_before,
3623                              word_size,
3624                              false, /* should_initiate_conc_mark */
3625                              g1_policy()->max_pause_time_ms(),
3626                              gc_cause);
3627   VMThread::execute(&op);
3628 
3629   HeapWord* result = op.result();
3630   bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
3631   assert(result == NULL || ret_succeeded,
3632          "the result should be NULL if the VM did not succeed");
3633   *succeeded = ret_succeeded;
3634 
3635   assert_heap_not_locked();
3636   return result;
3637 }
3638 
3639 void
3640 G1CollectedHeap::doConcurrentMark() {
3641   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
3642   if (!_cmThread->in_progress()) {
3643     _cmThread->set_started();
3644     CGC_lock->notify();
3645   }
3646 }
3647 
3648 size_t G1CollectedHeap::pending_card_num() {
3649   size_t extra_cards = 0;
3650   JavaThread *curr = Threads::first();
3651   while (curr != NULL) {
3652     DirtyCardQueue& dcq = curr->dirty_card_queue();
3653     extra_cards += dcq.size();
3654     curr = curr->next();
3655   }
3656   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
3657   size_t buffer_size = dcqs.buffer_size();
3658   size_t buffer_num = dcqs.completed_buffers_num();
3659 
3660   // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes
3661   // in bytes - not the number of 'entries'. We need to convert
3662   // into a number of cards.
3663   return (buffer_size * buffer_num + extra_cards) / oopSize;
3664 }
3665 
3666 size_t G1CollectedHeap::cards_scanned() {
3667   return g1_rem_set()->cardsScanned();
3668 }
3669 
3670 bool G1CollectedHeap::humongous_region_is_always_live(uint index) {
3671   HeapRegion* region = region_at(index);
3672   assert(region->startsHumongous(), "Must start a humongous object");
3673   return oop(region->bottom())->is_objArray() || !region->rem_set()->is_empty();
3674 }
3675 
3676 class RegisterHumongousWithInCSetFastTestClosure : public HeapRegionClosure {
3677  private:
3678   size_t _total_humongous;
3679   size_t _candidate_humongous;
3680  public:
3681   RegisterHumongousWithInCSetFastTestClosure() : _total_humongous(0), _candidate_humongous(0) {
3682   }
3683 
3684   virtual bool doHeapRegion(HeapRegion* r) {
3685     if (!r->startsHumongous()) {
3686       return false;
3687     }
3688     G1CollectedHeap* g1h = G1CollectedHeap::heap();
3689 
3690     uint region_idx = r->hrs_index();
3691     bool is_candidate = !g1h->humongous_region_is_always_live(region_idx);
3692     // Is_candidate already filters out humongous regions with some remembered set.
3693     // This will not lead to humongous object that we mistakenly keep alive because
3694     // during young collection the remembered sets will only be added to.
3695     if (is_candidate) {
3696       g1h->register_humongous_region_with_in_cset_fast_test(region_idx);
3697       _candidate_humongous++;
3698     }
3699     _total_humongous++;
3700 
3701     return false;
3702   }
3703 
3704   size_t total_humongous() const { return _total_humongous; }
3705   size_t candidate_humongous() const { return _candidate_humongous; }
3706 };
3707 
3708 void G1CollectedHeap::register_humongous_regions_with_in_cset_fast_test() {
3709   if (!G1ReclaimDeadHumongousObjectsAtYoungGC) {
3710     g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(0, 0);
3711     return;
3712   }
3713 
3714   RegisterHumongousWithInCSetFastTestClosure cl;
3715   heap_region_iterate(&cl);
3716   g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(cl.total_humongous(),
3717                                                                   cl.candidate_humongous());
3718   _has_humongous_reclaim_candidates = cl.candidate_humongous() > 0;
3719 
3720   if (_has_humongous_reclaim_candidates) {
3721     clear_humongous_is_live_table();
3722   }
3723 }
3724 
3725 void
3726 G1CollectedHeap::setup_surviving_young_words() {
3727   assert(_surviving_young_words == NULL, "pre-condition");
3728   uint array_length = g1_policy()->young_cset_region_length();
3729   _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC);
3730   if (_surviving_young_words == NULL) {
3731     vm_exit_out_of_memory(sizeof(size_t) * array_length, OOM_MALLOC_ERROR,
3732                           "Not enough space for young surv words summary.");
3733   }
3734   memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t));
3735 #ifdef ASSERT
3736   for (uint i = 0;  i < array_length; ++i) {
3737     assert( _surviving_young_words[i] == 0, "memset above" );
3738   }
3739 #endif // !ASSERT
3740 }
3741 
3742 void
3743 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
3744   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
3745   uint array_length = g1_policy()->young_cset_region_length();
3746   for (uint i = 0; i < array_length; ++i) {
3747     _surviving_young_words[i] += surv_young_words[i];
3748   }
3749 }
3750 
3751 void
3752 G1CollectedHeap::cleanup_surviving_young_words() {
3753   guarantee( _surviving_young_words != NULL, "pre-condition" );
3754   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words, mtGC);
3755   _surviving_young_words = NULL;
3756 }
3757 
3758 #ifdef ASSERT
3759 class VerifyCSetClosure: public HeapRegionClosure {
3760 public:
3761   bool doHeapRegion(HeapRegion* hr) {
3762     // Here we check that the CSet region's RSet is ready for parallel
3763     // iteration. The fields that we'll verify are only manipulated
3764     // when the region is part of a CSet and is collected. Afterwards,
3765     // we reset these fields when we clear the region's RSet (when the
3766     // region is freed) so they are ready when the region is
3767     // re-allocated. The only exception to this is if there's an
3768     // evacuation failure and instead of freeing the region we leave
3769     // it in the heap. In that case, we reset these fields during
3770     // evacuation failure handling.
3771     guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");
3772 
3773     // Here's a good place to add any other checks we'd like to
3774     // perform on CSet regions.
3775     return false;
3776   }
3777 };
3778 #endif // ASSERT
3779 
3780 #if TASKQUEUE_STATS
3781 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
3782   st->print_raw_cr("GC Task Stats");
3783   st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
3784   st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
3785 }
3786 
3787 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
3788   print_taskqueue_stats_hdr(st);
3789 
3790   TaskQueueStats totals;
3791   const int n = workers() != NULL ? workers()->total_workers() : 1;
3792   for (int i = 0; i < n; ++i) {
3793     st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();
3794     totals += task_queue(i)->stats;
3795   }
3796   st->print_raw("tot "); totals.print(st); st->cr();
3797 
3798   DEBUG_ONLY(totals.verify());
3799 }
3800 
3801 void G1CollectedHeap::reset_taskqueue_stats() {
3802   const int n = workers() != NULL ? workers()->total_workers() : 1;
3803   for (int i = 0; i < n; ++i) {
3804     task_queue(i)->stats.reset();
3805   }
3806 }
3807 #endif // TASKQUEUE_STATS
3808 
3809 void G1CollectedHeap::log_gc_header() {
3810   if (!G1Log::fine()) {
3811     return;
3812   }
3813 
3814   gclog_or_tty->gclog_stamp(_gc_tracer_stw->gc_id());
3815 
3816   GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
3817     .append(g1_policy()->gcs_are_young() ? "(young)" : "(mixed)")
3818     .append(g1_policy()->during_initial_mark_pause() ? " (initial-mark)" : "");
3819 
3820   gclog_or_tty->print("[%s", (const char*)gc_cause_str);
3821 }
3822 
3823 void G1CollectedHeap::log_gc_footer(double pause_time_sec) {
3824   if (!G1Log::fine()) {
3825     return;
3826   }
3827 
3828   if (G1Log::finer()) {
3829     if (evacuation_failed()) {
3830       gclog_or_tty->print(" (to-space exhausted)");
3831     }
3832     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3833     g1_policy()->phase_times()->note_gc_end();
3834     g1_policy()->phase_times()->print(pause_time_sec);
3835     g1_policy()->print_detailed_heap_transition();
3836   } else {
3837     if (evacuation_failed()) {
3838       gclog_or_tty->print("--");
3839     }
3840     g1_policy()->print_heap_transition();
3841     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3842   }
3843   gclog_or_tty->flush();
3844 }
3845 
3846 bool
3847 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
3848   assert_at_safepoint(true /* should_be_vm_thread */);
3849   guarantee(!is_gc_active(), "collection is not reentrant");
3850 
3851   if (GC_locker::check_active_before_gc()) {
3852     return false;
3853   }
3854 
3855   _gc_timer_stw->register_gc_start();
3856 
3857   _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
3858 
3859   SvcGCMarker sgcm(SvcGCMarker::MINOR);
3860   ResourceMark rm;
3861 
3862   print_heap_before_gc();
3863   trace_heap_before_gc(_gc_tracer_stw);
3864 
3865   verify_region_sets_optional();
3866   verify_dirty_young_regions();
3867 
3868   // This call will decide whether this pause is an initial-mark
3869   // pause. If it is, during_initial_mark_pause() will return true
3870   // for the duration of this pause.
3871   g1_policy()->decide_on_conc_mark_initiation();
3872 
3873   // We do not allow initial-mark to be piggy-backed on a mixed GC.
3874   assert(!g1_policy()->during_initial_mark_pause() ||
3875           g1_policy()->gcs_are_young(), "sanity");
3876 
3877   // We also do not allow mixed GCs during marking.
3878   assert(!mark_in_progress() || g1_policy()->gcs_are_young(), "sanity");
3879 
3880   // Record whether this pause is an initial mark. When the current
3881   // thread has completed its logging output and it's safe to signal
3882   // the CM thread, the flag's value in the policy has been reset.
3883   bool should_start_conc_mark = g1_policy()->during_initial_mark_pause();
3884 
3885   // Inner scope for scope based logging, timers, and stats collection
3886   {
3887     EvacuationInfo evacuation_info;
3888 
3889     if (g1_policy()->during_initial_mark_pause()) {
3890       // We are about to start a marking cycle, so we increment the
3891       // full collection counter.
3892       increment_old_marking_cycles_started();
3893       register_concurrent_cycle_start(_gc_timer_stw->gc_start());
3894     }
3895 
3896     _gc_tracer_stw->report_yc_type(yc_type());
3897 
3898     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
3899 
3900     int active_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
3901                                 workers()->active_workers() : 1);
3902     double pause_start_sec = os::elapsedTime();
3903     g1_policy()->phase_times()->note_gc_start(active_workers);
3904     log_gc_header();
3905 
3906     TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
3907     TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
3908 
3909     // If the secondary_free_list is not empty, append it to the
3910     // free_list. No need to wait for the cleanup operation to finish;
3911     // the region allocation code will check the secondary_free_list
3912     // and wait if necessary. If the G1StressConcRegionFreeing flag is
3913     // set, skip this step so that the region allocation code has to
3914     // get entries from the secondary_free_list.
3915     if (!G1StressConcRegionFreeing) {
3916       append_secondary_free_list_if_not_empty_with_lock();
3917     }
3918 
3919     assert(check_young_list_well_formed(), "young list should be well formed");
3920     assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3921            "sanity check");
3922 
3923     // Don't dynamically change the number of GC threads this early.  A value of
3924     // 0 is used to indicate serial work.  When parallel work is done,
3925     // it will be set.
3926 
3927     { // Call to jvmpi::post_class_unload_events must occur outside of active GC
3928       IsGCActiveMark x;
3929 
3930       gc_prologue(false);
3931       increment_total_collections(false /* full gc */);
3932       increment_gc_time_stamp();
3933 
3934       verify_before_gc();
3935 
3936       check_bitmaps("GC Start");
3937 
3938       COMPILER2_PRESENT(DerivedPointerTable::clear());
3939 
3940       // Please see comment in g1CollectedHeap.hpp and
3941       // G1CollectedHeap::ref_processing_init() to see how
3942       // reference processing currently works in G1.
3943 
3944       // Enable discovery in the STW reference processor
3945       ref_processor_stw()->enable_discovery(true /*verify_disabled*/,
3946                                             true /*verify_no_refs*/);
3947 
3948       {
3949         // We want to temporarily turn off discovery by the
3950         // CM ref processor, if necessary, and turn it back on
3951         // on again later if we do. Using a scoped
3952         // NoRefDiscovery object will do this.
3953         NoRefDiscovery no_cm_discovery(ref_processor_cm());
3954 
3955         // Forget the current alloc region (we might even choose it to be part
3956         // of the collection set!).
3957         release_mutator_alloc_region();
3958 
3959         // We should call this after we retire the mutator alloc
3960         // region(s) so that all the ALLOC / RETIRE events are generated
3961         // before the start GC event.
3962         _hr_printer.start_gc(false /* full */, (size_t) total_collections());
3963 
3964         // This timing is only used by the ergonomics to handle our pause target.
3965         // It is unclear why this should not include the full pause. We will
3966         // investigate this in CR 7178365.
3967         //
3968         // Preserving the old comment here if that helps the investigation:
3969         //
3970         // The elapsed time induced by the start time below deliberately elides
3971         // the possible verification above.
3972         double sample_start_time_sec = os::elapsedTime();
3973 
3974 #if YOUNG_LIST_VERBOSE
3975         gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
3976         _young_list->print();
3977         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
3978 #endif // YOUNG_LIST_VERBOSE
3979 
3980         g1_policy()->record_collection_pause_start(sample_start_time_sec);
3981 
3982         double scan_wait_start = os::elapsedTime();
3983         // We have to wait until the CM threads finish scanning the
3984         // root regions as it's the only way to ensure that all the
3985         // objects on them have been correctly scanned before we start
3986         // moving them during the GC.
3987         bool waited = _cm->root_regions()->wait_until_scan_finished();
3988         double wait_time_ms = 0.0;
3989         if (waited) {
3990           double scan_wait_end = os::elapsedTime();
3991           wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
3992         }
3993         g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms);
3994 
3995 #if YOUNG_LIST_VERBOSE
3996         gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
3997         _young_list->print();
3998 #endif // YOUNG_LIST_VERBOSE
3999 
4000         if (g1_policy()->during_initial_mark_pause()) {
4001           concurrent_mark()->checkpointRootsInitialPre();
4002         }
4003 
4004 #if YOUNG_LIST_VERBOSE
4005         gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
4006         _young_list->print();
4007         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4008 #endif // YOUNG_LIST_VERBOSE
4009 
4010         g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info);
4011 
4012         register_humongous_regions_with_in_cset_fast_test();
4013 
4014         _cm->note_start_of_gc();
4015         // We should not verify the per-thread SATB buffers given that
4016         // we have not filtered them yet (we'll do so during the
4017         // GC). We also call this after finalize_cset() to
4018         // ensure that the CSet has been finalized.
4019         _cm->verify_no_cset_oops(true  /* verify_stacks */,
4020                                  true  /* verify_enqueued_buffers */,
4021                                  false /* verify_thread_buffers */,
4022                                  true  /* verify_fingers */);
4023 
4024         if (_hr_printer.is_active()) {
4025           HeapRegion* hr = g1_policy()->collection_set();
4026           while (hr != NULL) {
4027             G1HRPrinter::RegionType type;
4028             if (!hr->is_young()) {
4029               type = G1HRPrinter::Old;
4030             } else if (hr->is_survivor()) {
4031               type = G1HRPrinter::Survivor;
4032             } else {
4033               type = G1HRPrinter::Eden;
4034             }
4035             _hr_printer.cset(hr);
4036             hr = hr->next_in_collection_set();
4037           }
4038         }
4039 
4040 #ifdef ASSERT
4041         VerifyCSetClosure cl;
4042         collection_set_iterate(&cl);
4043 #endif // ASSERT
4044 
4045         setup_surviving_young_words();
4046 
4047         // Initialize the GC alloc regions.
4048         init_gc_alloc_regions(evacuation_info);
4049 
4050         // Actually do the work...
4051         evacuate_collection_set(evacuation_info);
4052 
4053         // We do this to mainly verify the per-thread SATB buffers
4054         // (which have been filtered by now) since we didn't verify
4055         // them earlier. No point in re-checking the stacks / enqueued
4056         // buffers given that the CSet has not changed since last time
4057         // we checked.
4058         _cm->verify_no_cset_oops(false /* verify_stacks */,
4059                                  false /* verify_enqueued_buffers */,
4060                                  true  /* verify_thread_buffers */,
4061                                  true  /* verify_fingers */);
4062 
4063         free_collection_set(g1_policy()->collection_set(), evacuation_info);
4064 
4065         eagerly_reclaim_humongous_regions();
4066 
4067         g1_policy()->clear_collection_set();
4068 
4069         cleanup_surviving_young_words();
4070 
4071         // Start a new incremental collection set for the next pause.
4072         g1_policy()->start_incremental_cset_building();
4073 
4074         clear_cset_fast_test();
4075 
4076         _young_list->reset_sampled_info();
4077 
4078         // Don't check the whole heap at this point as the
4079         // GC alloc regions from this pause have been tagged
4080         // as survivors and moved on to the survivor list.
4081         // Survivor regions will fail the !is_young() check.
4082         assert(check_young_list_empty(false /* check_heap */),
4083           "young list should be empty");
4084 
4085 #if YOUNG_LIST_VERBOSE
4086         gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
4087         _young_list->print();
4088 #endif // YOUNG_LIST_VERBOSE
4089 
4090         g1_policy()->record_survivor_regions(_young_list->survivor_length(),
4091                                              _young_list->first_survivor_region(),
4092                                              _young_list->last_survivor_region());
4093 
4094         _young_list->reset_auxilary_lists();
4095 
4096         if (evacuation_failed()) {
4097           _summary_bytes_used = recalculate_used();
4098           uint n_queues = MAX2((int)ParallelGCThreads, 1);
4099           for (uint i = 0; i < n_queues; i++) {
4100             if (_evacuation_failed_info_array[i].has_failed()) {
4101               _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4102             }
4103           }
4104         } else {
4105           // The "used" of the the collection set have already been subtracted
4106           // when they were freed.  Add in the bytes evacuated.
4107           _summary_bytes_used += g1_policy()->bytes_copied_during_gc();
4108         }
4109 
4110         if (g1_policy()->during_initial_mark_pause()) {
4111           // We have to do this before we notify the CM threads that
4112           // they can start working to make sure that all the
4113           // appropriate initialization is done on the CM object.
4114           concurrent_mark()->checkpointRootsInitialPost();
4115           set_marking_started();
4116           // Note that we don't actually trigger the CM thread at
4117           // this point. We do that later when we're sure that
4118           // the current thread has completed its logging output.
4119         }
4120 
4121         allocate_dummy_regions();
4122 
4123 #if YOUNG_LIST_VERBOSE
4124         gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
4125         _young_list->print();
4126         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4127 #endif // YOUNG_LIST_VERBOSE
4128 
4129         init_mutator_alloc_region();
4130 
4131         {
4132           size_t expand_bytes = g1_policy()->expansion_amount();
4133           if (expand_bytes > 0) {
4134             size_t bytes_before = capacity();
4135             // No need for an ergo verbose message here,
4136             // expansion_amount() does this when it returns a value > 0.
4137             if (!expand(expand_bytes)) {
4138               // We failed to expand the heap. Cannot do anything about it.
4139             }
4140           }
4141         }
4142 
4143         // We redo the verification but now wrt to the new CSet which
4144         // has just got initialized after the previous CSet was freed.
4145         _cm->verify_no_cset_oops(true  /* verify_stacks */,
4146                                  true  /* verify_enqueued_buffers */,
4147                                  true  /* verify_thread_buffers */,
4148                                  true  /* verify_fingers */);
4149         _cm->note_end_of_gc();
4150 
4151         // This timing is only used by the ergonomics to handle our pause target.
4152         // It is unclear why this should not include the full pause. We will
4153         // investigate this in CR 7178365.
4154         double sample_end_time_sec = os::elapsedTime();
4155         double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
4156         g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info);
4157 
4158         MemoryService::track_memory_usage();
4159 
4160         // In prepare_for_verify() below we'll need to scan the deferred
4161         // update buffers to bring the RSets up-to-date if
4162         // G1HRRSFlushLogBuffersOnVerify has been set. While scanning
4163         // the update buffers we'll probably need to scan cards on the
4164         // regions we just allocated to (i.e., the GC alloc
4165         // regions). However, during the last GC we called
4166         // set_saved_mark() on all the GC alloc regions, so card
4167         // scanning might skip the [saved_mark_word()...top()] area of
4168         // those regions (i.e., the area we allocated objects into
4169         // during the last GC). But it shouldn't. Given that
4170         // saved_mark_word() is conditional on whether the GC time stamp
4171         // on the region is current or not, by incrementing the GC time
4172         // stamp here we invalidate all the GC time stamps on all the
4173         // regions and saved_mark_word() will simply return top() for
4174         // all the regions. This is a nicer way of ensuring this rather
4175         // than iterating over the regions and fixing them. In fact, the
4176         // GC time stamp increment here also ensures that
4177         // saved_mark_word() will return top() between pauses, i.e.,
4178         // during concurrent refinement. So we don't need the
4179         // is_gc_active() check to decided which top to use when
4180         // scanning cards (see CR 7039627).
4181         increment_gc_time_stamp();
4182 
4183         verify_after_gc();
4184         check_bitmaps("GC End");
4185 
4186         assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
4187         ref_processor_stw()->verify_no_references_recorded();
4188 
4189         // CM reference discovery will be re-enabled if necessary.
4190       }
4191 
4192       // We should do this after we potentially expand the heap so
4193       // that all the COMMIT events are generated before the end GC
4194       // event, and after we retire the GC alloc regions so that all
4195       // RETIRE events are generated before the end GC event.
4196       _hr_printer.end_gc(false /* full */, (size_t) total_collections());
4197 
4198 #ifdef TRACESPINNING
4199       ParallelTaskTerminator::print_termination_counts();
4200 #endif
4201 
4202       gc_epilogue(false);
4203     }
4204 
4205     // Print the remainder of the GC log output.
4206     log_gc_footer(os::elapsedTime() - pause_start_sec);
4207 
4208     // It is not yet to safe to tell the concurrent mark to
4209     // start as we have some optional output below. We don't want the
4210     // output from the concurrent mark thread interfering with this
4211     // logging output either.
4212 
4213     _hrs.verify_optional();
4214     verify_region_sets_optional();
4215 
4216     TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());
4217     TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
4218 
4219     print_heap_after_gc();
4220     trace_heap_after_gc(_gc_tracer_stw);
4221 
4222     // We must call G1MonitoringSupport::update_sizes() in the same scoping level
4223     // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
4224     // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
4225     // before any GC notifications are raised.
4226     g1mm()->update_sizes();
4227 
4228     _gc_tracer_stw->report_evacuation_info(&evacuation_info);
4229     _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold());
4230     _gc_timer_stw->register_gc_end();
4231     _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());
4232   }
4233   // It should now be safe to tell the concurrent mark thread to start
4234   // without its logging output interfering with the logging output
4235   // that came from the pause.
4236 
4237   if (should_start_conc_mark) {
4238     // CAUTION: after the doConcurrentMark() call below,
4239     // the concurrent marking thread(s) could be running
4240     // concurrently with us. Make sure that anything after
4241     // this point does not assume that we are the only GC thread
4242     // running. Note: of course, the actual marking work will
4243     // not start until the safepoint itself is released in
4244     // SuspendibleThreadSet::desynchronize().
4245     doConcurrentMark();
4246   }
4247 
4248   return true;
4249 }
4250 
4251 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose)
4252 {
4253   size_t gclab_word_size;
4254   switch (purpose) {
4255     case GCAllocForSurvived:
4256       gclab_word_size = _survivor_plab_stats.desired_plab_sz();
4257       break;
4258     case GCAllocForTenured:
4259       gclab_word_size = _old_plab_stats.desired_plab_sz();
4260       break;
4261     default:
4262       assert(false, "unknown GCAllocPurpose");
4263       gclab_word_size = _old_plab_stats.desired_plab_sz();
4264       break;
4265   }
4266 
4267   // Prevent humongous PLAB sizes for two reasons:
4268   // * PLABs are allocated using a similar paths as oops, but should
4269   //   never be in a humongous region
4270   // * Allowing humongous PLABs needlessly churns the region free lists
4271   return MIN2(_humongous_object_threshold_in_words, gclab_word_size);
4272 }
4273 
4274 void G1CollectedHeap::init_mutator_alloc_region() {
4275   assert(_mutator_alloc_region.get() == NULL, "pre-condition");
4276   _mutator_alloc_region.init();
4277 }
4278 
4279 void G1CollectedHeap::release_mutator_alloc_region() {
4280   _mutator_alloc_region.release();
4281   assert(_mutator_alloc_region.get() == NULL, "post-condition");
4282 }
4283 
4284 void G1CollectedHeap::use_retained_old_gc_alloc_region(EvacuationInfo& evacuation_info) {
4285   HeapRegion* retained_region = _retained_old_gc_alloc_region;
4286   _retained_old_gc_alloc_region = NULL;
4287 
4288   // We will discard the current GC alloc region if:
4289   // a) it's in the collection set (it can happen!),
4290   // b) it's already full (no point in using it),
4291   // c) it's empty (this means that it was emptied during
4292   // a cleanup and it should be on the free list now), or
4293   // d) it's humongous (this means that it was emptied
4294   // during a cleanup and was added to the free list, but
4295   // has been subsequently used to allocate a humongous
4296   // object that may be less than the region size).
4297   if (retained_region != NULL &&
4298       !retained_region->in_collection_set() &&
4299       !(retained_region->top() == retained_region->end()) &&
4300       !retained_region->is_empty() &&
4301       !retained_region->isHumongous()) {
4302     retained_region->record_top_and_timestamp();
4303     // The retained region was added to the old region set when it was
4304     // retired. We have to remove it now, since we don't allow regions
4305     // we allocate to in the region sets. We'll re-add it later, when
4306     // it's retired again.
4307     _old_set.remove(retained_region);
4308     bool during_im = g1_policy()->during_initial_mark_pause();
4309     retained_region->note_start_of_copying(during_im);
4310     _old_gc_alloc_region.set(retained_region);
4311     _hr_printer.reuse(retained_region);
4312     evacuation_info.set_alloc_regions_used_before(retained_region->used());
4313   }
4314 }
4315 
4316 void G1CollectedHeap::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
4317   assert_at_safepoint(true /* should_be_vm_thread */);
4318 
4319   _survivor_gc_alloc_region.init();
4320   _old_gc_alloc_region.init();
4321 
4322   use_retained_old_gc_alloc_region(evacuation_info);
4323 }
4324 
4325 void G1CollectedHeap::release_gc_alloc_regions(uint no_of_gc_workers, EvacuationInfo& evacuation_info) {
4326   evacuation_info.set_allocation_regions(_survivor_gc_alloc_region.count() +
4327                                          _old_gc_alloc_region.count());
4328   _survivor_gc_alloc_region.release();
4329   // If we have an old GC alloc region to release, we'll save it in
4330   // _retained_old_gc_alloc_region. If we don't
4331   // _retained_old_gc_alloc_region will become NULL. This is what we
4332   // want either way so no reason to check explicitly for either
4333   // condition.
4334   _retained_old_gc_alloc_region = _old_gc_alloc_region.release();
4335 
4336   if (ResizePLAB) {
4337     _survivor_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4338     _old_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4339   }
4340 }
4341 
4342 void G1CollectedHeap::abandon_gc_alloc_regions() {
4343   assert(_survivor_gc_alloc_region.get() == NULL, "pre-condition");
4344   assert(_old_gc_alloc_region.get() == NULL, "pre-condition");
4345   _retained_old_gc_alloc_region = NULL;
4346 }
4347 
4348 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
4349   _drain_in_progress = false;
4350   set_evac_failure_closure(cl);
4351   _evac_failure_scan_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true);
4352 }
4353 
4354 void G1CollectedHeap::finalize_for_evac_failure() {
4355   assert(_evac_failure_scan_stack != NULL &&
4356          _evac_failure_scan_stack->length() == 0,
4357          "Postcondition");
4358   assert(!_drain_in_progress, "Postcondition");
4359   delete _evac_failure_scan_stack;
4360   _evac_failure_scan_stack = NULL;
4361 }
4362 
4363 void G1CollectedHeap::remove_self_forwarding_pointers() {
4364   assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4365 
4366   double remove_self_forwards_start = os::elapsedTime();
4367 
4368   G1ParRemoveSelfForwardPtrsTask rsfp_task(this);
4369 
4370   if (G1CollectedHeap::use_parallel_gc_threads()) {
4371     set_par_threads();
4372     workers()->run_task(&rsfp_task);
4373     set_par_threads(0);
4374   } else {
4375     rsfp_task.work(0);
4376   }
4377 
4378   assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");
4379 
4380   // Reset the claim values in the regions in the collection set.
4381   reset_cset_heap_region_claim_values();
4382 
4383   assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4384 
4385   // Now restore saved marks, if any.
4386   assert(_objs_with_preserved_marks.size() ==
4387             _preserved_marks_of_objs.size(), "Both or none.");
4388   while (!_objs_with_preserved_marks.is_empty()) {
4389     oop obj = _objs_with_preserved_marks.pop();
4390     markOop m = _preserved_marks_of_objs.pop();
4391     obj->set_mark(m);
4392   }
4393   _objs_with_preserved_marks.clear(true);
4394   _preserved_marks_of_objs.clear(true);
4395 
4396   g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0);
4397 }
4398 
4399 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
4400   _evac_failure_scan_stack->push(obj);
4401 }
4402 
4403 void G1CollectedHeap::drain_evac_failure_scan_stack() {
4404   assert(_evac_failure_scan_stack != NULL, "precondition");
4405 
4406   while (_evac_failure_scan_stack->length() > 0) {
4407      oop obj = _evac_failure_scan_stack->pop();
4408      _evac_failure_closure->set_region(heap_region_containing(obj));
4409      obj->oop_iterate_backwards(_evac_failure_closure);
4410   }
4411 }
4412 
4413 oop
4414 G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state,
4415                                                oop old) {
4416   assert(obj_in_cs(old),
4417          err_msg("obj: "PTR_FORMAT" should still be in the CSet",
4418                  (HeapWord*) old));
4419   markOop m = old->mark();
4420   oop forward_ptr = old->forward_to_atomic(old);
4421   if (forward_ptr == NULL) {
4422     // Forward-to-self succeeded.
4423     assert(_par_scan_state != NULL, "par scan state");
4424     OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
4425     uint queue_num = _par_scan_state->queue_num();
4426 
4427     _evacuation_failed = true;
4428     _evacuation_failed_info_array[queue_num].register_copy_failure(old->size());
4429     if (_evac_failure_closure != cl) {
4430       MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
4431       assert(!_drain_in_progress,
4432              "Should only be true while someone holds the lock.");
4433       // Set the global evac-failure closure to the current thread's.
4434       assert(_evac_failure_closure == NULL, "Or locking has failed.");
4435       set_evac_failure_closure(cl);
4436       // Now do the common part.
4437       handle_evacuation_failure_common(old, m);
4438       // Reset to NULL.
4439       set_evac_failure_closure(NULL);
4440     } else {
4441       // The lock is already held, and this is recursive.
4442       assert(_drain_in_progress, "This should only be the recursive case.");
4443       handle_evacuation_failure_common(old, m);
4444     }
4445     return old;
4446   } else {
4447     // Forward-to-self failed. Either someone else managed to allocate
4448     // space for this object (old != forward_ptr) or they beat us in
4449     // self-forwarding it (old == forward_ptr).
4450     assert(old == forward_ptr || !obj_in_cs(forward_ptr),
4451            err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" "
4452                    "should not be in the CSet",
4453                    (HeapWord*) old, (HeapWord*) forward_ptr));
4454     return forward_ptr;
4455   }
4456 }
4457 
4458 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
4459   preserve_mark_if_necessary(old, m);
4460 
4461   HeapRegion* r = heap_region_containing(old);
4462   if (!r->evacuation_failed()) {
4463     r->set_evacuation_failed(true);
4464     _hr_printer.evac_failure(r);
4465   }
4466 
4467   push_on_evac_failure_scan_stack(old);
4468 
4469   if (!_drain_in_progress) {
4470     // prevent recursion in copy_to_survivor_space()
4471     _drain_in_progress = true;
4472     drain_evac_failure_scan_stack();
4473     _drain_in_progress = false;
4474   }
4475 }
4476 
4477 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
4478   assert(evacuation_failed(), "Oversaving!");
4479   // We want to call the "for_promotion_failure" version only in the
4480   // case of a promotion failure.
4481   if (m->must_be_preserved_for_promotion_failure(obj)) {
4482     _objs_with_preserved_marks.push(obj);
4483     _preserved_marks_of_objs.push(m);
4484   }
4485 }
4486 
4487 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
4488                                                   size_t word_size) {
4489   if (purpose == GCAllocForSurvived) {
4490     HeapWord* result = survivor_attempt_allocation(word_size);
4491     if (result != NULL) {
4492       return result;
4493     } else {
4494       // Let's try to allocate in the old gen in case we can fit the
4495       // object there.
4496       return old_attempt_allocation(word_size);
4497     }
4498   } else {
4499     assert(purpose ==  GCAllocForTenured, "sanity");
4500     HeapWord* result = old_attempt_allocation(word_size);
4501     if (result != NULL) {
4502       return result;
4503     } else {
4504       // Let's try to allocate in the survivors in case we can fit the
4505       // object there.
4506       return survivor_attempt_allocation(word_size);
4507     }
4508   }
4509 
4510   ShouldNotReachHere();
4511   // Trying to keep some compilers happy.
4512   return NULL;
4513 }
4514 
4515 G1ParGCAllocBuffer::G1ParGCAllocBuffer(size_t gclab_word_size) :
4516   ParGCAllocBuffer(gclab_word_size), _retired(true) { }
4517 
4518 void G1ParCopyHelper::mark_object(oop obj) {
4519   assert(!_g1->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet");
4520 
4521   // We know that the object is not moving so it's safe to read its size.
4522   _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
4523 }
4524 
4525 void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) {
4526   assert(from_obj->is_forwarded(), "from obj should be forwarded");
4527   assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");
4528   assert(from_obj != to_obj, "should not be self-forwarded");
4529 
4530   assert(_g1->heap_region_containing(from_obj)->in_collection_set(), "from obj should be in the CSet");
4531   assert(!_g1->heap_region_containing(to_obj)->in_collection_set(), "should not mark objects in the CSet");
4532 
4533   // The object might be in the process of being copied by another
4534   // worker so we cannot trust that its to-space image is
4535   // well-formed. So we have to read its size from its from-space
4536   // image which we know should not be changing.
4537   _cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);
4538 }
4539 
4540 template <class T>
4541 void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) {
4542   if (_g1->heap_region_containing_raw(new_obj)->is_young()) {
4543     _scanned_klass->record_modified_oops();
4544   }
4545 }
4546 
4547 template <G1Barrier barrier, G1Mark do_mark_object>
4548 template <class T>
4549 void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) {
4550   T heap_oop = oopDesc::load_heap_oop(p);
4551 
4552   if (oopDesc::is_null(heap_oop)) {
4553     return;
4554   }
4555 
4556   oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
4557 
4558   assert(_worker_id == _par_scan_state->queue_num(), "sanity");
4559 
4560   G1CollectedHeap::in_cset_state_t state = _g1->in_cset_state(obj);
4561 
4562   if (state == G1CollectedHeap::InCSet) {
4563     oop forwardee;
4564     if (obj->is_forwarded()) {
4565       forwardee = obj->forwardee();
4566     } else {
4567       forwardee = _par_scan_state->copy_to_survivor_space(obj);
4568     }
4569     assert(forwardee != NULL, "forwardee should not be NULL");
4570     oopDesc::encode_store_heap_oop(p, forwardee);
4571     if (do_mark_object != G1MarkNone && forwardee != obj) {
4572       // If the object is self-forwarded we don't need to explicitly
4573       // mark it, the evacuation failure protocol will do so.
4574       mark_forwarded_object(obj, forwardee);
4575     }
4576 
4577     if (barrier == G1BarrierKlass) {
4578       do_klass_barrier(p, forwardee);
4579     }
4580   } else {
4581     if (state == G1CollectedHeap::IsHumongous) {
4582       _g1->set_humongous_is_live(obj);
4583     }
4584     // The object is not in collection set. If we're a root scanning
4585     // closure during an initial mark pause then attempt to mark the object.
4586     if (do_mark_object == G1MarkFromRoot) {
4587       mark_object(obj);
4588     }
4589   }
4590 
4591   if (barrier == G1BarrierEvac) {
4592     _par_scan_state->update_rs(_from, p, _worker_id);
4593   }
4594 }
4595 
4596 template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(oop* p);
4597 template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(narrowOop* p);
4598 
4599 class G1ParEvacuateFollowersClosure : public VoidClosure {
4600 protected:
4601   G1CollectedHeap*              _g1h;
4602   G1ParScanThreadState*         _par_scan_state;
4603   RefToScanQueueSet*            _queues;
4604   ParallelTaskTerminator*       _terminator;
4605 
4606   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
4607   RefToScanQueueSet*      queues()         { return _queues; }
4608   ParallelTaskTerminator* terminator()     { return _terminator; }
4609 
4610 public:
4611   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4612                                 G1ParScanThreadState* par_scan_state,
4613                                 RefToScanQueueSet* queues,
4614                                 ParallelTaskTerminator* terminator)
4615     : _g1h(g1h), _par_scan_state(par_scan_state),
4616       _queues(queues), _terminator(terminator) {}
4617 
4618   void do_void();
4619 
4620 private:
4621   inline bool offer_termination();
4622 };
4623 
4624 bool G1ParEvacuateFollowersClosure::offer_termination() {
4625   G1ParScanThreadState* const pss = par_scan_state();
4626   pss->start_term_time();
4627   const bool res = terminator()->offer_termination();
4628   pss->end_term_time();
4629   return res;
4630 }
4631 
4632 void G1ParEvacuateFollowersClosure::do_void() {
4633   G1ParScanThreadState* const pss = par_scan_state();
4634   pss->trim_queue();
4635   do {
4636     pss->steal_and_trim_queue(queues());
4637   } while (!offer_termination());
4638 }
4639 
4640 class G1KlassScanClosure : public KlassClosure {
4641  G1ParCopyHelper* _closure;
4642  bool             _process_only_dirty;
4643  int              _count;
4644  public:
4645   G1KlassScanClosure(G1ParCopyHelper* closure, bool process_only_dirty)
4646       : _process_only_dirty(process_only_dirty), _closure(closure), _count(0) {}
4647   void do_klass(Klass* klass) {
4648     // If the klass has not been dirtied we know that there's
4649     // no references into  the young gen and we can skip it.
4650    if (!_process_only_dirty || klass->has_modified_oops()) {
4651       // Clean the klass since we're going to scavenge all the metadata.
4652       klass->clear_modified_oops();
4653 
4654       // Tell the closure that this klass is the Klass to scavenge
4655       // and is the one to dirty if oops are left pointing into the young gen.
4656       _closure->set_scanned_klass(klass);
4657 
4658       klass->oops_do(_closure);
4659 
4660       _closure->set_scanned_klass(NULL);
4661     }
4662     _count++;
4663   }
4664 };
4665 
4666 class G1ParTask : public AbstractGangTask {
4667 protected:
4668   G1CollectedHeap*       _g1h;
4669   RefToScanQueueSet      *_queues;
4670   ParallelTaskTerminator _terminator;
4671   uint _n_workers;
4672 
4673   Mutex _stats_lock;
4674   Mutex* stats_lock() { return &_stats_lock; }
4675 
4676 public:
4677   G1ParTask(G1CollectedHeap* g1h, RefToScanQueueSet *task_queues)
4678     : AbstractGangTask("G1 collection"),
4679       _g1h(g1h),
4680       _queues(task_queues),
4681       _terminator(0, _queues),
4682       _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
4683   {}
4684 
4685   RefToScanQueueSet* queues() { return _queues; }
4686 
4687   RefToScanQueue *work_queue(int i) {
4688     return queues()->queue(i);
4689   }
4690 
4691   ParallelTaskTerminator* terminator() { return &_terminator; }
4692 
4693   virtual void set_for_termination(int active_workers) {
4694     // This task calls set_n_termination() in par_non_clean_card_iterate_work()
4695     // in the young space (_par_seq_tasks) in the G1 heap
4696     // for SequentialSubTasksDone.
4697     // This task also uses SubTasksDone in SharedHeap and G1CollectedHeap
4698     // both of which need setting by set_n_termination().
4699     _g1h->SharedHeap::set_n_termination(active_workers);
4700     _g1h->set_n_termination(active_workers);
4701     terminator()->reset_for_reuse(active_workers);
4702     _n_workers = active_workers;
4703   }
4704 
4705   // Helps out with CLD processing.
4706   //
4707   // During InitialMark we need to:
4708   // 1) Scavenge all CLDs for the young GC.
4709   // 2) Mark all objects directly reachable from strong CLDs.
4710   template <G1Mark do_mark_object>
4711   class G1CLDClosure : public CLDClosure {
4712     G1ParCopyClosure<G1BarrierNone,  do_mark_object>* _oop_closure;
4713     G1ParCopyClosure<G1BarrierKlass, do_mark_object>  _oop_in_klass_closure;
4714     G1KlassScanClosure                                _klass_in_cld_closure;
4715     bool                                              _claim;
4716 
4717    public:
4718     G1CLDClosure(G1ParCopyClosure<G1BarrierNone, do_mark_object>* oop_closure,
4719                  bool only_young, bool claim)
4720         : _oop_closure(oop_closure),
4721           _oop_in_klass_closure(oop_closure->g1(),
4722                                 oop_closure->pss(),
4723                                 oop_closure->rp()),
4724           _klass_in_cld_closure(&_oop_in_klass_closure, only_young),
4725           _claim(claim) {
4726 
4727     }
4728 
4729     void do_cld(ClassLoaderData* cld) {
4730       cld->oops_do(_oop_closure, &_klass_in_cld_closure, _claim);
4731     }
4732   };
4733 
4734   class G1CodeBlobClosure: public CodeBlobClosure {
4735     OopClosure* _f;
4736 
4737    public:
4738     G1CodeBlobClosure(OopClosure* f) : _f(f) {}
4739     void do_code_blob(CodeBlob* blob) {
4740       nmethod* that = blob->as_nmethod_or_null();
4741       if (that != NULL) {
4742         if (!that->test_set_oops_do_mark()) {
4743           that->oops_do(_f);
4744           that->fix_oop_relocations();
4745         }
4746       }
4747     }
4748   };
4749 
4750   void work(uint worker_id) {
4751     if (worker_id >= _n_workers) return;  // no work needed this round
4752 
4753     double start_time_ms = os::elapsedTime() * 1000.0;
4754     _g1h->g1_policy()->phase_times()->record_gc_worker_start_time(worker_id, start_time_ms);
4755 
4756     {
4757       ResourceMark rm;
4758       HandleMark   hm;
4759 
4760       ReferenceProcessor*             rp = _g1h->ref_processor_stw();
4761 
4762       G1ParScanThreadState            pss(_g1h, worker_id, rp);
4763       G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, rp);
4764 
4765       pss.set_evac_failure_closure(&evac_failure_cl);
4766 
4767       bool only_young = _g1h->g1_policy()->gcs_are_young();
4768 
4769       // Non-IM young GC.
4770       G1ParCopyClosure<G1BarrierNone, G1MarkNone>             scan_only_root_cl(_g1h, &pss, rp);
4771       G1CLDClosure<G1MarkNone>                                scan_only_cld_cl(&scan_only_root_cl,
4772                                                                                only_young, // Only process dirty klasses.
4773                                                                                false);     // No need to claim CLDs.
4774       // IM young GC.
4775       //    Strong roots closures.
4776       G1ParCopyClosure<G1BarrierNone, G1MarkFromRoot>         scan_mark_root_cl(_g1h, &pss, rp);
4777       G1CLDClosure<G1MarkFromRoot>                            scan_mark_cld_cl(&scan_mark_root_cl,
4778                                                                                false, // Process all klasses.
4779                                                                                true); // Need to claim CLDs.
4780       //    Weak roots closures.
4781       G1ParCopyClosure<G1BarrierNone, G1MarkPromotedFromRoot> scan_mark_weak_root_cl(_g1h, &pss, rp);
4782       G1CLDClosure<G1MarkPromotedFromRoot>                    scan_mark_weak_cld_cl(&scan_mark_weak_root_cl,
4783                                                                                     false, // Process all klasses.
4784                                                                                     true); // Need to claim CLDs.
4785 
4786       G1CodeBlobClosure scan_only_code_cl(&scan_only_root_cl);
4787       G1CodeBlobClosure scan_mark_code_cl(&scan_mark_root_cl);
4788       // IM Weak code roots are handled later.
4789 
4790       OopClosure* strong_root_cl;
4791       OopClosure* weak_root_cl;
4792       CLDClosure* strong_cld_cl;
4793       CLDClosure* weak_cld_cl;
4794       CodeBlobClosure* strong_code_cl;
4795 
4796       if (_g1h->g1_policy()->during_initial_mark_pause()) {
4797         // We also need to mark copied objects.
4798         strong_root_cl = &scan_mark_root_cl;
4799         strong_cld_cl  = &scan_mark_cld_cl;
4800         strong_code_cl = &scan_mark_code_cl;
4801         if (ClassUnloadingWithConcurrentMark) {
4802           weak_root_cl = &scan_mark_weak_root_cl;
4803           weak_cld_cl  = &scan_mark_weak_cld_cl;
4804         } else {
4805           weak_root_cl = &scan_mark_root_cl;
4806           weak_cld_cl  = &scan_mark_cld_cl;
4807         }
4808       } else {
4809         strong_root_cl = &scan_only_root_cl;
4810         weak_root_cl   = &scan_only_root_cl;
4811         strong_cld_cl  = &scan_only_cld_cl;
4812         weak_cld_cl    = &scan_only_cld_cl;
4813         strong_code_cl = &scan_only_code_cl;
4814       }
4815 
4816 
4817       G1ParPushHeapRSClosure  push_heap_rs_cl(_g1h, &pss);
4818 
4819       pss.start_strong_roots();
4820       _g1h->g1_process_roots(strong_root_cl,
4821                              weak_root_cl,
4822                              &push_heap_rs_cl,
4823                              strong_cld_cl,
4824                              weak_cld_cl,
4825                              strong_code_cl,
4826                              worker_id);
4827 
4828       pss.end_strong_roots();
4829 
4830       {
4831         double start = os::elapsedTime();
4832         G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
4833         evac.do_void();
4834         double elapsed_ms = (os::elapsedTime()-start)*1000.0;
4835         double term_ms = pss.term_time()*1000.0;
4836         _g1h->g1_policy()->phase_times()->add_obj_copy_time(worker_id, elapsed_ms-term_ms);
4837         _g1h->g1_policy()->phase_times()->record_termination(worker_id, term_ms, pss.term_attempts());
4838       }
4839       _g1h->g1_policy()->record_thread_age_table(pss.age_table());
4840       _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
4841 
4842       if (ParallelGCVerbose) {
4843         MutexLocker x(stats_lock());
4844         pss.print_termination_stats(worker_id);
4845       }
4846 
4847       assert(pss.queue_is_empty(), "should be empty");
4848 
4849       // Close the inner scope so that the ResourceMark and HandleMark
4850       // destructors are executed here and are included as part of the
4851       // "GC Worker Time".
4852     }
4853 
4854     double end_time_ms = os::elapsedTime() * 1000.0;
4855     _g1h->g1_policy()->phase_times()->record_gc_worker_end_time(worker_id, end_time_ms);
4856   }
4857 };
4858 
4859 // *** Common G1 Evacuation Stuff
4860 
4861 // This method is run in a GC worker.
4862 
4863 void
4864 G1CollectedHeap::
4865 g1_process_roots(OopClosure* scan_non_heap_roots,
4866                  OopClosure* scan_non_heap_weak_roots,
4867                  OopsInHeapRegionClosure* scan_rs,
4868                  CLDClosure* scan_strong_clds,
4869                  CLDClosure* scan_weak_clds,
4870                  CodeBlobClosure* scan_strong_code,
4871                  uint worker_i) {
4872 
4873   // First scan the shared roots.
4874   double ext_roots_start = os::elapsedTime();
4875   double closure_app_time_sec = 0.0;
4876 
4877   bool during_im = _g1h->g1_policy()->during_initial_mark_pause();
4878   bool trace_metadata = during_im && ClassUnloadingWithConcurrentMark;
4879 
4880   BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
4881   BufferingOopClosure buf_scan_non_heap_weak_roots(scan_non_heap_weak_roots);
4882 
4883   process_roots(false, // no scoping; this is parallel code
4884                 SharedHeap::SO_None,
4885                 &buf_scan_non_heap_roots,
4886                 &buf_scan_non_heap_weak_roots,
4887                 scan_strong_clds,
4888                 // Unloading Initial Marks handle the weak CLDs separately.
4889                 (trace_metadata ? NULL : scan_weak_clds),
4890                 scan_strong_code);
4891 
4892   // Now the CM ref_processor roots.
4893   if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
4894     // We need to treat the discovered reference lists of the
4895     // concurrent mark ref processor as roots and keep entries
4896     // (which are added by the marking threads) on them live
4897     // until they can be processed at the end of marking.
4898     ref_processor_cm()->weak_oops_do(&buf_scan_non_heap_roots);
4899   }
4900 
4901   if (trace_metadata) {
4902     // Barrier to make sure all workers passed
4903     // the strong CLD and strong nmethods phases.
4904     active_strong_roots_scope()->wait_until_all_workers_done_with_threads(n_par_threads());
4905 
4906     // Now take the complement of the strong CLDs.
4907     ClassLoaderDataGraph::roots_cld_do(NULL, scan_weak_clds);
4908   }
4909 
4910   // Finish up any enqueued closure apps (attributed as object copy time).
4911   buf_scan_non_heap_roots.done();
4912   buf_scan_non_heap_weak_roots.done();
4913 
4914   double obj_copy_time_sec = buf_scan_non_heap_roots.closure_app_seconds()
4915       + buf_scan_non_heap_weak_roots.closure_app_seconds();
4916 
4917   g1_policy()->phase_times()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
4918 
4919   double ext_root_time_ms =
4920     ((os::elapsedTime() - ext_roots_start) - obj_copy_time_sec) * 1000.0;
4921 
4922   g1_policy()->phase_times()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
4923 
4924   // During conc marking we have to filter the per-thread SATB buffers
4925   // to make sure we remove any oops into the CSet (which will show up
4926   // as implicitly live).
4927   double satb_filtering_ms = 0.0;
4928   if (!_process_strong_tasks->is_task_claimed(G1H_PS_filter_satb_buffers)) {
4929     if (mark_in_progress()) {
4930       double satb_filter_start = os::elapsedTime();
4931 
4932       JavaThread::satb_mark_queue_set().filter_thread_buffers();
4933 
4934       satb_filtering_ms = (os::elapsedTime() - satb_filter_start) * 1000.0;
4935     }
4936   }
4937   g1_policy()->phase_times()->record_satb_filtering_time(worker_i, satb_filtering_ms);
4938 
4939   // Now scan the complement of the collection set.
4940   MarkingCodeBlobClosure scavenge_cs_nmethods(scan_non_heap_weak_roots, CodeBlobToOopClosure::FixRelocations);
4941 
4942   g1_rem_set()->oops_into_collection_set_do(scan_rs, &scavenge_cs_nmethods, worker_i);
4943 
4944   _process_strong_tasks->all_tasks_completed();
4945 }
4946 
4947 class G1StringSymbolTableUnlinkTask : public AbstractGangTask {
4948 private:
4949   BoolObjectClosure* _is_alive;
4950   int _initial_string_table_size;
4951   int _initial_symbol_table_size;
4952 
4953   bool  _process_strings;
4954   int _strings_processed;
4955   int _strings_removed;
4956 
4957   bool  _process_symbols;
4958   int _symbols_processed;
4959   int _symbols_removed;
4960 
4961   bool _do_in_parallel;
4962 public:
4963   G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :
4964     AbstractGangTask("String/Symbol Unlinking"),
4965     _is_alive(is_alive),
4966     _do_in_parallel(G1CollectedHeap::use_parallel_gc_threads()),
4967     _process_strings(process_strings), _strings_processed(0), _strings_removed(0),
4968     _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {
4969 
4970     _initial_string_table_size = StringTable::the_table()->table_size();
4971     _initial_symbol_table_size = SymbolTable::the_table()->table_size();
4972     if (process_strings) {
4973       StringTable::clear_parallel_claimed_index();
4974     }
4975     if (process_symbols) {
4976       SymbolTable::clear_parallel_claimed_index();
4977     }
4978   }
4979 
4980   ~G1StringSymbolTableUnlinkTask() {
4981     guarantee(!_process_strings || !_do_in_parallel || StringTable::parallel_claimed_index() >= _initial_string_table_size,
4982               err_msg("claim value %d after unlink less than initial string table size %d",
4983                       StringTable::parallel_claimed_index(), _initial_string_table_size));
4984     guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
4985               err_msg("claim value %d after unlink less than initial symbol table size %d",
4986                       SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
4987 
4988     if (G1TraceStringSymbolTableScrubbing) {
4989       gclog_or_tty->print_cr("Cleaned string and symbol table, "
4990                              "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
4991                              "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
4992                              strings_processed(), strings_removed(),
4993                              symbols_processed(), symbols_removed());
4994     }
4995   }
4996 
4997   void work(uint worker_id) {
4998     if (_do_in_parallel) {
4999       int strings_processed = 0;
5000       int strings_removed = 0;
5001       int symbols_processed = 0;
5002       int symbols_removed = 0;
5003       if (_process_strings) {
5004         StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed);
5005         Atomic::add(strings_processed, &_strings_processed);
5006         Atomic::add(strings_removed, &_strings_removed);
5007       }
5008       if (_process_symbols) {
5009         SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed);
5010         Atomic::add(symbols_processed, &_symbols_processed);
5011         Atomic::add(symbols_removed, &_symbols_removed);
5012       }
5013     } else {
5014       if (_process_strings) {
5015         StringTable::unlink(_is_alive, &_strings_processed, &_strings_removed);
5016       }
5017       if (_process_symbols) {
5018         SymbolTable::unlink(&_symbols_processed, &_symbols_removed);
5019       }
5020     }
5021   }
5022 
5023   size_t strings_processed() const { return (size_t)_strings_processed; }
5024   size_t strings_removed()   const { return (size_t)_strings_removed; }
5025 
5026   size_t symbols_processed() const { return (size_t)_symbols_processed; }
5027   size_t symbols_removed()   const { return (size_t)_symbols_removed; }
5028 };
5029 
5030 class G1CodeCacheUnloadingTask VALUE_OBJ_CLASS_SPEC {
5031 private:
5032   static Monitor* _lock;
5033 
5034   BoolObjectClosure* const _is_alive;
5035   const bool               _unloading_occurred;
5036   const uint               _num_workers;
5037 
5038   // Variables used to claim nmethods.
5039   nmethod* _first_nmethod;
5040   volatile nmethod* _claimed_nmethod;
5041 
5042   // The list of nmethods that need to be processed by the second pass.
5043   volatile nmethod* _postponed_list;
5044   volatile uint     _num_entered_barrier;
5045 
5046  public:
5047   G1CodeCacheUnloadingTask(uint num_workers, BoolObjectClosure* is_alive, bool unloading_occurred) :
5048       _is_alive(is_alive),
5049       _unloading_occurred(unloading_occurred),
5050       _num_workers(num_workers),
5051       _first_nmethod(NULL),
5052       _claimed_nmethod(NULL),
5053       _postponed_list(NULL),
5054       _num_entered_barrier(0)
5055   {
5056     nmethod::increase_unloading_clock();
5057     _first_nmethod = CodeCache::alive_nmethod(CodeCache::first());
5058     _claimed_nmethod = (volatile nmethod*)_first_nmethod;
5059   }
5060 
5061   ~G1CodeCacheUnloadingTask() {
5062     CodeCache::verify_clean_inline_caches();
5063 
5064     CodeCache::set_needs_cache_clean(false);
5065     guarantee(CodeCache::scavenge_root_nmethods() == NULL, "Must be");
5066 
5067     CodeCache::verify_icholder_relocations();
5068   }
5069 
5070  private:
5071   void add_to_postponed_list(nmethod* nm) {
5072       nmethod* old;
5073       do {
5074         old = (nmethod*)_postponed_list;
5075         nm->set_unloading_next(old);
5076       } while ((nmethod*)Atomic::cmpxchg_ptr(nm, &_postponed_list, old) != old);
5077   }
5078 
5079   void clean_nmethod(nmethod* nm) {
5080     bool postponed = nm->do_unloading_parallel(_is_alive, _unloading_occurred);
5081 
5082     if (postponed) {
5083       // This nmethod referred to an nmethod that has not been cleaned/unloaded yet.
5084       add_to_postponed_list(nm);
5085     }
5086 
5087     // Mark that this thread has been cleaned/unloaded.
5088     // After this call, it will be safe to ask if this nmethod was unloaded or not.
5089     nm->set_unloading_clock(nmethod::global_unloading_clock());
5090   }
5091 
5092   void clean_nmethod_postponed(nmethod* nm) {
5093     nm->do_unloading_parallel_postponed(_is_alive, _unloading_occurred);
5094   }
5095 
5096   static const int MaxClaimNmethods = 16;
5097 
5098   void claim_nmethods(nmethod** claimed_nmethods, int *num_claimed_nmethods) {
5099     nmethod* first;
5100     nmethod* last;
5101 
5102     do {
5103       *num_claimed_nmethods = 0;
5104 
5105       first = last = (nmethod*)_claimed_nmethod;
5106 
5107       if (first != NULL) {
5108         for (int i = 0; i < MaxClaimNmethods; i++) {
5109           last = CodeCache::alive_nmethod(CodeCache::next(last));
5110 
5111           if (last == NULL) {
5112             break;
5113           }
5114 
5115           claimed_nmethods[i] = last;
5116           (*num_claimed_nmethods)++;
5117         }
5118       }
5119 
5120     } while ((nmethod*)Atomic::cmpxchg_ptr(last, &_claimed_nmethod, first) != first);
5121   }
5122 
5123   nmethod* claim_postponed_nmethod() {
5124     nmethod* claim;
5125     nmethod* next;
5126 
5127     do {
5128       claim = (nmethod*)_postponed_list;
5129       if (claim == NULL) {
5130         return NULL;
5131       }
5132 
5133       next = claim->unloading_next();
5134 
5135     } while ((nmethod*)Atomic::cmpxchg_ptr(next, &_postponed_list, claim) != claim);
5136 
5137     return claim;
5138   }
5139 
5140  public:
5141   // Mark that we're done with the first pass of nmethod cleaning.
5142   void barrier_mark(uint worker_id) {
5143     MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
5144     _num_entered_barrier++;
5145     if (_num_entered_barrier == _num_workers) {
5146       ml.notify_all();
5147     }
5148   }
5149 
5150   // See if we have to wait for the other workers to
5151   // finish their first-pass nmethod cleaning work.
5152   void barrier_wait(uint worker_id) {
5153     if (_num_entered_barrier < _num_workers) {
5154       MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
5155       while (_num_entered_barrier < _num_workers) {
5156           ml.wait(Mutex::_no_safepoint_check_flag, 0, false);
5157       }
5158     }
5159   }
5160 
5161   // Cleaning and unloading of nmethods. Some work has to be postponed
5162   // to the second pass, when we know which nmethods survive.
5163   void work_first_pass(uint worker_id) {
5164     // The first nmethods is claimed by the first worker.
5165     if (worker_id == 0 && _first_nmethod != NULL) {
5166       clean_nmethod(_first_nmethod);
5167       _first_nmethod = NULL;
5168     }
5169 
5170     int num_claimed_nmethods;
5171     nmethod* claimed_nmethods[MaxClaimNmethods];
5172 
5173     while (true) {
5174       claim_nmethods(claimed_nmethods, &num_claimed_nmethods);
5175 
5176       if (num_claimed_nmethods == 0) {
5177         break;
5178       }
5179 
5180       for (int i = 0; i < num_claimed_nmethods; i++) {
5181         clean_nmethod(claimed_nmethods[i]);
5182       }
5183     }
5184   }
5185 
5186   void work_second_pass(uint worker_id) {
5187     nmethod* nm;
5188     // Take care of postponed nmethods.
5189     while ((nm = claim_postponed_nmethod()) != NULL) {
5190       clean_nmethod_postponed(nm);
5191     }
5192   }
5193 };
5194 
5195 Monitor* G1CodeCacheUnloadingTask::_lock = new Monitor(Mutex::leaf, "Code Cache Unload lock");
5196 
5197 class G1KlassCleaningTask : public StackObj {
5198   BoolObjectClosure*                      _is_alive;
5199   volatile jint                           _clean_klass_tree_claimed;
5200   ClassLoaderDataGraphKlassIteratorAtomic _klass_iterator;
5201 
5202  public:
5203   G1KlassCleaningTask(BoolObjectClosure* is_alive) :
5204       _is_alive(is_alive),
5205       _clean_klass_tree_claimed(0),
5206       _klass_iterator() {
5207   }
5208 
5209  private:
5210   bool claim_clean_klass_tree_task() {
5211     if (_clean_klass_tree_claimed) {
5212       return false;
5213     }
5214 
5215     return Atomic::cmpxchg(1, (jint*)&_clean_klass_tree_claimed, 0) == 0;
5216   }
5217 
5218   InstanceKlass* claim_next_klass() {
5219     Klass* klass;
5220     do {
5221       klass =_klass_iterator.next_klass();
5222     } while (klass != NULL && !klass->oop_is_instance());
5223 
5224     return (InstanceKlass*)klass;
5225   }
5226 
5227 public:
5228 
5229   void clean_klass(InstanceKlass* ik) {
5230     ik->clean_implementors_list(_is_alive);
5231     ik->clean_method_data(_is_alive);
5232 
5233     // G1 specific cleanup work that has
5234     // been moved here to be done in parallel.
5235     ik->clean_dependent_nmethods();
5236   }
5237 
5238   void work() {
5239     ResourceMark rm;
5240 
5241     // One worker will clean the subklass/sibling klass tree.
5242     if (claim_clean_klass_tree_task()) {
5243       Klass::clean_subklass_tree(_is_alive);
5244     }
5245 
5246     // All workers will help cleaning the classes,
5247     InstanceKlass* klass;
5248     while ((klass = claim_next_klass()) != NULL) {
5249       clean_klass(klass);
5250     }
5251   }
5252 };
5253 
5254 // To minimize the remark pause times, the tasks below are done in parallel.
5255 class G1ParallelCleaningTask : public AbstractGangTask {
5256 private:
5257   G1StringSymbolTableUnlinkTask _string_symbol_task;
5258   G1CodeCacheUnloadingTask      _code_cache_task;
5259   G1KlassCleaningTask           _klass_cleaning_task;
5260 
5261 public:
5262   // The constructor is run in the VMThread.
5263   G1ParallelCleaningTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, uint num_workers, bool unloading_occurred) :
5264       AbstractGangTask("Parallel Cleaning"),
5265       _string_symbol_task(is_alive, process_strings, process_symbols),
5266       _code_cache_task(num_workers, is_alive, unloading_occurred),
5267       _klass_cleaning_task(is_alive) {
5268   }
5269 
5270   // The parallel work done by all worker threads.
5271   void work(uint worker_id) {
5272     // Do first pass of code cache cleaning.
5273     _code_cache_task.work_first_pass(worker_id);
5274 
5275     // Let the threads mark that the first pass is done.
5276     _code_cache_task.barrier_mark(worker_id);
5277 
5278     // Clean the Strings and Symbols.
5279     _string_symbol_task.work(worker_id);
5280 
5281     // Wait for all workers to finish the first code cache cleaning pass.
5282     _code_cache_task.barrier_wait(worker_id);
5283 
5284     // Do the second code cache cleaning work, which realize on
5285     // the liveness information gathered during the first pass.
5286     _code_cache_task.work_second_pass(worker_id);
5287 
5288     // Clean all klasses that were not unloaded.
5289     _klass_cleaning_task.work();
5290   }
5291 };
5292 
5293 
5294 void G1CollectedHeap::parallel_cleaning(BoolObjectClosure* is_alive,
5295                                         bool process_strings,
5296                                         bool process_symbols,
5297                                         bool class_unloading_occurred) {
5298   uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5299                     workers()->active_workers() : 1);
5300 
5301   G1ParallelCleaningTask g1_unlink_task(is_alive, process_strings, process_symbols,
5302                                         n_workers, class_unloading_occurred);
5303   if (G1CollectedHeap::use_parallel_gc_threads()) {
5304     set_par_threads(n_workers);
5305     workers()->run_task(&g1_unlink_task);
5306     set_par_threads(0);
5307   } else {
5308     g1_unlink_task.work(0);
5309   }
5310 }
5311 
5312 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
5313                                                      bool process_strings, bool process_symbols) {
5314   {
5315     uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5316                      _g1h->workers()->active_workers() : 1);
5317     G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
5318     if (G1CollectedHeap::use_parallel_gc_threads()) {
5319       set_par_threads(n_workers);
5320       workers()->run_task(&g1_unlink_task);
5321       set_par_threads(0);
5322     } else {
5323       g1_unlink_task.work(0);
5324     }
5325   }
5326 
5327   if (G1StringDedup::is_enabled()) {
5328     G1StringDedup::unlink(is_alive);
5329   }
5330 }
5331 
5332 class G1RedirtyLoggedCardsTask : public AbstractGangTask {
5333  private:
5334   DirtyCardQueueSet* _queue;
5335  public:
5336   G1RedirtyLoggedCardsTask(DirtyCardQueueSet* queue) : AbstractGangTask("Redirty Cards"), _queue(queue) { }
5337 
5338   virtual void work(uint worker_id) {
5339     double start_time = os::elapsedTime();
5340 
5341     RedirtyLoggedCardTableEntryClosure cl;
5342     if (G1CollectedHeap::heap()->use_parallel_gc_threads()) {
5343       _queue->par_apply_closure_to_all_completed_buffers(&cl);
5344     } else {
5345       _queue->apply_closure_to_all_completed_buffers(&cl);
5346     }
5347 
5348     G1GCPhaseTimes* timer = G1CollectedHeap::heap()->g1_policy()->phase_times();
5349     timer->record_redirty_logged_cards_time_ms(worker_id, (os::elapsedTime() - start_time) * 1000.0);
5350     timer->record_redirty_logged_cards_processed_cards(worker_id, cl.num_processed());
5351   }
5352 };
5353 
5354 void G1CollectedHeap::redirty_logged_cards() {
5355   guarantee(G1DeferredRSUpdate, "Must only be called when using deferred RS updates.");
5356   double redirty_logged_cards_start = os::elapsedTime();
5357 
5358   uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5359                    _g1h->workers()->active_workers() : 1);
5360 
5361   G1RedirtyLoggedCardsTask redirty_task(&dirty_card_queue_set());
5362   dirty_card_queue_set().reset_for_par_iteration();
5363   if (use_parallel_gc_threads()) {
5364     set_par_threads(n_workers);
5365     workers()->run_task(&redirty_task);
5366     set_par_threads(0);
5367   } else {
5368     redirty_task.work(0);
5369   }
5370 
5371   DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
5372   dcq.merge_bufferlists(&dirty_card_queue_set());
5373   assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
5374 
5375   g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0);
5376 }
5377 
5378 // Weak Reference Processing support
5379 
5380 // An always "is_alive" closure that is used to preserve referents.
5381 // If the object is non-null then it's alive.  Used in the preservation
5382 // of referent objects that are pointed to by reference objects
5383 // discovered by the CM ref processor.
5384 class G1AlwaysAliveClosure: public BoolObjectClosure {
5385   G1CollectedHeap* _g1;
5386 public:
5387   G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5388   bool do_object_b(oop p) {
5389     if (p != NULL) {
5390       return true;
5391     }
5392     return false;
5393   }
5394 };
5395 
5396 bool G1STWIsAliveClosure::do_object_b(oop p) {
5397   // An object is reachable if it is outside the collection set,
5398   // or is inside and copied.
5399   return !_g1->obj_in_cs(p) || p->is_forwarded();
5400 }
5401 
5402 // Non Copying Keep Alive closure
5403 class G1KeepAliveClosure: public OopClosure {
5404   G1CollectedHeap* _g1;
5405 public:
5406   G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5407   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
5408   void do_oop(oop* p) {
5409     oop obj = *p;
5410 
5411     G1CollectedHeap::in_cset_state_t cset_state = _g1->in_cset_state(obj);
5412     if (obj == NULL || cset_state == G1CollectedHeap::InNeither) {
5413       return;
5414     }
5415     if (cset_state == G1CollectedHeap::InCSet) {
5416       assert( obj->is_forwarded(), "invariant" );
5417       *p = obj->forwardee();
5418     } else {
5419       assert(!obj->is_forwarded(), "invariant" );
5420       assert(cset_state == G1CollectedHeap::IsHumongous,
5421              err_msg("Only allowed InCSet state is IsHumongous, but is %d", cset_state));
5422       _g1->set_humongous_is_live(obj);
5423     }
5424   }
5425 };
5426 
5427 // Copying Keep Alive closure - can be called from both
5428 // serial and parallel code as long as different worker
5429 // threads utilize different G1ParScanThreadState instances
5430 // and different queues.
5431 
5432 class G1CopyingKeepAliveClosure: public OopClosure {
5433   G1CollectedHeap*         _g1h;
5434   OopClosure*              _copy_non_heap_obj_cl;
5435   G1ParScanThreadState*    _par_scan_state;
5436 
5437 public:
5438   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
5439                             OopClosure* non_heap_obj_cl,
5440                             G1ParScanThreadState* pss):
5441     _g1h(g1h),
5442     _copy_non_heap_obj_cl(non_heap_obj_cl),
5443     _par_scan_state(pss)
5444   {}
5445 
5446   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
5447   virtual void do_oop(      oop* p) { do_oop_work(p); }
5448 
5449   template <class T> void do_oop_work(T* p) {
5450     oop obj = oopDesc::load_decode_heap_oop(p);
5451 
5452     if (_g1h->is_in_cset_or_humongous(obj)) {
5453       // If the referent object has been forwarded (either copied
5454       // to a new location or to itself in the event of an
5455       // evacuation failure) then we need to update the reference
5456       // field and, if both reference and referent are in the G1
5457       // heap, update the RSet for the referent.
5458       //
5459       // If the referent has not been forwarded then we have to keep
5460       // it alive by policy. Therefore we have copy the referent.
5461       //
5462       // If the reference field is in the G1 heap then we can push
5463       // on the PSS queue. When the queue is drained (after each
5464       // phase of reference processing) the object and it's followers
5465       // will be copied, the reference field set to point to the
5466       // new location, and the RSet updated. Otherwise we need to
5467       // use the the non-heap or metadata closures directly to copy
5468       // the referent object and update the pointer, while avoiding
5469       // updating the RSet.
5470 
5471       if (_g1h->is_in_g1_reserved(p)) {
5472         _par_scan_state->push_on_queue(p);
5473       } else {
5474         assert(!Metaspace::contains((const void*)p),
5475                err_msg("Unexpectedly found a pointer from metadata: "
5476                               PTR_FORMAT, p));
5477         _copy_non_heap_obj_cl->do_oop(p);
5478       }
5479     }
5480   }
5481 };
5482 
5483 // Serial drain queue closure. Called as the 'complete_gc'
5484 // closure for each discovered list in some of the
5485 // reference processing phases.
5486 
5487 class G1STWDrainQueueClosure: public VoidClosure {
5488 protected:
5489   G1CollectedHeap* _g1h;
5490   G1ParScanThreadState* _par_scan_state;
5491 
5492   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
5493 
5494 public:
5495   G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
5496     _g1h(g1h),
5497     _par_scan_state(pss)
5498   { }
5499 
5500   void do_void() {
5501     G1ParScanThreadState* const pss = par_scan_state();
5502     pss->trim_queue();
5503   }
5504 };
5505 
5506 // Parallel Reference Processing closures
5507 
5508 // Implementation of AbstractRefProcTaskExecutor for parallel reference
5509 // processing during G1 evacuation pauses.
5510 
5511 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
5512 private:
5513   G1CollectedHeap*   _g1h;
5514   RefToScanQueueSet* _queues;
5515   FlexibleWorkGang*  _workers;
5516   int                _active_workers;
5517 
5518 public:
5519   G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
5520                         FlexibleWorkGang* workers,
5521                         RefToScanQueueSet *task_queues,
5522                         int n_workers) :
5523     _g1h(g1h),
5524     _queues(task_queues),
5525     _workers(workers),
5526     _active_workers(n_workers)
5527   {
5528     assert(n_workers > 0, "shouldn't call this otherwise");
5529   }
5530 
5531   // Executes the given task using concurrent marking worker threads.
5532   virtual void execute(ProcessTask& task);
5533   virtual void execute(EnqueueTask& task);
5534 };
5535 
5536 // Gang task for possibly parallel reference processing
5537 
5538 class G1STWRefProcTaskProxy: public AbstractGangTask {
5539   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
5540   ProcessTask&     _proc_task;
5541   G1CollectedHeap* _g1h;
5542   RefToScanQueueSet *_task_queues;
5543   ParallelTaskTerminator* _terminator;
5544 
5545 public:
5546   G1STWRefProcTaskProxy(ProcessTask& proc_task,
5547                      G1CollectedHeap* g1h,
5548                      RefToScanQueueSet *task_queues,
5549                      ParallelTaskTerminator* terminator) :
5550     AbstractGangTask("Process reference objects in parallel"),
5551     _proc_task(proc_task),
5552     _g1h(g1h),
5553     _task_queues(task_queues),
5554     _terminator(terminator)
5555   {}
5556 
5557   virtual void work(uint worker_id) {
5558     // The reference processing task executed by a single worker.
5559     ResourceMark rm;
5560     HandleMark   hm;
5561 
5562     G1STWIsAliveClosure is_alive(_g1h);
5563 
5564     G1ParScanThreadState            pss(_g1h, worker_id, NULL);
5565     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5566 
5567     pss.set_evac_failure_closure(&evac_failure_cl);
5568 
5569     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
5570 
5571     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5572 
5573     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5574 
5575     if (_g1h->g1_policy()->during_initial_mark_pause()) {
5576       // We also need to mark copied objects.
5577       copy_non_heap_cl = &copy_mark_non_heap_cl;
5578     }
5579 
5580     // Keep alive closure.
5581     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
5582 
5583     // Complete GC closure
5584     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);
5585 
5586     // Call the reference processing task's work routine.
5587     _proc_task.work(worker_id, is_alive, keep_alive, drain_queue);
5588 
5589     // Note we cannot assert that the refs array is empty here as not all
5590     // of the processing tasks (specifically phase2 - pp2_work) execute
5591     // the complete_gc closure (which ordinarily would drain the queue) so
5592     // the queue may not be empty.
5593   }
5594 };
5595 
5596 // Driver routine for parallel reference processing.
5597 // Creates an instance of the ref processing gang
5598 // task and has the worker threads execute it.
5599 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {
5600   assert(_workers != NULL, "Need parallel worker threads.");
5601 
5602   ParallelTaskTerminator terminator(_active_workers, _queues);
5603   G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator);
5604 
5605   _g1h->set_par_threads(_active_workers);
5606   _workers->run_task(&proc_task_proxy);
5607   _g1h->set_par_threads(0);
5608 }
5609 
5610 // Gang task for parallel reference enqueueing.
5611 
5612 class G1STWRefEnqueueTaskProxy: public AbstractGangTask {
5613   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
5614   EnqueueTask& _enq_task;
5615 
5616 public:
5617   G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) :
5618     AbstractGangTask("Enqueue reference objects in parallel"),
5619     _enq_task(enq_task)
5620   { }
5621 
5622   virtual void work(uint worker_id) {
5623     _enq_task.work(worker_id);
5624   }
5625 };
5626 
5627 // Driver routine for parallel reference enqueueing.
5628 // Creates an instance of the ref enqueueing gang
5629 // task and has the worker threads execute it.
5630 
5631 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
5632   assert(_workers != NULL, "Need parallel worker threads.");
5633 
5634   G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task);
5635 
5636   _g1h->set_par_threads(_active_workers);
5637   _workers->run_task(&enq_task_proxy);
5638   _g1h->set_par_threads(0);
5639 }
5640 
5641 // End of weak reference support closures
5642 
5643 // Abstract task used to preserve (i.e. copy) any referent objects
5644 // that are in the collection set and are pointed to by reference
5645 // objects discovered by the CM ref processor.
5646 
5647 class G1ParPreserveCMReferentsTask: public AbstractGangTask {
5648 protected:
5649   G1CollectedHeap* _g1h;
5650   RefToScanQueueSet      *_queues;
5651   ParallelTaskTerminator _terminator;
5652   uint _n_workers;
5653 
5654 public:
5655   G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h,int workers, RefToScanQueueSet *task_queues) :
5656     AbstractGangTask("ParPreserveCMReferents"),
5657     _g1h(g1h),
5658     _queues(task_queues),
5659     _terminator(workers, _queues),
5660     _n_workers(workers)
5661   { }
5662 
5663   void work(uint worker_id) {
5664     ResourceMark rm;
5665     HandleMark   hm;
5666 
5667     G1ParScanThreadState            pss(_g1h, worker_id, NULL);
5668     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5669 
5670     pss.set_evac_failure_closure(&evac_failure_cl);
5671 
5672     assert(pss.queue_is_empty(), "both queue and overflow should be empty");
5673 
5674     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
5675 
5676     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5677 
5678     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5679 
5680     if (_g1h->g1_policy()->during_initial_mark_pause()) {
5681       // We also need to mark copied objects.
5682       copy_non_heap_cl = &copy_mark_non_heap_cl;
5683     }
5684 
5685     // Is alive closure
5686     G1AlwaysAliveClosure always_alive(_g1h);
5687 
5688     // Copying keep alive closure. Applied to referent objects that need
5689     // to be copied.
5690     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
5691 
5692     ReferenceProcessor* rp = _g1h->ref_processor_cm();
5693 
5694     uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q();
5695     uint stride = MIN2(MAX2(_n_workers, 1U), limit);
5696 
5697     // limit is set using max_num_q() - which was set using ParallelGCThreads.
5698     // So this must be true - but assert just in case someone decides to
5699     // change the worker ids.
5700     assert(0 <= worker_id && worker_id < limit, "sanity");
5701     assert(!rp->discovery_is_atomic(), "check this code");
5702 
5703     // Select discovered lists [i, i+stride, i+2*stride,...,limit)
5704     for (uint idx = worker_id; idx < limit; idx += stride) {
5705       DiscoveredList& ref_list = rp->discovered_refs()[idx];
5706 
5707       DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive);
5708       while (iter.has_next()) {
5709         // Since discovery is not atomic for the CM ref processor, we
5710         // can see some null referent objects.
5711         iter.load_ptrs(DEBUG_ONLY(true));
5712         oop ref = iter.obj();
5713 
5714         // This will filter nulls.
5715         if (iter.is_referent_alive()) {
5716           iter.make_referent_alive();
5717         }
5718         iter.move_to_next();
5719       }
5720     }
5721 
5722     // Drain the queue - which may cause stealing
5723     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);
5724     drain_queue.do_void();
5725     // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure
5726     assert(pss.queue_is_empty(), "should be");
5727   }
5728 };
5729 
5730 // Weak Reference processing during an evacuation pause (part 1).
5731 void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
5732   double ref_proc_start = os::elapsedTime();
5733 
5734   ReferenceProcessor* rp = _ref_processor_stw;
5735   assert(rp->discovery_enabled(), "should have been enabled");
5736 
5737   // Any reference objects, in the collection set, that were 'discovered'
5738   // by the CM ref processor should have already been copied (either by
5739   // applying the external root copy closure to the discovered lists, or
5740   // by following an RSet entry).
5741   //
5742   // But some of the referents, that are in the collection set, that these
5743   // reference objects point to may not have been copied: the STW ref
5744   // processor would have seen that the reference object had already
5745   // been 'discovered' and would have skipped discovering the reference,
5746   // but would not have treated the reference object as a regular oop.
5747   // As a result the copy closure would not have been applied to the
5748   // referent object.
5749   //
5750   // We need to explicitly copy these referent objects - the references
5751   // will be processed at the end of remarking.
5752   //
5753   // We also need to do this copying before we process the reference
5754   // objects discovered by the STW ref processor in case one of these
5755   // referents points to another object which is also referenced by an
5756   // object discovered by the STW ref processor.
5757 
5758   assert(!G1CollectedHeap::use_parallel_gc_threads() ||
5759            no_of_gc_workers == workers()->active_workers(),
5760            "Need to reset active GC workers");
5761 
5762   set_par_threads(no_of_gc_workers);
5763   G1ParPreserveCMReferentsTask keep_cm_referents(this,
5764                                                  no_of_gc_workers,
5765                                                  _task_queues);
5766 
5767   if (G1CollectedHeap::use_parallel_gc_threads()) {
5768     workers()->run_task(&keep_cm_referents);
5769   } else {
5770     keep_cm_referents.work(0);
5771   }
5772 
5773   set_par_threads(0);
5774 
5775   // Closure to test whether a referent is alive.
5776   G1STWIsAliveClosure is_alive(this);
5777 
5778   // Even when parallel reference processing is enabled, the processing
5779   // of JNI refs is serial and performed serially by the current thread
5780   // rather than by a worker. The following PSS will be used for processing
5781   // JNI refs.
5782 
5783   // Use only a single queue for this PSS.
5784   G1ParScanThreadState            pss(this, 0, NULL);
5785 
5786   // We do not embed a reference processor in the copying/scanning
5787   // closures while we're actually processing the discovered
5788   // reference objects.
5789   G1ParScanHeapEvacFailureClosure evac_failure_cl(this, &pss, NULL);
5790 
5791   pss.set_evac_failure_closure(&evac_failure_cl);
5792 
5793   assert(pss.queue_is_empty(), "pre-condition");
5794 
5795   G1ParScanExtRootClosure        only_copy_non_heap_cl(this, &pss, NULL);
5796 
5797   G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);
5798 
5799   OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5800 
5801   if (_g1h->g1_policy()->during_initial_mark_pause()) {
5802     // We also need to mark copied objects.
5803     copy_non_heap_cl = &copy_mark_non_heap_cl;
5804   }
5805 
5806   // Keep alive closure.
5807   G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, &pss);
5808 
5809   // Serial Complete GC closure
5810   G1STWDrainQueueClosure drain_queue(this, &pss);
5811 
5812   // Setup the soft refs policy...
5813   rp->setup_policy(false);
5814 
5815   ReferenceProcessorStats stats;
5816   if (!rp->processing_is_mt()) {
5817     // Serial reference processing...
5818     stats = rp->process_discovered_references(&is_alive,
5819                                               &keep_alive,
5820                                               &drain_queue,
5821                                               NULL,
5822                                               _gc_timer_stw,
5823                                               _gc_tracer_stw->gc_id());
5824   } else {
5825     // Parallel reference processing
5826     assert(rp->num_q() == no_of_gc_workers, "sanity");
5827     assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5828 
5829     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5830     stats = rp->process_discovered_references(&is_alive,
5831                                               &keep_alive,
5832                                               &drain_queue,
5833                                               &par_task_executor,
5834                                               _gc_timer_stw,
5835                                               _gc_tracer_stw->gc_id());
5836   }
5837 
5838   _gc_tracer_stw->report_gc_reference_stats(stats);
5839 
5840   // We have completed copying any necessary live referent objects.
5841   assert(pss.queue_is_empty(), "both queue and overflow should be empty");
5842 
5843   double ref_proc_time = os::elapsedTime() - ref_proc_start;
5844   g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
5845 }
5846 
5847 // Weak Reference processing during an evacuation pause (part 2).
5848 void G1CollectedHeap::enqueue_discovered_references(uint no_of_gc_workers) {
5849   double ref_enq_start = os::elapsedTime();
5850 
5851   ReferenceProcessor* rp = _ref_processor_stw;
5852   assert(!rp->discovery_enabled(), "should have been disabled as part of processing");
5853 
5854   // Now enqueue any remaining on the discovered lists on to
5855   // the pending list.
5856   if (!rp->processing_is_mt()) {
5857     // Serial reference processing...
5858     rp->enqueue_discovered_references();
5859   } else {
5860     // Parallel reference enqueueing
5861 
5862     assert(no_of_gc_workers == workers()->active_workers(),
5863            "Need to reset active workers");
5864     assert(rp->num_q() == no_of_gc_workers, "sanity");
5865     assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5866 
5867     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5868     rp->enqueue_discovered_references(&par_task_executor);
5869   }
5870 
5871   rp->verify_no_references_recorded();
5872   assert(!rp->discovery_enabled(), "should have been disabled");
5873 
5874   // FIXME
5875   // CM's reference processing also cleans up the string and symbol tables.
5876   // Should we do that here also? We could, but it is a serial operation
5877   // and could significantly increase the pause time.
5878 
5879   double ref_enq_time = os::elapsedTime() - ref_enq_start;
5880   g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0);
5881 }
5882 
5883 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {
5884   _expand_heap_after_alloc_failure = true;
5885   _evacuation_failed = false;
5886 
5887   // Should G1EvacuationFailureALot be in effect for this GC?
5888   NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
5889 
5890   g1_rem_set()->prepare_for_oops_into_collection_set_do();
5891 
5892   // Disable the hot card cache.
5893   G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
5894   hot_card_cache->reset_hot_cache_claimed_index();
5895   hot_card_cache->set_use_cache(false);
5896 
5897   uint n_workers;
5898   if (G1CollectedHeap::use_parallel_gc_threads()) {
5899     n_workers =
5900       AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
5901                                      workers()->active_workers(),
5902                                      Threads::number_of_non_daemon_threads());
5903     assert(UseDynamicNumberOfGCThreads ||
5904            n_workers == workers()->total_workers(),
5905            "If not dynamic should be using all the  workers");
5906     workers()->set_active_workers(n_workers);
5907     set_par_threads(n_workers);
5908   } else {
5909     assert(n_par_threads() == 0,
5910            "Should be the original non-parallel value");
5911     n_workers = 1;
5912   }
5913 
5914   G1ParTask g1_par_task(this, _task_queues);
5915 
5916   init_for_evac_failure(NULL);
5917 
5918   rem_set()->prepare_for_younger_refs_iterate(true);
5919 
5920   assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
5921   double start_par_time_sec = os::elapsedTime();
5922   double end_par_time_sec;
5923 
5924   {
5925     StrongRootsScope srs(this);
5926     // InitialMark needs claim bits to keep track of the marked-through CLDs.
5927     if (g1_policy()->during_initial_mark_pause()) {
5928       ClassLoaderDataGraph::clear_claimed_marks();
5929     }
5930 
5931     if (G1CollectedHeap::use_parallel_gc_threads()) {
5932       // The individual threads will set their evac-failure closures.
5933       if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();
5934       // These tasks use ShareHeap::_process_strong_tasks
5935       assert(UseDynamicNumberOfGCThreads ||
5936              workers()->active_workers() == workers()->total_workers(),
5937              "If not dynamic should be using all the  workers");
5938       workers()->run_task(&g1_par_task);
5939     } else {
5940       g1_par_task.set_for_termination(n_workers);
5941       g1_par_task.work(0);
5942     }
5943     end_par_time_sec = os::elapsedTime();
5944 
5945     // Closing the inner scope will execute the destructor
5946     // for the StrongRootsScope object. We record the current
5947     // elapsed time before closing the scope so that time
5948     // taken for the SRS destructor is NOT included in the
5949     // reported parallel time.
5950   }
5951 
5952   double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0;
5953   g1_policy()->phase_times()->record_par_time(par_time_ms);
5954 
5955   double code_root_fixup_time_ms =
5956         (os::elapsedTime() - end_par_time_sec) * 1000.0;
5957   g1_policy()->phase_times()->record_code_root_fixup_time(code_root_fixup_time_ms);
5958 
5959   set_par_threads(0);
5960 
5961   // Process any discovered reference objects - we have
5962   // to do this _before_ we retire the GC alloc regions
5963   // as we may have to copy some 'reachable' referent
5964   // objects (and their reachable sub-graphs) that were
5965   // not copied during the pause.
5966   process_discovered_references(n_workers);
5967 
5968   // Weak root processing.
5969   {
5970     G1STWIsAliveClosure is_alive(this);
5971     G1KeepAliveClosure keep_alive(this);
5972     JNIHandles::weak_oops_do(&is_alive, &keep_alive);
5973     if (G1StringDedup::is_enabled()) {
5974       G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive);
5975     }
5976   }
5977 
5978   release_gc_alloc_regions(n_workers, evacuation_info);
5979   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
5980 
5981   // Reset and re-enable the hot card cache.
5982   // Note the counts for the cards in the regions in the
5983   // collection set are reset when the collection set is freed.
5984   hot_card_cache->reset_hot_cache();
5985   hot_card_cache->set_use_cache(true);
5986 
5987   // Migrate the strong code roots attached to each region in
5988   // the collection set. Ideally we would like to do this
5989   // after we have finished the scanning/evacuation of the
5990   // strong code roots for a particular heap region.
5991   migrate_strong_code_roots();
5992 
5993   purge_code_root_memory();
5994 
5995   if (g1_policy()->during_initial_mark_pause()) {
5996     // Reset the claim values set during marking the strong code roots
5997     reset_heap_region_claim_values();
5998   }
5999 
6000   finalize_for_evac_failure();
6001 
6002   if (evacuation_failed()) {
6003     remove_self_forwarding_pointers();
6004 
6005     // Reset the G1EvacuationFailureALot counters and flags
6006     // Note: the values are reset only when an actual
6007     // evacuation failure occurs.
6008     NOT_PRODUCT(reset_evacuation_should_fail();)
6009   }
6010 
6011   // Enqueue any remaining references remaining on the STW
6012   // reference processor's discovered lists. We need to do
6013   // this after the card table is cleaned (and verified) as
6014   // the act of enqueueing entries on to the pending list
6015   // will log these updates (and dirty their associated
6016   // cards). We need these updates logged to update any
6017   // RSets.
6018   enqueue_discovered_references(n_workers);
6019 
6020   if (G1DeferredRSUpdate) {
6021     redirty_logged_cards();
6022   }
6023   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
6024 }
6025 
6026 void G1CollectedHeap::free_region(HeapRegion* hr,
6027                                   FreeRegionList* free_list,
6028                                   bool par,
6029                                   bool locked) {
6030   assert(!hr->isHumongous(), "this is only for non-humongous regions");
6031   assert(!hr->is_empty(), "the region should not be empty");
6032   assert(_hrs.is_available(hr->hrs_index()), "region should be committed");
6033   assert(free_list != NULL, "pre-condition");
6034 
6035   if (G1VerifyBitmaps) {
6036     MemRegion mr(hr->bottom(), hr->end());
6037     concurrent_mark()->clearRangePrevBitmap(mr);
6038   }
6039 
6040   // Clear the card counts for this region.
6041   // Note: we only need to do this if the region is not young
6042   // (since we don't refine cards in young regions).
6043   if (!hr->is_young()) {
6044     _cg1r->hot_card_cache()->reset_card_counts(hr);
6045   }
6046   hr->hr_clear(par, true /* clear_space */, locked /* locked */);
6047   free_list->add_ordered(hr);
6048 }
6049 
6050 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
6051                                      FreeRegionList* free_list,
6052                                      bool par) {
6053   assert(hr->startsHumongous(), "this is only for starts humongous regions");
6054   assert(free_list != NULL, "pre-condition");
6055 
6056   size_t hr_capacity = hr->capacity();
6057   // We need to read this before we make the region non-humongous,
6058   // otherwise the information will be gone.
6059   uint last_index = hr->last_hc_index();
6060   hr->set_notHumongous();
6061   free_region(hr, free_list, par);
6062 
6063   uint i = hr->hrs_index() + 1;
6064   while (i < last_index) {
6065     HeapRegion* curr_hr = region_at(i);
6066     assert(curr_hr->continuesHumongous(), "invariant");
6067     curr_hr->set_notHumongous();
6068     free_region(curr_hr, free_list, par);
6069     i += 1;
6070   }
6071 }
6072 
6073 void G1CollectedHeap::remove_from_old_sets(const HeapRegionSetCount& old_regions_removed,
6074                                        const HeapRegionSetCount& humongous_regions_removed) {
6075   if (old_regions_removed.length() > 0 || humongous_regions_removed.length() > 0) {
6076     MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
6077     _old_set.bulk_remove(old_regions_removed);
6078     _humongous_set.bulk_remove(humongous_regions_removed);
6079   }
6080 
6081 }
6082 
6083 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
6084   assert(list != NULL, "list can't be null");
6085   if (!list->is_empty()) {
6086     MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
6087     _hrs.insert_list_into_free_list(list);
6088   }
6089 }
6090 
6091 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
6092   assert(_summary_bytes_used >= bytes,
6093          err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" should be >= bytes: "SIZE_FORMAT,
6094                   _summary_bytes_used, bytes));
6095   _summary_bytes_used -= bytes;
6096 }
6097 
6098 class G1ParCleanupCTTask : public AbstractGangTask {
6099   G1SATBCardTableModRefBS* _ct_bs;
6100   G1CollectedHeap* _g1h;
6101   HeapRegion* volatile _su_head;
6102 public:
6103   G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs,
6104                      G1CollectedHeap* g1h) :
6105     AbstractGangTask("G1 Par Cleanup CT Task"),
6106     _ct_bs(ct_bs), _g1h(g1h) { }
6107 
6108   void work(uint worker_id) {
6109     HeapRegion* r;
6110     while (r = _g1h->pop_dirty_cards_region()) {
6111       clear_cards(r);
6112     }
6113   }
6114 
6115   void clear_cards(HeapRegion* r) {
6116     // Cards of the survivors should have already been dirtied.
6117     if (!r->is_survivor()) {
6118       _ct_bs->clear(MemRegion(r->bottom(), r->end()));
6119     }
6120   }
6121 };
6122 
6123 #ifndef PRODUCT
6124 class G1VerifyCardTableCleanup: public HeapRegionClosure {
6125   G1CollectedHeap* _g1h;
6126   G1SATBCardTableModRefBS* _ct_bs;
6127 public:
6128   G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs)
6129     : _g1h(g1h), _ct_bs(ct_bs) { }
6130   virtual bool doHeapRegion(HeapRegion* r) {
6131     if (r->is_survivor()) {
6132       _g1h->verify_dirty_region(r);
6133     } else {
6134       _g1h->verify_not_dirty_region(r);
6135     }
6136     return false;
6137   }
6138 };
6139 
6140 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {
6141   // All of the region should be clean.
6142   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6143   MemRegion mr(hr->bottom(), hr->end());
6144   ct_bs->verify_not_dirty_region(mr);
6145 }
6146 
6147 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {
6148   // We cannot guarantee that [bottom(),end()] is dirty.  Threads
6149   // dirty allocated blocks as they allocate them. The thread that
6150   // retires each region and replaces it with a new one will do a
6151   // maximal allocation to fill in [pre_dummy_top(),end()] but will
6152   // not dirty that area (one less thing to have to do while holding
6153   // a lock). So we can only verify that [bottom(),pre_dummy_top()]
6154   // is dirty.
6155   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6156   MemRegion mr(hr->bottom(), hr->pre_dummy_top());
6157   if (hr->is_young()) {
6158     ct_bs->verify_g1_young_region(mr);
6159   } else {
6160     ct_bs->verify_dirty_region(mr);
6161   }
6162 }
6163 
6164 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {
6165   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6166   for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {
6167     verify_dirty_region(hr);
6168   }
6169 }
6170 
6171 void G1CollectedHeap::verify_dirty_young_regions() {
6172   verify_dirty_young_list(_young_list->first_region());
6173 }
6174 
6175 bool G1CollectedHeap::verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap,
6176                                                HeapWord* tams, HeapWord* end) {
6177   guarantee(tams <= end,
6178             err_msg("tams: "PTR_FORMAT" end: "PTR_FORMAT, tams, end));
6179   HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end);
6180   if (result < end) {
6181     gclog_or_tty->cr();
6182     gclog_or_tty->print_cr("## wrong marked address on %s bitmap: "PTR_FORMAT,
6183                            bitmap_name, result);
6184     gclog_or_tty->print_cr("## %s tams: "PTR_FORMAT" end: "PTR_FORMAT,
6185                            bitmap_name, tams, end);
6186     return false;
6187   }
6188   return true;
6189 }
6190 
6191 bool G1CollectedHeap::verify_bitmaps(const char* caller, HeapRegion* hr) {
6192   CMBitMapRO* prev_bitmap = concurrent_mark()->prevMarkBitMap();
6193   CMBitMapRO* next_bitmap = (CMBitMapRO*) concurrent_mark()->nextMarkBitMap();
6194 
6195   HeapWord* bottom = hr->bottom();
6196   HeapWord* ptams  = hr->prev_top_at_mark_start();
6197   HeapWord* ntams  = hr->next_top_at_mark_start();
6198   HeapWord* end    = hr->end();
6199 
6200   bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);
6201 
6202   bool res_n = true;
6203   // We reset mark_in_progress() before we reset _cmThread->in_progress() and in this window
6204   // we do the clearing of the next bitmap concurrently. Thus, we can not verify the bitmap
6205   // if we happen to be in that state.
6206   if (mark_in_progress() || !_cmThread->in_progress()) {
6207     res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
6208   }
6209   if (!res_p || !res_n) {
6210     gclog_or_tty->print_cr("#### Bitmap verification failed for "HR_FORMAT,
6211                            HR_FORMAT_PARAMS(hr));
6212     gclog_or_tty->print_cr("#### Caller: %s", caller);
6213     return false;
6214   }
6215   return true;
6216 }
6217 
6218 void G1CollectedHeap::check_bitmaps(const char* caller, HeapRegion* hr) {
6219   if (!G1VerifyBitmaps) return;
6220 
6221   guarantee(verify_bitmaps(caller, hr), "bitmap verification");
6222 }
6223 
6224 class G1VerifyBitmapClosure : public HeapRegionClosure {
6225 private:
6226   const char* _caller;
6227   G1CollectedHeap* _g1h;
6228   bool _failures;
6229 
6230 public:
6231   G1VerifyBitmapClosure(const char* caller, G1CollectedHeap* g1h) :
6232     _caller(caller), _g1h(g1h), _failures(false) { }
6233 
6234   bool failures() { return _failures; }
6235 
6236   virtual bool doHeapRegion(HeapRegion* hr) {
6237     if (hr->continuesHumongous()) return false;
6238 
6239     bool result = _g1h->verify_bitmaps(_caller, hr);
6240     if (!result) {
6241       _failures = true;
6242     }
6243     return false;
6244   }
6245 };
6246 
6247 void G1CollectedHeap::check_bitmaps(const char* caller) {
6248   if (!G1VerifyBitmaps) return;
6249 
6250   G1VerifyBitmapClosure cl(caller, this);
6251   heap_region_iterate(&cl);
6252   guarantee(!cl.failures(), "bitmap verification");
6253 }
6254 #endif // PRODUCT
6255 
6256 void G1CollectedHeap::cleanUpCardTable() {
6257   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6258   double start = os::elapsedTime();
6259 
6260   {
6261     // Iterate over the dirty cards region list.
6262     G1ParCleanupCTTask cleanup_task(ct_bs, this);
6263 
6264     if (G1CollectedHeap::use_parallel_gc_threads()) {
6265       set_par_threads();
6266       workers()->run_task(&cleanup_task);
6267       set_par_threads(0);
6268     } else {
6269       while (_dirty_cards_region_list) {
6270         HeapRegion* r = _dirty_cards_region_list;
6271         cleanup_task.clear_cards(r);
6272         _dirty_cards_region_list = r->get_next_dirty_cards_region();
6273         if (_dirty_cards_region_list == r) {
6274           // The last region.
6275           _dirty_cards_region_list = NULL;
6276         }
6277         r->set_next_dirty_cards_region(NULL);
6278       }
6279     }
6280 #ifndef PRODUCT
6281     if (G1VerifyCTCleanup || VerifyAfterGC) {
6282       G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
6283       heap_region_iterate(&cleanup_verifier);
6284     }
6285 #endif
6286   }
6287 
6288   double elapsed = os::elapsedTime() - start;
6289   g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0);
6290 }
6291 
6292 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) {
6293   size_t pre_used = 0;
6294   FreeRegionList local_free_list("Local List for CSet Freeing");
6295 
6296   double young_time_ms     = 0.0;
6297   double non_young_time_ms = 0.0;
6298 
6299   // Since the collection set is a superset of the the young list,
6300   // all we need to do to clear the young list is clear its
6301   // head and length, and unlink any young regions in the code below
6302   _young_list->clear();
6303 
6304   G1CollectorPolicy* policy = g1_policy();
6305 
6306   double start_sec = os::elapsedTime();
6307   bool non_young = true;
6308 
6309   HeapRegion* cur = cs_head;
6310   int age_bound = -1;
6311   size_t rs_lengths = 0;
6312 
6313   while (cur != NULL) {
6314     assert(!is_on_master_free_list(cur), "sanity");
6315     if (non_young) {
6316       if (cur->is_young()) {
6317         double end_sec = os::elapsedTime();
6318         double elapsed_ms = (end_sec - start_sec) * 1000.0;
6319         non_young_time_ms += elapsed_ms;
6320 
6321         start_sec = os::elapsedTime();
6322         non_young = false;
6323       }
6324     } else {
6325       if (!cur->is_young()) {
6326         double end_sec = os::elapsedTime();
6327         double elapsed_ms = (end_sec - start_sec) * 1000.0;
6328         young_time_ms += elapsed_ms;
6329 
6330         start_sec = os::elapsedTime();
6331         non_young = true;
6332       }
6333     }
6334 
6335     rs_lengths += cur->rem_set()->occupied_locked();
6336 
6337     HeapRegion* next = cur->next_in_collection_set();
6338     assert(cur->in_collection_set(), "bad CS");
6339     cur->set_next_in_collection_set(NULL);
6340     cur->set_in_collection_set(false);
6341 
6342     if (cur->is_young()) {
6343       int index = cur->young_index_in_cset();
6344       assert(index != -1, "invariant");
6345       assert((uint) index < policy->young_cset_region_length(), "invariant");
6346       size_t words_survived = _surviving_young_words[index];
6347       cur->record_surv_words_in_group(words_survived);
6348 
6349       // At this point the we have 'popped' cur from the collection set
6350       // (linked via next_in_collection_set()) but it is still in the
6351       // young list (linked via next_young_region()). Clear the
6352       // _next_young_region field.
6353       cur->set_next_young_region(NULL);
6354     } else {
6355       int index = cur->young_index_in_cset();
6356       assert(index == -1, "invariant");
6357     }
6358 
6359     assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
6360             (!cur->is_young() && cur->young_index_in_cset() == -1),
6361             "invariant" );
6362 
6363     if (!cur->evacuation_failed()) {
6364       MemRegion used_mr = cur->used_region();
6365 
6366       // And the region is empty.
6367       assert(!used_mr.is_empty(), "Should not have empty regions in a CS.");
6368       pre_used += cur->used();
6369       free_region(cur, &local_free_list, false /* par */, true /* locked */);
6370     } else {
6371       cur->uninstall_surv_rate_group();
6372       if (cur->is_young()) {
6373         cur->set_young_index_in_cset(-1);
6374       }
6375       cur->set_not_young();
6376       cur->set_evacuation_failed(false);
6377       // The region is now considered to be old.
6378       _old_set.add(cur);
6379       evacuation_info.increment_collectionset_used_after(cur->used());
6380     }
6381     cur = next;
6382   }
6383 
6384   evacuation_info.set_regions_freed(local_free_list.length());
6385   policy->record_max_rs_lengths(rs_lengths);
6386   policy->cset_regions_freed();
6387 
6388   double end_sec = os::elapsedTime();
6389   double elapsed_ms = (end_sec - start_sec) * 1000.0;
6390 
6391   if (non_young) {
6392     non_young_time_ms += elapsed_ms;
6393   } else {
6394     young_time_ms += elapsed_ms;
6395   }
6396 
6397   prepend_to_freelist(&local_free_list);
6398   decrement_summary_bytes(pre_used);
6399   policy->phase_times()->record_young_free_cset_time_ms(young_time_ms);
6400   policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms);
6401 }
6402 
6403 class G1FreeHumongousRegionClosure : public HeapRegionClosure {
6404  private:
6405   FreeRegionList* _free_region_list;
6406   HeapRegionSet* _proxy_set;
6407   HeapRegionSetCount _humongous_regions_removed;
6408   size_t _freed_bytes;
6409  public:
6410 
6411   G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) :
6412     _free_region_list(free_region_list), _humongous_regions_removed(), _freed_bytes(0) {
6413   }
6414 
6415   virtual bool doHeapRegion(HeapRegion* r) {
6416     if (!r->startsHumongous()) {
6417       return false;
6418     }
6419 
6420     G1CollectedHeap* g1h = G1CollectedHeap::heap();
6421 
6422     oop obj = (oop)r->bottom();
6423     CMBitMap* next_bitmap = g1h->concurrent_mark()->nextMarkBitMap();
6424 
6425     // The following checks whether the humongous object is live are sufficient.
6426     // The main additional check (in addition to having a reference from the roots
6427     // or the young gen) is whether the humongous object has a remembered set entry.
6428     //
6429     // A humongous object cannot be live if there is no remembered set for it
6430     // because:
6431     // - there can be no references from within humongous starts regions referencing
6432     // the object because we never allocate other objects into them.
6433     // (I.e. there are no intra-region references that may be missed by the
6434     // remembered set)
6435     // - as soon there is a remembered set entry to the humongous starts region
6436     // (i.e. it has "escaped" to an old object) this remembered set entry will stay
6437     // until the end of a concurrent mark.
6438     //
6439     // It is not required to check whether the object has been found dead by marking
6440     // or not, in fact it would prevent reclamation within a concurrent cycle, as
6441     // all objects allocated during that time are considered live.
6442     // SATB marking is even more conservative than the remembered set.
6443     // So if at this point in the collection there is no remembered set entry,
6444     // nobody has a reference to it.
6445     // At the start of collection we flush all refinement logs, and remembered sets
6446     // are completely up-to-date wrt to references to the humongous object.
6447     //
6448     // Other implementation considerations:
6449     // - never consider object arrays: while they are a valid target, they have not
6450     // been observed to be used as temporary objects.
6451     // - they would also pose considerable effort for cleaning up the the remembered
6452     // sets.
6453     // While this cleanup is not strictly necessary to be done (or done instantly),
6454     // given that their occurrence is very low, this saves us this additional
6455     // complexity.
6456     uint region_idx = r->hrs_index();
6457     if (g1h->humongous_is_live(region_idx) ||
6458         g1h->humongous_region_is_always_live(region_idx)) {
6459 
6460       if (G1TraceReclaimDeadHumongousObjectsAtYoungGC) {
6461         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",
6462                                r->isHumongous(),
6463                                region_idx,
6464                                r->rem_set()->occupied(),
6465                                r->rem_set()->strong_code_roots_list_length(),
6466                                next_bitmap->isMarked(r->bottom()),
6467                                g1h->humongous_is_live(region_idx),
6468                                obj->is_objArray()
6469                               );
6470       }
6471 
6472       return false;
6473     }
6474 
6475     guarantee(!obj->is_objArray(),
6476               err_msg("Eagerly reclaiming object arrays is not supported, but the object "PTR_FORMAT" is.",
6477                       r->bottom()));
6478 
6479     if (G1TraceReclaimDeadHumongousObjectsAtYoungGC) {
6480       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",
6481                              r->isHumongous(),
6482                              r->bottom(),
6483                              region_idx,
6484                              r->region_num(),
6485                              r->rem_set()->occupied(),
6486                              r->rem_set()->strong_code_roots_list_length(),
6487                              next_bitmap->isMarked(r->bottom()),
6488                              g1h->humongous_is_live(region_idx),
6489                              obj->is_objArray()
6490                             );
6491     }
6492     // Need to clear mark bit of the humongous object if already set.
6493     if (next_bitmap->isMarked(r->bottom())) {
6494       next_bitmap->clear(r->bottom());
6495     }
6496     _freed_bytes += r->used();
6497     r->set_containing_set(NULL);
6498     _humongous_regions_removed.increment(1u, r->capacity());
6499     g1h->free_humongous_region(r, _free_region_list, false);
6500 
6501     return false;
6502   }
6503 
6504   HeapRegionSetCount& humongous_free_count() {
6505     return _humongous_regions_removed;
6506   }
6507 
6508   size_t bytes_freed() const {
6509     return _freed_bytes;
6510   }
6511 
6512   size_t humongous_reclaimed() const {
6513     return _humongous_regions_removed.length();
6514   }
6515 };
6516 
6517 void G1CollectedHeap::eagerly_reclaim_humongous_regions() {
6518   assert_at_safepoint(true);
6519 
6520   if (!G1ReclaimDeadHumongousObjectsAtYoungGC || !_has_humongous_reclaim_candidates) {
6521     g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0);
6522     return;
6523   }
6524 
6525   double start_time = os::elapsedTime();
6526 
6527   FreeRegionList local_cleanup_list("Local Humongous Cleanup List");
6528 
6529   G1FreeHumongousRegionClosure cl(&local_cleanup_list);
6530   heap_region_iterate(&cl);
6531 
6532   HeapRegionSetCount empty_set;
6533   remove_from_old_sets(empty_set, cl.humongous_free_count());
6534 
6535   G1HRPrinter* hr_printer = _g1h->hr_printer();
6536   if (hr_printer->is_active()) {
6537     FreeRegionListIterator iter(&local_cleanup_list);
6538     while (iter.more_available()) {
6539       HeapRegion* hr = iter.get_next();
6540       hr_printer->cleanup(hr);
6541     }
6542   }
6543 
6544   prepend_to_freelist(&local_cleanup_list);
6545   decrement_summary_bytes(cl.bytes_freed());
6546 
6547   g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0,
6548                                                                     cl.humongous_reclaimed());
6549 }
6550 
6551 // This routine is similar to the above but does not record
6552 // any policy statistics or update free lists; we are abandoning
6553 // the current incremental collection set in preparation of a
6554 // full collection. After the full GC we will start to build up
6555 // the incremental collection set again.
6556 // This is only called when we're doing a full collection
6557 // and is immediately followed by the tearing down of the young list.
6558 
6559 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
6560   HeapRegion* cur = cs_head;
6561 
6562   while (cur != NULL) {
6563     HeapRegion* next = cur->next_in_collection_set();
6564     assert(cur->in_collection_set(), "bad CS");
6565     cur->set_next_in_collection_set(NULL);
6566     cur->set_in_collection_set(false);
6567     cur->set_young_index_in_cset(-1);
6568     cur = next;
6569   }
6570 }
6571 
6572 void G1CollectedHeap::set_free_regions_coming() {
6573   if (G1ConcRegionFreeingVerbose) {
6574     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6575                            "setting free regions coming");
6576   }
6577 
6578   assert(!free_regions_coming(), "pre-condition");
6579   _free_regions_coming = true;
6580 }
6581 
6582 void G1CollectedHeap::reset_free_regions_coming() {
6583   assert(free_regions_coming(), "pre-condition");
6584 
6585   {
6586     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6587     _free_regions_coming = false;
6588     SecondaryFreeList_lock->notify_all();
6589   }
6590 
6591   if (G1ConcRegionFreeingVerbose) {
6592     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6593                            "reset free regions coming");
6594   }
6595 }
6596 
6597 void G1CollectedHeap::wait_while_free_regions_coming() {
6598   // Most of the time we won't have to wait, so let's do a quick test
6599   // first before we take the lock.
6600   if (!free_regions_coming()) {
6601     return;
6602   }
6603 
6604   if (G1ConcRegionFreeingVerbose) {
6605     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6606                            "waiting for free regions");
6607   }
6608 
6609   {
6610     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6611     while (free_regions_coming()) {
6612       SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
6613     }
6614   }
6615 
6616   if (G1ConcRegionFreeingVerbose) {
6617     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6618                            "done waiting for free regions");
6619   }
6620 }
6621 
6622 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
6623   assert(heap_lock_held_for_gc(),
6624               "the heap lock should already be held by or for this thread");
6625   _young_list->push_region(hr);
6626 }
6627 
6628 class NoYoungRegionsClosure: public HeapRegionClosure {
6629 private:
6630   bool _success;
6631 public:
6632   NoYoungRegionsClosure() : _success(true) { }
6633   bool doHeapRegion(HeapRegion* r) {
6634     if (r->is_young()) {
6635       gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
6636                              r->bottom(), r->end());
6637       _success = false;
6638     }
6639     return false;
6640   }
6641   bool success() { return _success; }
6642 };
6643 
6644 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
6645   bool ret = _young_list->check_list_empty(check_sample);
6646 
6647   if (check_heap) {
6648     NoYoungRegionsClosure closure;
6649     heap_region_iterate(&closure);
6650     ret = ret && closure.success();
6651   }
6652 
6653   return ret;
6654 }
6655 
6656 class TearDownRegionSetsClosure : public HeapRegionClosure {
6657 private:
6658   HeapRegionSet *_old_set;
6659 
6660 public:
6661   TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }
6662 
6663   bool doHeapRegion(HeapRegion* r) {
6664     if (r->is_empty()) {
6665       // We ignore empty regions, we'll empty the free list afterwards
6666     } else if (r->is_young()) {
6667       // We ignore young regions, we'll empty the young list afterwards
6668     } else if (r->isHumongous()) {
6669       // We ignore humongous regions, we're not tearing down the
6670       // humongous region set
6671     } else {
6672       // The rest should be old
6673       _old_set->remove(r);
6674     }
6675     return false;
6676   }
6677 
6678   ~TearDownRegionSetsClosure() {
6679     assert(_old_set->is_empty(), "post-condition");
6680   }
6681 };
6682 
6683 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {
6684   assert_at_safepoint(true /* should_be_vm_thread */);
6685 
6686   if (!free_list_only) {
6687     TearDownRegionSetsClosure cl(&_old_set);
6688     heap_region_iterate(&cl);
6689 
6690     // Note that emptying the _young_list is postponed and instead done as
6691     // the first step when rebuilding the regions sets again. The reason for
6692     // this is that during a full GC string deduplication needs to know if
6693     // a collected region was young or old when the full GC was initiated.
6694   }
6695   _hrs.remove_all_free_regions();
6696 }
6697 
6698 class RebuildRegionSetsClosure : public HeapRegionClosure {
6699 private:
6700   bool            _free_list_only;
6701   HeapRegionSet*   _old_set;
6702   HeapRegionSeq*   _hrs;
6703   size_t          _total_used;
6704 
6705 public:
6706   RebuildRegionSetsClosure(bool free_list_only,
6707                            HeapRegionSet* old_set, HeapRegionSeq* hrs) :
6708     _free_list_only(free_list_only),
6709     _old_set(old_set), _hrs(hrs), _total_used(0) {
6710     assert(_hrs->num_free_regions() == 0, "pre-condition");
6711     if (!free_list_only) {
6712       assert(_old_set->is_empty(), "pre-condition");
6713     }
6714   }
6715 
6716   bool doHeapRegion(HeapRegion* r) {
6717     if (r->continuesHumongous()) {
6718       return false;
6719     }
6720 
6721     if (r->is_empty()) {
6722       // Add free regions to the free list
6723       _hrs->insert_into_free_list(r);
6724     } else if (!_free_list_only) {
6725       assert(!r->is_young(), "we should not come across young regions");
6726 
6727       if (r->isHumongous()) {
6728         // We ignore humongous regions, we left the humongous set unchanged
6729       } else {
6730         // The rest should be old, add them to the old set
6731         _old_set->add(r);
6732       }
6733       _total_used += r->used();
6734     }
6735 
6736     return false;
6737   }
6738 
6739   size_t total_used() {
6740     return _total_used;
6741   }
6742 };
6743 
6744 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
6745   assert_at_safepoint(true /* should_be_vm_thread */);
6746 
6747   if (!free_list_only) {
6748     _young_list->empty_list();
6749   }
6750 
6751   RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_hrs);
6752   heap_region_iterate(&cl);
6753 
6754   if (!free_list_only) {
6755     _summary_bytes_used = cl.total_used();
6756   }
6757   assert(_summary_bytes_used == recalculate_used(),
6758          err_msg("inconsistent _summary_bytes_used, "
6759                  "value: "SIZE_FORMAT" recalculated: "SIZE_FORMAT,
6760                  _summary_bytes_used, recalculate_used()));
6761 }
6762 
6763 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
6764   _refine_cte_cl->set_concurrent(concurrent);
6765 }
6766 
6767 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
6768   HeapRegion* hr = heap_region_containing(p);
6769   return hr->is_in(p);
6770 }
6771 
6772 // Methods for the mutator alloc region
6773 
6774 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
6775                                                       bool force) {
6776   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6777   assert(!force || g1_policy()->can_expand_young_list(),
6778          "if force is true we should be able to expand the young list");
6779   bool young_list_full = g1_policy()->is_young_list_full();
6780   if (force || !young_list_full) {
6781     HeapRegion* new_alloc_region = new_region(word_size,
6782                                               false /* is_old */,
6783                                               false /* do_expand */);
6784     if (new_alloc_region != NULL) {
6785       set_region_short_lived_locked(new_alloc_region);
6786       _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
6787       check_bitmaps("Mutator Region Allocation", new_alloc_region);
6788       return new_alloc_region;
6789     }
6790   }
6791   return NULL;
6792 }
6793 
6794 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
6795                                                   size_t allocated_bytes) {
6796   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6797   assert(alloc_region->is_young(), "all mutator alloc regions should be young");
6798 
6799   g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
6800   _summary_bytes_used += allocated_bytes;
6801   _hr_printer.retire(alloc_region);
6802   // We update the eden sizes here, when the region is retired,
6803   // instead of when it's allocated, since this is the point that its
6804   // used space has been recored in _summary_bytes_used.
6805   g1mm()->update_eden_size();
6806 }
6807 
6808 HeapRegion* MutatorAllocRegion::allocate_new_region(size_t word_size,
6809                                                     bool force) {
6810   return _g1h->new_mutator_alloc_region(word_size, force);
6811 }
6812 
6813 void G1CollectedHeap::set_par_threads() {
6814   // Don't change the number of workers.  Use the value previously set
6815   // in the workgroup.
6816   assert(G1CollectedHeap::use_parallel_gc_threads(), "shouldn't be here otherwise");
6817   uint n_workers = workers()->active_workers();
6818   assert(UseDynamicNumberOfGCThreads ||
6819            n_workers == workers()->total_workers(),
6820       "Otherwise should be using the total number of workers");
6821   if (n_workers == 0) {
6822     assert(false, "Should have been set in prior evacuation pause.");
6823     n_workers = ParallelGCThreads;
6824     workers()->set_active_workers(n_workers);
6825   }
6826   set_par_threads(n_workers);
6827 }
6828 
6829 void MutatorAllocRegion::retire_region(HeapRegion* alloc_region,
6830                                        size_t allocated_bytes) {
6831   _g1h->retire_mutator_alloc_region(alloc_region, allocated_bytes);
6832 }
6833 
6834 // Methods for the GC alloc regions
6835 
6836 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,
6837                                                  uint count,
6838                                                  GCAllocPurpose ap) {
6839   assert(FreeList_lock->owned_by_self(), "pre-condition");
6840 
6841   if (count < g1_policy()->max_regions(ap)) {
6842     bool survivor = (ap == GCAllocForSurvived);
6843     HeapRegion* new_alloc_region = new_region(word_size,
6844                                               !survivor,
6845                                               true /* do_expand */);
6846     if (new_alloc_region != NULL) {
6847       // We really only need to do this for old regions given that we
6848       // should never scan survivors. But it doesn't hurt to do it
6849       // for survivors too.
6850       new_alloc_region->record_top_and_timestamp();
6851       if (survivor) {
6852         new_alloc_region->set_survivor();
6853         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
6854         check_bitmaps("Survivor Region Allocation", new_alloc_region);
6855       } else {
6856         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
6857         check_bitmaps("Old Region Allocation", new_alloc_region);
6858       }
6859       bool during_im = g1_policy()->during_initial_mark_pause();
6860       new_alloc_region->note_start_of_copying(during_im);
6861       return new_alloc_region;
6862     } else {
6863       g1_policy()->note_alloc_region_limit_reached(ap);
6864     }
6865   }
6866   return NULL;
6867 }
6868 
6869 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
6870                                              size_t allocated_bytes,
6871                                              GCAllocPurpose ap) {
6872   bool during_im = g1_policy()->during_initial_mark_pause();
6873   alloc_region->note_end_of_copying(during_im);
6874   g1_policy()->record_bytes_copied_during_gc(allocated_bytes);
6875   if (ap == GCAllocForSurvived) {
6876     young_list()->add_survivor_region(alloc_region);
6877   } else {
6878     _old_set.add(alloc_region);
6879   }
6880   _hr_printer.retire(alloc_region);
6881 }
6882 
6883 HeapRegion* SurvivorGCAllocRegion::allocate_new_region(size_t word_size,
6884                                                        bool force) {
6885   assert(!force, "not supported for GC alloc regions");
6886   return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForSurvived);
6887 }
6888 
6889 void SurvivorGCAllocRegion::retire_region(HeapRegion* alloc_region,
6890                                           size_t allocated_bytes) {
6891   _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6892                                GCAllocForSurvived);
6893 }
6894 
6895 HeapRegion* OldGCAllocRegion::allocate_new_region(size_t word_size,
6896                                                   bool force) {
6897   assert(!force, "not supported for GC alloc regions");
6898   return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForTenured);
6899 }
6900 
6901 void OldGCAllocRegion::retire_region(HeapRegion* alloc_region,
6902                                      size_t allocated_bytes) {
6903   _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6904                                GCAllocForTenured);
6905 }
6906 
6907 HeapRegion* OldGCAllocRegion::release() {
6908   HeapRegion* cur = get();
6909   if (cur != NULL) {
6910     // Determine how far we are from the next card boundary. If it is smaller than
6911     // the minimum object size we can allocate into, expand into the next card.
6912     HeapWord* top = cur->top();
6913     HeapWord* aligned_top = (HeapWord*)align_ptr_up(top, G1BlockOffsetSharedArray::N_bytes);
6914 
6915     size_t to_allocate_words = pointer_delta(aligned_top, top, HeapWordSize);
6916 
6917     if (to_allocate_words != 0) {
6918       // We are not at a card boundary. Fill up, possibly into the next, taking the
6919       // end of the region and the minimum object size into account.
6920       to_allocate_words = MIN2(pointer_delta(cur->end(), cur->top(), HeapWordSize),
6921                                MAX2(to_allocate_words, G1CollectedHeap::min_fill_size()));
6922 
6923       // Skip allocation if there is not enough space to allocate even the smallest
6924       // possible object. In this case this region will not be retained, so the
6925       // original problem cannot occur.
6926       if (to_allocate_words >= G1CollectedHeap::min_fill_size()) {
6927         HeapWord* dummy = attempt_allocation(to_allocate_words, true /* bot_updates */);
6928         CollectedHeap::fill_with_object(dummy, to_allocate_words);
6929       }
6930     }
6931   }
6932   return G1AllocRegion::release();
6933 }
6934 
6935 // Heap region set verification
6936 
6937 class VerifyRegionListsClosure : public HeapRegionClosure {
6938 private:
6939   HeapRegionSet*   _old_set;
6940   HeapRegionSet*   _humongous_set;
6941   HeapRegionSeq*   _hrs;
6942 
6943 public:
6944   HeapRegionSetCount _old_count;
6945   HeapRegionSetCount _humongous_count;
6946   HeapRegionSetCount _free_count;
6947 
6948   VerifyRegionListsClosure(HeapRegionSet* old_set,
6949                            HeapRegionSet* humongous_set,
6950                            HeapRegionSeq* hrs) :
6951     _old_set(old_set), _humongous_set(humongous_set), _hrs(hrs),
6952     _old_count(), _humongous_count(), _free_count(){ }
6953 
6954   bool doHeapRegion(HeapRegion* hr) {
6955     if (hr->continuesHumongous()) {
6956       return false;
6957     }
6958 
6959     if (hr->is_young()) {
6960       // TODO
6961     } else if (hr->startsHumongous()) {
6962       assert(hr->containing_set() == _humongous_set, err_msg("Heap region %u is starts humongous but not in humongous set.", hr->hrs_index()));
6963       _humongous_count.increment(1u, hr->capacity());
6964     } else if (hr->is_empty()) {
6965       assert(_hrs->is_free(hr), err_msg("Heap region %u is empty but not on the free list.", hr->hrs_index()));
6966       _free_count.increment(1u, hr->capacity());
6967     } else {
6968       assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->hrs_index()));
6969       _old_count.increment(1u, hr->capacity());
6970     }
6971     return false;
6972   }
6973 
6974   void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, HeapRegionSeq* free_list) {
6975     guarantee(old_set->length() == _old_count.length(), err_msg("Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count.length()));
6976     guarantee(old_set->total_capacity_bytes() == _old_count.capacity(), err_msg("Old set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6977         old_set->total_capacity_bytes(), _old_count.capacity()));
6978 
6979     guarantee(humongous_set->length() == _humongous_count.length(), err_msg("Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count.length()));
6980     guarantee(humongous_set->total_capacity_bytes() == _humongous_count.capacity(), err_msg("Hum set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6981         humongous_set->total_capacity_bytes(), _humongous_count.capacity()));
6982 
6983     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()));
6984     guarantee(free_list->total_capacity_bytes() == _free_count.capacity(), err_msg("Free list capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6985         free_list->total_capacity_bytes(), _free_count.capacity()));
6986   }
6987 };
6988 
6989 void G1CollectedHeap::verify_region_sets() {
6990   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6991 
6992   // First, check the explicit lists.
6993   _hrs.verify();
6994   {
6995     // Given that a concurrent operation might be adding regions to
6996     // the secondary free list we have to take the lock before
6997     // verifying it.
6998     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6999     _secondary_free_list.verify_list();
7000   }
7001 
7002   // If a concurrent region freeing operation is in progress it will
7003   // be difficult to correctly attributed any free regions we come
7004   // across to the correct free list given that they might belong to
7005   // one of several (free_list, secondary_free_list, any local lists,
7006   // etc.). So, if that's the case we will skip the rest of the
7007   // verification operation. Alternatively, waiting for the concurrent
7008   // operation to complete will have a non-trivial effect on the GC's
7009   // operation (no concurrent operation will last longer than the
7010   // interval between two calls to verification) and it might hide
7011   // any issues that we would like to catch during testing.
7012   if (free_regions_coming()) {
7013     return;
7014   }
7015 
7016   // Make sure we append the secondary_free_list on the free_list so
7017   // that all free regions we will come across can be safely
7018   // attributed to the free_list.
7019   append_secondary_free_list_if_not_empty_with_lock();
7020 
7021   // Finally, make sure that the region accounting in the lists is
7022   // consistent with what we see in the heap.
7023 
7024   VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_hrs);
7025   heap_region_iterate(&cl);
7026   cl.verify_counts(&_old_set, &_humongous_set, &_hrs);
7027 }
7028 
7029 // Optimized nmethod scanning
7030 
7031 class RegisterNMethodOopClosure: public OopClosure {
7032   G1CollectedHeap* _g1h;
7033   nmethod* _nm;
7034 
7035   template <class T> void do_oop_work(T* p) {
7036     T heap_oop = oopDesc::load_heap_oop(p);
7037     if (!oopDesc::is_null(heap_oop)) {
7038       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
7039       HeapRegion* hr = _g1h->heap_region_containing(obj);
7040       assert(!hr->continuesHumongous(),
7041              err_msg("trying to add code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
7042                      " starting at "HR_FORMAT,
7043                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
7044 
7045       // HeapRegion::add_strong_code_root() avoids adding duplicate
7046       // entries but having duplicates is  OK since we "mark" nmethods
7047       // as visited when we scan the strong code root lists during the GC.
7048       hr->add_strong_code_root(_nm);
7049       assert(hr->rem_set()->strong_code_roots_list_contains(_nm),
7050              err_msg("failed to add code root "PTR_FORMAT" to remembered set of region "HR_FORMAT,
7051                      _nm, HR_FORMAT_PARAMS(hr)));
7052     }
7053   }
7054 
7055 public:
7056   RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
7057     _g1h(g1h), _nm(nm) {}
7058 
7059   void do_oop(oop* p)       { do_oop_work(p); }
7060   void do_oop(narrowOop* p) { do_oop_work(p); }
7061 };
7062 
7063 class UnregisterNMethodOopClosure: public OopClosure {
7064   G1CollectedHeap* _g1h;
7065   nmethod* _nm;
7066 
7067   template <class T> void do_oop_work(T* p) {
7068     T heap_oop = oopDesc::load_heap_oop(p);
7069     if (!oopDesc::is_null(heap_oop)) {
7070       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
7071       HeapRegion* hr = _g1h->heap_region_containing(obj);
7072       assert(!hr->continuesHumongous(),
7073              err_msg("trying to remove code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
7074                      " starting at "HR_FORMAT,
7075                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
7076 
7077       hr->remove_strong_code_root(_nm);
7078       assert(!hr->rem_set()->strong_code_roots_list_contains(_nm),
7079              err_msg("failed to remove code root "PTR_FORMAT" of region "HR_FORMAT,
7080                      _nm, HR_FORMAT_PARAMS(hr)));
7081     }
7082   }
7083 
7084 public:
7085   UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
7086     _g1h(g1h), _nm(nm) {}
7087 
7088   void do_oop(oop* p)       { do_oop_work(p); }
7089   void do_oop(narrowOop* p) { do_oop_work(p); }
7090 };
7091 
7092 void G1CollectedHeap::register_nmethod(nmethod* nm) {
7093   CollectedHeap::register_nmethod(nm);
7094 
7095   guarantee(nm != NULL, "sanity");
7096   RegisterNMethodOopClosure reg_cl(this, nm);
7097   nm->oops_do(&reg_cl);
7098 }
7099 
7100 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
7101   CollectedHeap::unregister_nmethod(nm);
7102 
7103   guarantee(nm != NULL, "sanity");
7104   UnregisterNMethodOopClosure reg_cl(this, nm);
7105   nm->oops_do(&reg_cl, true);
7106 }
7107 
7108 class MigrateCodeRootsHeapRegionClosure: public HeapRegionClosure {
7109 public:
7110   bool doHeapRegion(HeapRegion *hr) {
7111     assert(!hr->isHumongous(),
7112            err_msg("humongous region "HR_FORMAT" should not have been added to collection set",
7113                    HR_FORMAT_PARAMS(hr)));
7114     hr->migrate_strong_code_roots();
7115     return false;
7116   }
7117 };
7118 
7119 void G1CollectedHeap::migrate_strong_code_roots() {
7120   MigrateCodeRootsHeapRegionClosure cl;
7121   double migrate_start = os::elapsedTime();
7122   collection_set_iterate(&cl);
7123   double migration_time_ms = (os::elapsedTime() - migrate_start) * 1000.0;
7124   g1_policy()->phase_times()->record_strong_code_root_migration_time(migration_time_ms);
7125 }
7126 
7127 void G1CollectedHeap::purge_code_root_memory() {
7128   double purge_start = os::elapsedTime();
7129   G1CodeRootSet::purge_chunks(G1CodeRootsChunkCacheKeepPercent);
7130   double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0;
7131   g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms);
7132 }
7133 
7134 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
7135   G1CollectedHeap* _g1h;
7136 
7137 public:
7138   RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
7139     _g1h(g1h) {}
7140 
7141   void do_code_blob(CodeBlob* cb) {
7142     nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
7143     if (nm == NULL) {
7144       return;
7145     }
7146 
7147     if (ScavengeRootsInCode) {
7148       _g1h->register_nmethod(nm);
7149     }
7150   }
7151 };
7152 
7153 void G1CollectedHeap::rebuild_strong_code_roots() {
7154   RebuildStrongCodeRootClosure blob_cl(this);
7155   CodeCache::blobs_do(&blob_cl);
7156 }