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