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