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