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