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