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