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