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