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