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