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