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