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