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