< prev index next >

src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp

Print this page

  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 "memory/allocation.hpp"
  27 #include "memory/universe.hpp"
  28 
  29 #include "gc/shared/gcArguments.hpp"
  30 #include "gc/shared/gcTimer.hpp"
  31 #include "gc/shared/gcTraceTime.inline.hpp"
  32 #include "gc/shared/locationPrinter.inline.hpp"
  33 #include "gc/shared/memAllocator.hpp"
  34 #include "gc/shared/plab.hpp"
  35 #include "gc/shared/tlab_globals.hpp"
  36 
  37 #include "gc/shenandoah/shenandoahBarrierSet.hpp"

  38 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  39 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  40 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  41 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
  42 #include "gc/shenandoah/shenandoahControlThread.hpp"

  43 #include "gc/shenandoah/shenandoahFreeSet.hpp"

  44 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  45 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  46 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  47 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  48 #include "gc/shenandoah/shenandoahInitLogger.hpp"
  49 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  50 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  51 #include "gc/shenandoah/shenandoahMetrics.hpp"
  52 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"

  53 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  54 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
  55 #include "gc/shenandoah/shenandoahPadding.hpp"
  56 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
  57 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  58 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"

  59 #include "gc/shenandoah/shenandoahStringDedup.hpp"
  60 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  61 #include "gc/shenandoah/shenandoahUtils.hpp"
  62 #include "gc/shenandoah/shenandoahVerifier.hpp"
  63 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  64 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  65 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  66 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"


  67 #include "gc/shenandoah/mode/shenandoahIUMode.hpp"
  68 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"
  69 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp"

  70 #if INCLUDE_JFR
  71 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
  72 #endif
  73 


  74 #include "classfile/systemDictionary.hpp"
  75 #include "memory/classLoaderMetaspace.hpp"
  76 #include "memory/metaspaceUtils.hpp"
  77 #include "oops/compressedOops.inline.hpp"
  78 #include "prims/jvmtiTagMap.hpp"
  79 #include "runtime/atomic.hpp"
  80 #include "runtime/globals.hpp"
  81 #include "runtime/interfaceSupport.inline.hpp"
  82 #include "runtime/java.hpp"
  83 #include "runtime/orderAccess.hpp"
  84 #include "runtime/safepointMechanism.hpp"
  85 #include "runtime/vmThread.hpp"
  86 #include "services/mallocTracker.hpp"
  87 #include "services/memTracker.hpp"
  88 #include "utilities/events.hpp"
  89 #include "utilities/powerOfTwo.hpp"
  90 
  91 class ShenandoahPretouchHeapTask : public WorkerTask {
  92 private:
  93   ShenandoahRegionIterator _regions;

 140 jint ShenandoahHeap::initialize() {
 141   //
 142   // Figure out heap sizing
 143   //
 144 
 145   size_t init_byte_size = InitialHeapSize;
 146   size_t min_byte_size  = MinHeapSize;
 147   size_t max_byte_size  = MaxHeapSize;
 148   size_t heap_alignment = HeapAlignment;
 149 
 150   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 151 
 152   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 153   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 154 
 155   _num_regions = ShenandoahHeapRegion::region_count();
 156   assert(_num_regions == (max_byte_size / reg_size_bytes),
 157          "Regions should cover entire heap exactly: " SIZE_FORMAT " != " SIZE_FORMAT "/" SIZE_FORMAT,
 158          _num_regions, max_byte_size, reg_size_bytes);
 159 
 160   // Now we know the number of regions, initialize the heuristics.
 161   initialize_heuristics();
 162 
 163   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 164   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 165   assert(num_committed_regions <= _num_regions, "sanity");
 166   _initial_size = num_committed_regions * reg_size_bytes;
 167 
 168   size_t num_min_regions = min_byte_size / reg_size_bytes;
 169   num_min_regions = MIN2(num_min_regions, _num_regions);
 170   assert(num_min_regions <= _num_regions, "sanity");
 171   _minimum_size = num_min_regions * reg_size_bytes;
 172 
 173   // Default to max heap size.
 174   _soft_max_size = _num_regions * reg_size_bytes;
 175 
 176   _committed = _initial_size;
 177 




 178   size_t heap_page_size   = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 179   size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 180   size_t region_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 181 
 182   //
 183   // Reserve and commit memory for heap
 184   //
 185 
 186   ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 187   initialize_reserved_region(heap_rs);
 188   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 189   _heap_region_special = heap_rs.special();
 190 
 191   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 192          "Misaligned heap: " PTR_FORMAT, p2i(base()));
 193 
 194 #if SHENANDOAH_OPTIMIZED_MARKTASK
 195   // The optimized ShenandoahMarkTask takes some bits away from the full object bits.
 196   // Fail if we ever attempt to address more than we can.
 197   if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {
 198     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 199                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 200                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 201                 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());
 202     vm_exit_during_initialization("Fatal Error", buf);
 203   }
 204 #endif
 205 
 206   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 207   if (!_heap_region_special) {
 208     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 209                               "Cannot commit heap memory");
 210   }
 211 

























 212   //
 213   // Reserve and commit memory for bitmap(s)
 214   //
 215 
 216   _bitmap_size = ShenandoahMarkBitMap::compute_size(heap_rs.size());
 217   _bitmap_size = align_up(_bitmap_size, bitmap_page_size);
 218 
 219   size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();
 220 
 221   guarantee(bitmap_bytes_per_region != 0,
 222             "Bitmap bytes per region should not be zero");
 223   guarantee(is_power_of_2(bitmap_bytes_per_region),
 224             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
 225 
 226   if (bitmap_page_size > bitmap_bytes_per_region) {
 227     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 228     _bitmap_bytes_per_slice = bitmap_page_size;
 229   } else {
 230     _bitmap_regions_per_slice = 1;
 231     _bitmap_bytes_per_slice = bitmap_bytes_per_region;

 235             "Should have at least one region per slice: " SIZE_FORMAT,
 236             _bitmap_regions_per_slice);
 237 
 238   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 239             "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
 240             _bitmap_bytes_per_slice, bitmap_page_size);
 241 
 242   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 243   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 244   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 245   _bitmap_region_special = bitmap.special();
 246 
 247   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 248                               align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 249   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 250   if (!_bitmap_region_special) {
 251     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 252                               "Cannot commit bitmap memory");
 253   }
 254 
 255   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions, _max_workers);
 256 
 257   if (ShenandoahVerify) {
 258     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
 259     if (!verify_bitmap.special()) {
 260       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 261                                 "Cannot commit verification bitmap memory");
 262     }
 263     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 264     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 265     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 266     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 267   }
 268 
 269   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 270   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 271   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 272   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 273   _aux_bitmap_region_special = aux_bitmap.special();
 274   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 275 

 381   // There should probably be Shenandoah-specific options for these,
 382   // just as there are G1-specific options.
 383   {
 384     ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
 385     satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
 386     satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
 387   }
 388 
 389   _monitoring_support = new ShenandoahMonitoringSupport(this);
 390   _phase_timings = new ShenandoahPhaseTimings(max_workers());
 391   ShenandoahCodeRoots::initialize();
 392 
 393   if (ShenandoahPacing) {
 394     _pacer = new ShenandoahPacer(this);
 395     _pacer->setup_for_idle();
 396   } else {
 397     _pacer = NULL;
 398   }
 399 
 400   _control_thread = new ShenandoahControlThread();

 401 
 402   ShenandoahInitLogger::print();
 403 
 404   return JNI_OK;
 405 }
 406 
 407 void ShenandoahHeap::initialize_mode() {











 408   if (ShenandoahGCMode != NULL) {
 409     if (strcmp(ShenandoahGCMode, "satb") == 0) {
 410       _gc_mode = new ShenandoahSATBMode();
 411     } else if (strcmp(ShenandoahGCMode, "iu") == 0) {
 412       _gc_mode = new ShenandoahIUMode();
 413     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 414       _gc_mode = new ShenandoahPassiveMode();


 415     } else {
 416       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 417     }
 418   } else {
 419     vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)");
 420   }
 421   _gc_mode->initialize_flags();
 422   if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 423     vm_exit_during_initialization(
 424             err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 425                     _gc_mode->name()));
 426   }
 427   if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
 428     vm_exit_during_initialization(
 429             err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 430                     _gc_mode->name()));
 431   }
 432 }
 433 
 434 void ShenandoahHeap::initialize_heuristics() {
 435   assert(_gc_mode != NULL, "Must be initialized");
 436   _heuristics = _gc_mode->initialize_heuristics();

 437 
 438   if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 439     vm_exit_during_initialization(
 440             err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 441                     _heuristics->name()));
 442   }
 443   if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
 444     vm_exit_during_initialization(
 445             err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 446                     _heuristics->name()));
 447   }
 448 }
 449 
 450 #ifdef _MSC_VER
 451 #pragma warning( push )
 452 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 453 #endif
 454 
 455 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 456   CollectedHeap(),


 457   _initial_size(0),
 458   _used(0),
 459   _committed(0),
 460   _bytes_allocated_since_gc_start(0),
 461   _max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
 462   _workers(NULL),
 463   _safepoint_workers(NULL),
 464   _heap_region_special(false),
 465   _num_regions(0),
 466   _regions(NULL),
 467   _update_refs_iterator(this),











 468   _control_thread(NULL),

 469   _shenandoah_policy(policy),
 470   _gc_mode(NULL),
 471   _heuristics(NULL),
 472   _free_set(NULL),
 473   _pacer(NULL),
 474   _verifier(NULL),
 475   _phase_timings(NULL),
 476   _monitoring_support(NULL),
 477   _memory_pool(NULL),


 478   _stw_memory_manager("Shenandoah Pauses", "end of GC pause"),
 479   _cycle_memory_manager("Shenandoah Cycles", "end of GC cycle"),
 480   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 481   _soft_ref_policy(),
 482   _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
 483   _ref_processor(new ShenandoahReferenceProcessor(MAX2(_max_workers, 1U))),
 484   _marking_context(NULL),
 485   _bitmap_size(0),
 486   _bitmap_regions_per_slice(0),
 487   _bitmap_bytes_per_slice(0),
 488   _bitmap_region_special(false),
 489   _aux_bitmap_region_special(false),
 490   _liveness_cache(NULL),
 491   _collection_set(NULL)

 492 {
 493   // Initialize GC mode early, so we can adjust barrier support
 494   initialize_mode();
 495   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this));
 496 
 497   _max_workers = MAX2(_max_workers, 1U);
 498   _workers = new ShenandoahWorkerThreads("Shenandoah GC Threads", _max_workers);
 499   if (_workers == NULL) {
 500     vm_exit_during_initialization("Failed necessary allocation.");
 501   } else {
 502     _workers->initialize_workers();
 503   }
 504 
 505   if (ParallelGCThreads > 1) {
 506     _safepoint_workers = new ShenandoahWorkerThreads("Safepoint Cleanup Thread",
 507                                                 ParallelGCThreads);
 508     _safepoint_workers->initialize_workers();
 509   }
 510 }
 511 
 512 #ifdef _MSC_VER
 513 #pragma warning( pop )
 514 #endif
 515 
 516 class ShenandoahResetBitmapTask : public WorkerTask {
 517 private:
 518   ShenandoahRegionIterator _regions;
 519 
 520 public:
 521   ShenandoahResetBitmapTask() :
 522     WorkerTask("Shenandoah Reset Bitmap") {}
 523 
 524   void work(uint worker_id) {
 525     ShenandoahHeapRegion* region = _regions.next();
 526     ShenandoahHeap* heap = ShenandoahHeap::heap();
 527     ShenandoahMarkingContext* const ctx = heap->marking_context();
 528     while (region != NULL) {
 529       if (heap->is_bitmap_slice_committed(region)) {
 530         ctx->clear_bitmap(region);
 531       }
 532       region = _regions.next();
 533     }
 534   }
 535 };
 536 
 537 void ShenandoahHeap::reset_mark_bitmap() {
 538   assert_gc_workers(_workers->active_workers());
 539   mark_incomplete_marking_context();
 540 
 541   ShenandoahResetBitmapTask task;
 542   _workers->run_task(&task);
 543 }
 544 
 545 void ShenandoahHeap::print_on(outputStream* st) const {
 546   st->print_cr("Shenandoah Heap");
 547   st->print_cr(" " SIZE_FORMAT "%s max, " SIZE_FORMAT "%s soft max, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
 548                byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
 549                byte_size_in_proper_unit(soft_max_capacity()), proper_unit_for_byte_size(soft_max_capacity()),
 550                byte_size_in_proper_unit(committed()),    proper_unit_for_byte_size(committed()),
 551                byte_size_in_proper_unit(used()),         proper_unit_for_byte_size(used()));
 552   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
 553                num_regions(),
 554                byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
 555                proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
 556 
 557   st->print("Status: ");
 558   if (has_forwarded_objects())                 st->print("has forwarded objects, ");
 559   if (is_concurrent_mark_in_progress())        st->print("marking, ");

 560   if (is_evacuation_in_progress())             st->print("evacuating, ");
 561   if (is_update_refs_in_progress())            st->print("updating refs, ");
 562   if (is_degenerated_gc_in_progress())         st->print("degenerated gc, ");
 563   if (is_full_gc_in_progress())                st->print("full gc, ");
 564   if (is_full_gc_move_in_progress())           st->print("full gc move, ");
 565   if (is_concurrent_weak_root_in_progress())   st->print("concurrent weak roots, ");
 566   if (is_concurrent_strong_root_in_progress() &&
 567       !is_concurrent_weak_root_in_progress())  st->print("concurrent strong roots, ");
 568 
 569   if (cancelled_gc()) {
 570     st->print("cancelled");
 571   } else {
 572     st->print("not cancelled");
 573   }
 574   st->cr();
 575 
 576   st->print_cr("Reserved region:");
 577   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 578                p2i(reserved_region().start()),
 579                p2i(reserved_region().end()));

 602     assert(thread->is_Worker_thread(), "Only worker thread expected");
 603     ShenandoahThreadLocalData::initialize_gclab(thread);
 604   }
 605 };
 606 
 607 void ShenandoahHeap::post_initialize() {
 608   CollectedHeap::post_initialize();
 609   MutexLocker ml(Threads_lock);
 610 
 611   ShenandoahInitWorkerGCLABClosure init_gclabs;
 612   _workers->threads_do(&init_gclabs);
 613 
 614   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 615   // Now, we will let WorkerThreads to initialize gclab when new worker is created.
 616   _workers->set_initialize_gclab();
 617   if (_safepoint_workers != NULL) {
 618     _safepoint_workers->threads_do(&init_gclabs);
 619     _safepoint_workers->set_initialize_gclab();
 620   }
 621 
 622   _heuristics->initialize();
 623 
 624   JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());
 625 }
 626 







































 627 size_t ShenandoahHeap::used() const {
 628   return Atomic::load(&_used);
 629 }
 630 
 631 size_t ShenandoahHeap::committed() const {
 632   return Atomic::load(&_committed);
 633 }
 634 
 635 void ShenandoahHeap::increase_committed(size_t bytes) {
 636   shenandoah_assert_heaplocked_or_safepoint();
 637   _committed += bytes;
 638 }
 639 
 640 void ShenandoahHeap::decrease_committed(size_t bytes) {
 641   shenandoah_assert_heaplocked_or_safepoint();
 642   _committed -= bytes;
 643 }
 644 
 645 void ShenandoahHeap::increase_used(size_t bytes) {
 646   Atomic::add(&_used, bytes, memory_order_relaxed);
 647 }
 648 
 649 void ShenandoahHeap::set_used(size_t bytes) {
 650   Atomic::store(&_used, bytes);
 651 }
 652 
 653 void ShenandoahHeap::decrease_used(size_t bytes) {
 654   assert(used() >= bytes, "never decrease heap size by more than we've left");
 655   Atomic::sub(&_used, bytes, memory_order_relaxed);
 656 }
 657 
 658 void ShenandoahHeap::increase_allocated(size_t bytes) {
 659   Atomic::add(&_bytes_allocated_since_gc_start, bytes, memory_order_relaxed);
 660 }
 661 
 662 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
 663   size_t bytes = words * HeapWordSize;
 664   if (!waste) {
 665     increase_used(bytes);
 666   }
 667   increase_allocated(bytes);
 668   if (ShenandoahPacing) {
 669     control_thread()->pacing_notify_alloc(words);
 670     if (waste) {
 671       pacer()->claim_for_alloc(words, true);
 672     }
 673   }
 674 }
 675 
 676 size_t ShenandoahHeap::capacity() const {
 677   return committed();
 678 }
 679 
 680 size_t ShenandoahHeap::max_capacity() const {
 681   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 682 }
 683 
 684 size_t ShenandoahHeap::soft_max_capacity() const {
 685   size_t v = Atomic::load(&_soft_max_size);
 686   assert(min_capacity() <= v && v <= max_capacity(),
 687          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 688          min_capacity(), v, max_capacity());
 689   return v;
 690 }
 691 
 692 void ShenandoahHeap::set_soft_max_capacity(size_t v) {
 693   assert(min_capacity() <= v && v <= max_capacity(),
 694          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 695          min_capacity(), v, max_capacity());
 696   Atomic::store(&_soft_max_size, v);







 697 }
 698 
 699 size_t ShenandoahHeap::min_capacity() const {
 700   return _minimum_size;
 701 }
 702 
 703 size_t ShenandoahHeap::initial_capacity() const {
 704   return _initial_size;
 705 }
 706 
 707 bool ShenandoahHeap::is_in(const void* p) const {
 708   HeapWord* heap_base = (HeapWord*) base();
 709   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 710   return p >= heap_base && p < last_region_end;
 711 }
 712 























 713 void ShenandoahHeap::op_uncommit(double shrink_before, size_t shrink_until) {
 714   assert (ShenandoahUncommit, "should be enabled");
 715 
 716   // Application allocates from the beginning of the heap, and GC allocates at
 717   // the end of it. It is more efficient to uncommit from the end, so that applications
 718   // could enjoy the near committed regions. GC allocations are much less frequent,
 719   // and therefore can accept the committing costs.
 720 
 721   size_t count = 0;
 722   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
 723     ShenandoahHeapRegion* r = get_region(i - 1);
 724     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
 725       ShenandoahHeapLocker locker(lock());
 726       if (r->is_empty_committed()) {
 727         if (committed() < shrink_until + ShenandoahHeapRegion::region_size_bytes()) {
 728           break;
 729         }
 730 
 731         r->make_uncommitted();
 732         count++;
 733       }
 734     }
 735     SpinPause(); // allow allocators to take the lock
 736   }
 737 
 738   if (count > 0) {
 739     control_thread()->notify_heap_changed();























 740   }
 741 }
 742 




 743 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 744   // New object should fit the GCLAB size
 745   size_t min_size = MAX2(size, PLAB::min_size());
 746 
 747   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
 748   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;






 749   new_size = MIN2(new_size, PLAB::max_size());
 750   new_size = MAX2(new_size, PLAB::min_size());
 751 
 752   // Record new heuristic value even if we take any shortcut. This captures
 753   // the case when moderately-sized objects always take a shortcut. At some point,
 754   // heuristics should catch up with them.
 755   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
 756 
 757   if (new_size < size) {
 758     // New size still does not fit the object. Fall back to shared allocation.
 759     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
 760     return NULL;
 761   }
 762 
 763   // Retire current GCLAB, and allocate a new one.
 764   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 765   gclab->retire();
 766 
 767   size_t actual_size = 0;
 768   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);

 772 
 773   assert (size <= actual_size, "allocation should fit");
 774 
 775   if (ZeroTLAB) {
 776     // ..and clear it.
 777     Copy::zero_to_words(gclab_buf, actual_size);
 778   } else {
 779     // ...and zap just allocated object.
 780 #ifdef ASSERT
 781     // Skip mangling the space corresponding to the object header to
 782     // ensure that the returned space is not considered parsable by
 783     // any concurrent GC thread.
 784     size_t hdr_size = oopDesc::header_size();
 785     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 786 #endif // ASSERT
 787   }
 788   gclab->set_buf(gclab_buf, actual_size);
 789   return gclab->allocate(size);
 790 }
 791 













































































































































 792 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
 793                                             size_t requested_size,
 794                                             size_t* actual_size) {
 795   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
 796   HeapWord* res = allocate_memory(req);
 797   if (res != NULL) {
 798     *actual_size = req.actual_size();
 799   } else {
 800     *actual_size = 0;
 801   }
 802   return res;
 803 }
 804 
 805 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
 806                                              size_t word_size,
 807                                              size_t* actual_size) {
 808   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
 809   HeapWord* res = allocate_memory(req);
 810   if (res != NULL) {
 811     *actual_size = req.actual_size();
 812   } else {
 813     *actual_size = 0;
 814   }
 815   return res;
 816 }
 817 
 818 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {

















 819   intptr_t pacer_epoch = 0;
 820   bool in_new_region = false;
 821   HeapWord* result = NULL;
 822 
 823   if (req.is_mutator_alloc()) {
 824     if (ShenandoahPacing) {
 825       pacer()->pace_for_alloc(req.size());
 826       pacer_epoch = pacer()->epoch();
 827     }
 828 
 829     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
 830       result = allocate_memory_under_lock(req, in_new_region);
 831     }
 832 
 833     // Allocation failed, block until control thread reacted, then retry allocation.
 834     //
 835     // It might happen that one of the threads requesting allocation would unblock
 836     // way later after GC happened, only to fail the second allocation, because
 837     // other threads have already depleted the free storage. In this case, a better
 838     // strategy is to try again, as long as GC makes progress.
 839     //
 840     // Then, we need to make sure the allocation was retried after at least one
 841     // Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
 842 
 843     size_t tries = 0;
 844 
 845     while (result == NULL && _progress_last_gc.is_set()) {
 846       tries++;
 847       control_thread()->handle_alloc_failure(req);
 848       result = allocate_memory_under_lock(req, in_new_region);
 849     }
 850 
 851     while (result == NULL && tries <= ShenandoahFullGCThreshold) {
 852       tries++;
 853       control_thread()->handle_alloc_failure(req);
 854       result = allocate_memory_under_lock(req, in_new_region);
 855     }
 856 
 857   } else {
 858     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
 859     result = allocate_memory_under_lock(req, in_new_region);
 860     // Do not call handle_alloc_failure() here, because we cannot block.
 861     // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
 862   }
 863 
 864   if (in_new_region) {
 865     control_thread()->notify_heap_changed();

 866   }
 867 
 868   if (result != NULL) {

 869     size_t requested = req.size();
 870     size_t actual = req.actual_size();

 871 
 872     assert (req.is_lab_alloc() || (requested == actual),
 873             "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
 874             ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
 875 
 876     if (req.is_mutator_alloc()) {
 877       notify_mutator_alloc_words(actual, false);

 878 
 879       // If we requested more than we were granted, give the rest back to pacer.
 880       // This only matters if we are in the same pacing epoch: do not try to unpace
 881       // over the budget for the other phase.
 882       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
 883         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
 884       }
 885     } else {
 886       increase_used(actual*HeapWordSize);
 887     }
 888   }
 889 
 890   return result;
 891 }
 892 
 893 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {


 894   ShenandoahHeapLocker locker(lock());
 895   return _free_set->allocate(req, in_new_region);




































































 896 }
 897 
 898 HeapWord* ShenandoahHeap::mem_allocate(size_t size,
 899                                         bool*  gc_overhead_limit_was_exceeded) {
 900   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
 901   return allocate_memory(req);
 902 }
 903 
 904 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
 905                                                              size_t size,
 906                                                              Metaspace::MetadataType mdtype) {
 907   MetaWord* result;
 908 
 909   // Inform metaspace OOM to GC heuristics if class unloading is possible.
 910   if (heuristics()->can_unload_classes()) {
 911     ShenandoahHeuristics* h = heuristics();
 912     h->record_metaspace_oom();
 913   }
 914 
 915   // Expand and retry allocation
 916   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
 917   if (result != NULL) {
 918     return result;
 919   }
 920 
 921   // Start full GC
 922   collect(GCCause::_metadata_GC_clear_soft_refs);
 923 
 924   // Retry allocation
 925   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
 926   if (result != NULL) {
 927     return result;
 928   }
 929 
 930   // Expand and retry allocation
 931   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);

 970 
 971   void work(uint worker_id) {
 972     if (_concurrent) {
 973       ShenandoahConcurrentWorkerSession worker_session(worker_id);
 974       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
 975       ShenandoahEvacOOMScope oom_evac_scope;
 976       do_work();
 977     } else {
 978       ShenandoahParallelWorkerSession worker_session(worker_id);
 979       ShenandoahEvacOOMScope oom_evac_scope;
 980       do_work();
 981     }
 982   }
 983 
 984 private:
 985   void do_work() {
 986     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
 987     ShenandoahHeapRegion* r;
 988     while ((r =_cs->claim_next()) != NULL) {
 989       assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());

 990       _sh->marked_object_iterate(r, &cl);
 991 
 992       if (ShenandoahPacing) {
 993         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
 994       }




























































 995 
 996       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
 997         break;
 998       }
 999     }
1000   }
1001 };
1002 
1003 void ShenandoahHeap::evacuate_collection_set(bool concurrent) {
1004   ShenandoahEvacuationTask task(this, _collection_set, concurrent);
1005   workers()->run_task(&task);






1006 }
1007 
1008 void ShenandoahHeap::trash_cset_regions() {
1009   ShenandoahHeapLocker locker(lock());
1010 
1011   ShenandoahCollectionSet* set = collection_set();
1012   ShenandoahHeapRegion* r;
1013   set->clear_current_index();
1014   while ((r = set->next()) != NULL) {
1015     r->make_trash();
1016   }
1017   collection_set()->clear();
1018 }
1019 
1020 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1021   st->print_cr("Heap Regions:");
1022   st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
1023   st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
1024   st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start, UWM=update watermark");
1025   st->print_cr("SN=alloc sequence number");
1026 
1027   for (size_t i = 0; i < num_regions(); i++) {
1028     get_region(i)->print_on(st);
1029   }
1030 }
1031 
1032 void ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
1033   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1034 
1035   oop humongous_obj = cast_to_oop(start->bottom());
1036   size_t size = humongous_obj->size();
1037   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
1038   size_t index = start->index() + required_regions - 1;
1039 
1040   assert(!start->has_live(), "liveness must be zero");
1041 
1042   for(size_t i = 0; i < required_regions; i++) {
1043     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
1044     // as it expects that every region belongs to a humongous region starting with a humongous start region.
1045     ShenandoahHeapRegion* region = get_region(index --);
1046 
1047     assert(region->is_humongous(), "expect correct humongous start or continuation");
1048     assert(!region->is_cset(), "Humongous region should not be in collection set");
1049 
1050     region->make_trash_immediate();
1051   }

1052 }
1053 
1054 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {
1055 public:
1056   ShenandoahCheckCleanGCLABClosure() {}
1057   void do_thread(Thread* thread) {
1058     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1059     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1060     assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");




1061   }
1062 };
1063 
1064 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1065 private:
1066   bool const _resize;
1067 public:
1068   ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}
1069   void do_thread(Thread* thread) {
1070     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1071     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1072     gclab->retire();
1073     if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1074       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1075     }












1076   }
1077 };
1078 
1079 void ShenandoahHeap::labs_make_parsable() {
1080   assert(UseTLAB, "Only call with UseTLAB");
1081 
1082   ShenandoahRetireGCLABClosure cl(false);
1083 
1084   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1085     ThreadLocalAllocBuffer& tlab = t->tlab();
1086     tlab.make_parsable();
1087     cl.do_thread(t);
1088   }
1089 
1090   workers()->threads_do(&cl);
1091 }
1092 
1093 void ShenandoahHeap::tlabs_retire(bool resize) {
1094   assert(UseTLAB, "Only call with UseTLAB");
1095   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");

1113   }
1114   workers()->threads_do(&cl);
1115 #endif
1116 }
1117 
1118 void ShenandoahHeap::gclabs_retire(bool resize) {
1119   assert(UseTLAB, "Only call with UseTLAB");
1120   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1121 
1122   ShenandoahRetireGCLABClosure cl(resize);
1123   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1124     cl.do_thread(t);
1125   }
1126   workers()->threads_do(&cl);
1127 
1128   if (safepoint_workers() != NULL) {
1129     safepoint_workers()->threads_do(&cl);
1130   }
1131 }
1132 































1133 // Returns size in bytes
1134 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1135   if (ShenandoahElasticTLAB) {
1136     // With Elastic TLABs, return the max allowed size, and let the allocation path
1137     // figure out the safe size for current allocation.
1138     return ShenandoahHeapRegion::max_tlab_size_bytes();
1139   } else {
1140     return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1141   }
1142 }
1143 
1144 size_t ShenandoahHeap::max_tlab_size() const {
1145   // Returns size in words
1146   return ShenandoahHeapRegion::max_tlab_size_words();
1147 }
1148 
1149 void ShenandoahHeap::collect(GCCause::Cause cause) {
1150   control_thread()->request_gc(cause);
1151 }
1152 

1509       if (start >= max) break;
1510 
1511       for (size_t i = cur; i < end; i++) {
1512         ShenandoahHeapRegion* current = _heap->get_region(i);
1513         _blk->heap_region_do(current);
1514       }
1515     }
1516   }
1517 };
1518 
1519 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1520   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1521   if (num_regions() > ShenandoahParallelRegionStride) {
1522     ShenandoahParallelHeapRegionTask task(blk);
1523     workers()->run_task(&task);
1524   } else {
1525     heap_region_iterate(blk);
1526   }
1527 }
1528 
1529 class ShenandoahInitMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1530 private:
1531   ShenandoahMarkingContext* const _ctx;
1532 public:
1533   ShenandoahInitMarkUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1534 
1535   void heap_region_do(ShenandoahHeapRegion* r) {
1536     assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());
1537     if (r->is_active()) {
1538       // Check if region needs updating its TAMS. We have updated it already during concurrent
1539       // reset, so it is very likely we don't need to do another write here.
1540       if (_ctx->top_at_mark_start(r) != r->top()) {
1541         _ctx->capture_top_at_mark_start(r);
1542       }
1543     } else {
1544       assert(_ctx->top_at_mark_start(r) == r->top(),
1545              "Region " SIZE_FORMAT " should already have correct TAMS", r->index());
1546     }
1547   }
1548 
1549   bool is_thread_safe() { return true; }
1550 };
1551 
1552 class ShenandoahRendezvousClosure : public HandshakeClosure {
1553 public:
1554   inline ShenandoahRendezvousClosure() : HandshakeClosure("ShenandoahRendezvous") {}
1555   inline void do_thread(Thread* thread) {}
1556 };
1557 
1558 void ShenandoahHeap::rendezvous_threads() {
1559   ShenandoahRendezvousClosure cl;
1560   Handshake::execute(&cl);
1561 }
1562 
1563 void ShenandoahHeap::recycle_trash() {
1564   free_set()->recycle_trash();
1565 }
1566 
1567 class ShenandoahResetUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1568 private:
1569   ShenandoahMarkingContext* const _ctx;
1570 public:
1571   ShenandoahResetUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1572 
1573   void heap_region_do(ShenandoahHeapRegion* r) {
1574     if (r->is_active()) {
1575       // Reset live data and set TAMS optimistically. We would recheck these under the pause
1576       // anyway to capture any updates that happened since now.
1577       r->clear_live_data();
1578       _ctx->capture_top_at_mark_start(r);
1579     }
1580   }
1581 
1582   bool is_thread_safe() { return true; }
1583 };
1584 
1585 void ShenandoahHeap::prepare_gc() {
1586   reset_mark_bitmap();
1587 
1588   ShenandoahResetUpdateRegionStateClosure cl;
1589   parallel_heap_region_iterate(&cl);
1590 }
1591 
1592 class ShenandoahFinalMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1593 private:
1594   ShenandoahMarkingContext* const _ctx;
1595   ShenandoahHeapLock* const _lock;
1596 
1597 public:
1598   ShenandoahFinalMarkUpdateRegionStateClosure() :
1599     _ctx(ShenandoahHeap::heap()->complete_marking_context()), _lock(ShenandoahHeap::heap()->lock()) {}
1600 
1601   void heap_region_do(ShenandoahHeapRegion* r) {
1602     if (r->is_active()) {
1603       // All allocations past TAMS are implicitly live, adjust the region data.
1604       // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1605       HeapWord *tams = _ctx->top_at_mark_start(r);
1606       HeapWord *top = r->top();
1607       if (top > tams) {
1608         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1609       }
1610 
1611       // We are about to select the collection set, make sure it knows about
1612       // current pinning status. Also, this allows trashing more regions that
1613       // now have their pinning status dropped.
1614       if (r->is_pinned()) {
1615         if (r->pin_count() == 0) {
1616           ShenandoahHeapLocker locker(_lock);
1617           r->make_unpinned();
1618         }
1619       } else {
1620         if (r->pin_count() > 0) {
1621           ShenandoahHeapLocker locker(_lock);
1622           r->make_pinned();
1623         }
1624       }
1625 
1626       // Remember limit for updating refs. It's guaranteed that we get no
1627       // from-space-refs written from here on.
1628       r->set_update_watermark_at_safepoint(r->top());
1629     } else {
1630       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());
1631       assert(_ctx->top_at_mark_start(r) == r->top(),
1632              "Region " SIZE_FORMAT " should have correct TAMS", r->index());
1633     }
1634   }
1635 
1636   bool is_thread_safe() { return true; }
1637 };
1638 
1639 void ShenandoahHeap::prepare_regions_and_collection_set(bool concurrent) {
1640   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
1641   {
1642     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_update_region_states :
1643                                          ShenandoahPhaseTimings::degen_gc_final_update_region_states);
1644     ShenandoahFinalMarkUpdateRegionStateClosure cl;
1645     parallel_heap_region_iterate(&cl);
1646 
1647     assert_pinned_region_status();
1648   }
1649 
1650   {
1651     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::choose_cset :
1652                                          ShenandoahPhaseTimings::degen_gc_choose_cset);
1653     ShenandoahHeapLocker locker(lock());
1654     _collection_set->clear();
1655     heuristics()->choose_collection_set(_collection_set);
1656   }
1657 
1658   {
1659     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_rebuild_freeset :
1660                                          ShenandoahPhaseTimings::degen_gc_final_rebuild_freeset);
1661     ShenandoahHeapLocker locker(lock());
1662     _free_set->rebuild();
1663   }
1664 }
1665 
1666 void ShenandoahHeap::do_class_unloading() {
1667   _unloader.unload();
1668 }
1669 
1670 void ShenandoahHeap::stw_weak_refs(bool full_gc) {
1671   // Weak refs processing
1672   ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs
1673                                                 : ShenandoahPhaseTimings::degen_gc_weakrefs;
1674   ShenandoahTimingsTracker t(phase);
1675   ShenandoahGCWorkerPhase worker_phase(phase);
1676   ref_processor()->process_references(phase, workers(), false /* concurrent */);
1677 }
1678 
1679 void ShenandoahHeap::prepare_update_heap_references(bool concurrent) {
1680   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
1681 
1682   // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to
1683   // make them parsable for update code to work correctly. Plus, we can compute new sizes
1684   // for future GCLABs here.
1685   if (UseTLAB) {
1686     ShenandoahGCPhase phase(concurrent ?
1687                             ShenandoahPhaseTimings::init_update_refs_manage_gclabs :
1688                             ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);
1689     gclabs_retire(ResizeTLAB);
1690   }
1691 
1692   _update_refs_iterator.reset();
1693 }
1694 
1695 void ShenandoahHeap::set_gc_state_all_threads(char state) {
1696   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1697     ShenandoahThreadLocalData::set_gc_state(t, state);
1698   }
1699 }
1700 
1701 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1702   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1703   _gc_state.set_cond(mask, value);
1704   set_gc_state_all_threads(_gc_state.raw_value());
1705 }
1706 
1707 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1708   assert(!has_forwarded_objects(), "Not expected before/after mark phase");
1709   set_gc_state_mask(MARKING, in_progress);
1710   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);












































1711 }
1712 
1713 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1714   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1715   set_gc_state_mask(EVACUATION, in_progress);
1716 }
1717 
1718 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {
1719   if (in_progress) {
1720     _concurrent_strong_root_in_progress.set();
1721   } else {
1722     _concurrent_strong_root_in_progress.unset();
1723   }
1724 }
1725 
1726 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {
1727   set_gc_state_mask(WEAK_ROOTS, cond);
1728 }
1729 
1730 GCTracer* ShenandoahHeap::tracer() {

1735   return _free_set->used();
1736 }
1737 
1738 bool ShenandoahHeap::try_cancel_gc() {
1739   while (true) {
1740     jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
1741     if (prev == CANCELLABLE) return true;
1742     else if (prev == CANCELLED) return false;
1743     assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");
1744     assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");
1745     Thread* thread = Thread::current();
1746     if (thread->is_Java_thread()) {
1747       // We need to provide a safepoint here, otherwise we might
1748       // spin forever if a SP is pending.
1749       ThreadBlockInVM sp(JavaThread::cast(thread));
1750       SpinPause();
1751     }
1752   }
1753 }
1754 








1755 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1756   if (try_cancel_gc()) {
1757     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1758     log_info(gc)("%s", msg.buffer());
1759     Events::log(Thread::current(), "%s", msg.buffer());




1760   }
1761 }
1762 
1763 uint ShenandoahHeap::max_workers() {
1764   return _max_workers;
1765 }
1766 
1767 void ShenandoahHeap::stop() {
1768   // The shutdown sequence should be able to terminate when GC is running.
1769 



1770   // Step 0. Notify policy to disable event recording.
1771   _shenandoah_policy->record_shutdown();
1772 
1773   // Step 1. Notify control thread that we are in shutdown.
1774   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1775   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1776   control_thread()->prepare_for_graceful_shutdown();
1777 
1778   // Step 2. Notify GC workers that we are cancelling GC.
1779   cancel_gc(GCCause::_shenandoah_stop_vm);
1780 
1781   // Step 3. Wait until GC worker exits normally.
1782   control_thread()->stop();
1783 }
1784 
1785 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
1786   if (!unload_classes()) return;
1787   // Unload classes and purge SystemDictionary.
1788   {
1789     ShenandoahPhaseTimings::Phase phase = full_gc ?

1854 }
1855 
1856 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
1857   set_gc_state_mask(HAS_FORWARDED, cond);
1858 }
1859 
1860 void ShenandoahHeap::set_unload_classes(bool uc) {
1861   _unload_classes.set_cond(uc);
1862 }
1863 
1864 bool ShenandoahHeap::unload_classes() const {
1865   return _unload_classes.is_set();
1866 }
1867 
1868 address ShenandoahHeap::in_cset_fast_test_addr() {
1869   ShenandoahHeap* heap = ShenandoahHeap::heap();
1870   assert(heap->collection_set() != NULL, "Sanity");
1871   return (address) heap->collection_set()->biased_map_address();
1872 }
1873 
1874 address ShenandoahHeap::cancelled_gc_addr() {
1875   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
1876 }
1877 
1878 address ShenandoahHeap::gc_state_addr() {
1879   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
1880 }
1881 
1882 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
1883   return Atomic::load(&_bytes_allocated_since_gc_start);
1884 }
1885 
1886 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
1887   Atomic::store(&_bytes_allocated_since_gc_start, (size_t)0);





1888 }
1889 
1890 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
1891   _degenerated_gc_in_progress.set_cond(in_progress);
1892 }
1893 
1894 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
1895   _full_gc_in_progress.set_cond(in_progress);
1896 }
1897 
1898 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
1899   assert (is_full_gc_in_progress(), "should be");
1900   _full_gc_move_in_progress.set_cond(in_progress);
1901 }
1902 
1903 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
1904   set_gc_state_mask(UPDATEREFS, in_progress);
1905 }
1906 
1907 void ShenandoahHeap::register_nmethod(nmethod* nm) {

1936     if (r->is_active()) {
1937       if (r->is_pinned()) {
1938         if (r->pin_count() == 0) {
1939           r->make_unpinned();
1940         }
1941       } else {
1942         if (r->pin_count() > 0) {
1943           r->make_pinned();
1944         }
1945       }
1946     }
1947   }
1948 
1949   assert_pinned_region_status();
1950 }
1951 
1952 #ifdef ASSERT
1953 void ShenandoahHeap::assert_pinned_region_status() {
1954   for (size_t i = 0; i < num_regions(); i++) {
1955     ShenandoahHeapRegion* r = get_region(i);
1956     assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
1957            "Region " SIZE_FORMAT " pinning status is inconsistent", i);


1958   }
1959 }
1960 #endif
1961 
1962 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {
1963   return _gc_timer;
1964 }
1965 
1966 void ShenandoahHeap::prepare_concurrent_roots() {
1967   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
1968   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
1969   set_concurrent_strong_root_in_progress(!collection_set()->is_empty());
1970   set_concurrent_weak_root_in_progress(true);
1971   if (unload_classes()) {
1972     _unloader.prepare();
1973   }
1974 }
1975 
1976 void ShenandoahHeap::finish_concurrent_roots() {
1977   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");

1997       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
1998     } else {
1999       // Use ConcGCThreads outside safepoints
2000       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2001     }
2002   }
2003 }
2004 #endif
2005 
2006 ShenandoahVerifier* ShenandoahHeap::verifier() {
2007   guarantee(ShenandoahVerify, "Should be enabled");
2008   assert (_verifier != NULL, "sanity");
2009   return _verifier;
2010 }
2011 
2012 template<bool CONCURRENT>
2013 class ShenandoahUpdateHeapRefsTask : public WorkerTask {
2014 private:
2015   ShenandoahHeap* _heap;
2016   ShenandoahRegionIterator* _regions;

2017 public:
2018   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :
2019     WorkerTask("Shenandoah Update References"),
2020     _heap(ShenandoahHeap::heap()),
2021     _regions(regions) {

2022   }
2023 
2024   void work(uint worker_id) {
2025     if (CONCURRENT) {
2026       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2027       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2028       do_work<ShenandoahConcUpdateRefsClosure>();
2029     } else {
2030       ShenandoahParallelWorkerSession worker_session(worker_id);
2031       do_work<ShenandoahSTWUpdateRefsClosure>();
2032     }
2033   }
2034 
2035 private:
2036   template<class T>
2037   void do_work() {
2038     T cl;
2039     ShenandoahHeapRegion* r = _regions->next();
2040     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();




2041     while (r != NULL) {
2042       HeapWord* update_watermark = r->get_update_watermark();
2043       assert (update_watermark >= r->bottom(), "sanity");


2044       if (r->is_active() && !r->is_cset()) {
2045         _heap->marked_object_oop_iterate(r, &cl, update_watermark);


































































2046       }
2047       if (ShenandoahPacing) {
2048         _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom()));
2049       }
2050       if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
2051         return;
2052       }
2053       r = _regions->next();
2054     }
2055   }
2056 };
2057 
2058 void ShenandoahHeap::update_heap_references(bool concurrent) {
2059   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2060 
2061   if (concurrent) {
2062     ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);
2063     workers()->run_task(&task);
2064   } else {
2065     ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);
2066     workers()->run_task(&task);
2067   }
2068 }
2069 
2070 
2071 class ShenandoahFinalUpdateRefsUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
2072 private:

2073   ShenandoahHeapLock* const _lock;

2074 
2075 public:
2076   ShenandoahFinalUpdateRefsUpdateRegionStateClosure() : _lock(ShenandoahHeap::heap()->lock()) {}


2077 
2078   void heap_region_do(ShenandoahHeapRegion* r) {





















2079     // Drop unnecessary "pinned" state from regions that does not have CP marks
2080     // anymore, as this would allow trashing them.
2081 
2082     if (r->is_active()) {
2083       if (r->is_pinned()) {
2084         if (r->pin_count() == 0) {
2085           ShenandoahHeapLocker locker(_lock);
2086           r->make_unpinned();
2087         }
2088       } else {
2089         if (r->pin_count() > 0) {
2090           ShenandoahHeapLocker locker(_lock);
2091           r->make_pinned();
2092         }
2093       }
2094     }
2095   }
2096 
2097   bool is_thread_safe() { return true; }
2098 };
2099 
2100 void ShenandoahHeap::update_heap_region_states(bool concurrent) {
2101   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2102   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2103 
2104   {
2105     ShenandoahGCPhase phase(concurrent ?
2106                             ShenandoahPhaseTimings::final_update_refs_update_region_states :
2107                             ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);
2108     ShenandoahFinalUpdateRefsUpdateRegionStateClosure cl;
2109     parallel_heap_region_iterate(&cl);
2110 
2111     assert_pinned_region_status();
2112   }
2113 
2114   {
2115     ShenandoahGCPhase phase(concurrent ?
2116                             ShenandoahPhaseTimings::final_update_refs_trash_cset :
2117                             ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);
2118     trash_cset_regions();
2119   }
2120 }
2121 
2122 void ShenandoahHeap::rebuild_free_set(bool concurrent) {
2123   {
2124     ShenandoahGCPhase phase(concurrent ?
2125                             ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :
2126                             ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);
2127     ShenandoahHeapLocker locker(lock());
2128     _free_set->rebuild();

2222   EventMark em("%s", msg);
2223 
2224   op_uncommit(shrink_before, shrink_until);
2225 }
2226 
2227 void ShenandoahHeap::try_inject_alloc_failure() {
2228   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2229     _inject_alloc_failure.set();
2230     os::naked_short_sleep(1);
2231     if (cancelled_gc()) {
2232       log_info(gc)("Allocation failure was successfully injected");
2233     }
2234   }
2235 }
2236 
2237 bool ShenandoahHeap::should_inject_alloc_failure() {
2238   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2239 }
2240 
2241 void ShenandoahHeap::initialize_serviceability() {
2242   _memory_pool = new ShenandoahMemoryPool(this);
2243   _cycle_memory_manager.add_pool(_memory_pool);
2244   _stw_memory_manager.add_pool(_memory_pool);









2245 }
2246 
2247 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2248   GrowableArray<GCMemoryManager*> memory_managers(2);
2249   memory_managers.append(&_cycle_memory_manager);
2250   memory_managers.append(&_stw_memory_manager);
2251   return memory_managers;
2252 }
2253 
2254 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2255   GrowableArray<MemoryPool*> memory_pools(1);
2256   memory_pools.append(_memory_pool);





2257   return memory_pools;
2258 }
2259 
2260 MemoryUsage ShenandoahHeap::memory_usage() {
2261   return _memory_pool->get_memory_usage();
2262 }
2263 
2264 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2265   _heap(ShenandoahHeap::heap()),
2266   _index(0) {}
2267 
2268 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2269   _heap(heap),
2270   _index(0) {}
2271 
2272 void ShenandoahRegionIterator::reset() {
2273   _index = 0;
2274 }
2275 
2276 bool ShenandoahRegionIterator::has_next() const {
2277   return _index < _heap->num_regions();
2278 }
2279 
2280 char ShenandoahHeap::gc_state() const {
2281   return _gc_state.raw_value();
2282 }
2283 
2284 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2285 #ifdef ASSERT
2286   assert(_liveness_cache != NULL, "sanity");
2287   assert(worker_id < _max_workers, "sanity");
2288   for (uint i = 0; i < num_regions(); i++) {
2289     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2290   }
2291 #endif
2292   return _liveness_cache[worker_id];
2293 }
2294 
2295 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2296   assert(worker_id < _max_workers, "sanity");
2297   assert(_liveness_cache != NULL, "sanity");
2298   ShenandoahLiveData* ld = _liveness_cache[worker_id];

2299   for (uint i = 0; i < num_regions(); i++) {
2300     ShenandoahLiveData live = ld[i];
2301     if (live > 0) {
2302       ShenandoahHeapRegion* r = get_region(i);
2303       r->increase_live_data_gc_words(live);
2304       ld[i] = 0;
2305     }
2306   }
2307 }















































































































































































































  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 "memory/allocation.hpp"
  27 #include "memory/universe.hpp"
  28 
  29 #include "gc/shared/gcArguments.hpp"
  30 #include "gc/shared/gcTimer.hpp"
  31 #include "gc/shared/gcTraceTime.inline.hpp"
  32 #include "gc/shared/locationPrinter.inline.hpp"
  33 #include "gc/shared/memAllocator.hpp"
  34 #include "gc/shared/plab.hpp"
  35 #include "gc/shared/tlab_globals.hpp"
  36 
  37 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  38 #include "gc/shenandoah/shenandoahCardTable.hpp"
  39 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  40 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  41 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  42 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
  43 #include "gc/shenandoah/shenandoahControlThread.hpp"
  44 #include "gc/shenandoah/shenandoahRegulatorThread.hpp"
  45 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  46 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp"
  47 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  48 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  49 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  50 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  51 #include "gc/shenandoah/shenandoahInitLogger.hpp"
  52 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  53 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  54 #include "gc/shenandoah/shenandoahMetrics.hpp"
  55 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  56 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  57 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  58 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
  59 #include "gc/shenandoah/shenandoahPadding.hpp"
  60 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
  61 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  62 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  63 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
  64 #include "gc/shenandoah/shenandoahStringDedup.hpp"
  65 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  66 #include "gc/shenandoah/shenandoahUtils.hpp"
  67 #include "gc/shenandoah/shenandoahVerifier.hpp"
  68 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  69 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  70 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  71 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  72 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  73 #include "gc/shenandoah/mode/shenandoahGenerationalMode.hpp"
  74 #include "gc/shenandoah/mode/shenandoahIUMode.hpp"
  75 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"
  76 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp"
  77 
  78 #if INCLUDE_JFR
  79 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
  80 #endif
  81 
  82 #include "gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp"
  83 
  84 #include "classfile/systemDictionary.hpp"
  85 #include "memory/classLoaderMetaspace.hpp"
  86 #include "memory/metaspaceUtils.hpp"
  87 #include "oops/compressedOops.inline.hpp"
  88 #include "prims/jvmtiTagMap.hpp"
  89 #include "runtime/atomic.hpp"
  90 #include "runtime/globals.hpp"
  91 #include "runtime/interfaceSupport.inline.hpp"
  92 #include "runtime/java.hpp"
  93 #include "runtime/orderAccess.hpp"
  94 #include "runtime/safepointMechanism.hpp"
  95 #include "runtime/vmThread.hpp"
  96 #include "services/mallocTracker.hpp"
  97 #include "services/memTracker.hpp"
  98 #include "utilities/events.hpp"
  99 #include "utilities/powerOfTwo.hpp"
 100 
 101 class ShenandoahPretouchHeapTask : public WorkerTask {
 102 private:
 103   ShenandoahRegionIterator _regions;

 150 jint ShenandoahHeap::initialize() {
 151   //
 152   // Figure out heap sizing
 153   //
 154 
 155   size_t init_byte_size = InitialHeapSize;
 156   size_t min_byte_size  = MinHeapSize;
 157   size_t max_byte_size  = MaxHeapSize;
 158   size_t heap_alignment = HeapAlignment;
 159 
 160   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 161 
 162   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 163   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 164 
 165   _num_regions = ShenandoahHeapRegion::region_count();
 166   assert(_num_regions == (max_byte_size / reg_size_bytes),
 167          "Regions should cover entire heap exactly: " SIZE_FORMAT " != " SIZE_FORMAT "/" SIZE_FORMAT,
 168          _num_regions, max_byte_size, reg_size_bytes);
 169 



 170   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 171   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 172   assert(num_committed_regions <= _num_regions, "sanity");
 173   _initial_size = num_committed_regions * reg_size_bytes;
 174 
 175   size_t num_min_regions = min_byte_size / reg_size_bytes;
 176   num_min_regions = MIN2(num_min_regions, _num_regions);
 177   assert(num_min_regions <= _num_regions, "sanity");
 178   _minimum_size = num_min_regions * reg_size_bytes;
 179 
 180   // Default to max heap size.
 181   _soft_max_size = _num_regions * reg_size_bytes;
 182 
 183   _committed = _initial_size;
 184 
 185   // Now we know the number of regions and heap sizes, initialize the heuristics.
 186   initialize_generations();
 187   initialize_heuristics();
 188 
 189   size_t heap_page_size   = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 190   size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 191   size_t region_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 192 
 193   //
 194   // Reserve and commit memory for heap
 195   //
 196 
 197   ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 198   initialize_reserved_region(heap_rs);
 199   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 200   _heap_region_special = heap_rs.special();
 201 
 202   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 203          "Misaligned heap: " PTR_FORMAT, p2i(base()));
 204 
 205 #if SHENANDOAH_OPTIMIZED_MARKTASK
 206   // The optimized ShenandoahMarkTask takes some bits away from the full object bits.
 207   // Fail if we ever attempt to address more than we can.
 208   if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {
 209     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 210                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 211                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 212                 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());
 213     vm_exit_during_initialization("Fatal Error", buf);
 214   }
 215 #endif
 216 
 217   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 218   if (!_heap_region_special) {
 219     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 220                               "Cannot commit heap memory");
 221   }
 222 
 223   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this, _heap_region));
 224 
 225   //
 226   // After reserving the Java heap, create the card table, barriers, and workers, in dependency order
 227   //
 228   if (mode()->is_generational()) {
 229     ShenandoahDirectCardMarkRememberedSet *rs;
 230     ShenandoahCardTable* card_table = ShenandoahBarrierSet::barrier_set()->card_table();
 231     size_t card_count = card_table->cards_required(heap_rs.size() / HeapWordSize) - 1;
 232     rs = new ShenandoahDirectCardMarkRememberedSet(ShenandoahBarrierSet::barrier_set()->card_table(), card_count);
 233     _card_scan = new ShenandoahScanRemembered<ShenandoahDirectCardMarkRememberedSet>(rs);
 234   }
 235 
 236   _workers = new ShenandoahWorkerThreads("Shenandoah GC Threads", _max_workers);
 237   if (_workers == NULL) {
 238     vm_exit_during_initialization("Failed necessary allocation.");
 239   } else {
 240     _workers->initialize_workers();
 241   }
 242 
 243   if (ParallelGCThreads > 1) {
 244     _safepoint_workers = new ShenandoahWorkerThreads("Safepoint Cleanup Thread", ParallelGCThreads);
 245     _safepoint_workers->initialize_workers();
 246   }
 247 
 248   //
 249   // Reserve and commit memory for bitmap(s)
 250   //
 251 
 252   _bitmap_size = ShenandoahMarkBitMap::compute_size(heap_rs.size());
 253   _bitmap_size = align_up(_bitmap_size, bitmap_page_size);
 254 
 255   size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();
 256 
 257   guarantee(bitmap_bytes_per_region != 0,
 258             "Bitmap bytes per region should not be zero");
 259   guarantee(is_power_of_2(bitmap_bytes_per_region),
 260             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
 261 
 262   if (bitmap_page_size > bitmap_bytes_per_region) {
 263     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 264     _bitmap_bytes_per_slice = bitmap_page_size;
 265   } else {
 266     _bitmap_regions_per_slice = 1;
 267     _bitmap_bytes_per_slice = bitmap_bytes_per_region;

 271             "Should have at least one region per slice: " SIZE_FORMAT,
 272             _bitmap_regions_per_slice);
 273 
 274   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 275             "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
 276             _bitmap_bytes_per_slice, bitmap_page_size);
 277 
 278   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 279   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 280   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 281   _bitmap_region_special = bitmap.special();
 282 
 283   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 284                               align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 285   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 286   if (!_bitmap_region_special) {
 287     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 288                               "Cannot commit bitmap memory");
 289   }
 290 
 291   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
 292 
 293   if (ShenandoahVerify) {
 294     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
 295     if (!verify_bitmap.special()) {
 296       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 297                                 "Cannot commit verification bitmap memory");
 298     }
 299     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 300     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 301     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 302     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 303   }
 304 
 305   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 306   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 307   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 308   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 309   _aux_bitmap_region_special = aux_bitmap.special();
 310   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 311 

 417   // There should probably be Shenandoah-specific options for these,
 418   // just as there are G1-specific options.
 419   {
 420     ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
 421     satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
 422     satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
 423   }
 424 
 425   _monitoring_support = new ShenandoahMonitoringSupport(this);
 426   _phase_timings = new ShenandoahPhaseTimings(max_workers());
 427   ShenandoahCodeRoots::initialize();
 428 
 429   if (ShenandoahPacing) {
 430     _pacer = new ShenandoahPacer(this);
 431     _pacer->setup_for_idle();
 432   } else {
 433     _pacer = NULL;
 434   }
 435 
 436   _control_thread = new ShenandoahControlThread();
 437   _regulator_thread = new ShenandoahRegulatorThread(_control_thread);
 438 
 439   ShenandoahInitLogger::print();
 440 
 441   return JNI_OK;
 442 }
 443 
 444 void ShenandoahHeap::initialize_generations() {
 445   size_t max_capacity_new      = young_generation_capacity(max_capacity());
 446   size_t soft_max_capacity_new = young_generation_capacity(soft_max_capacity());
 447   size_t max_capacity_old      = max_capacity() - max_capacity_new;
 448   size_t soft_max_capacity_old = soft_max_capacity() - soft_max_capacity_new;
 449 
 450   _young_generation = new ShenandoahYoungGeneration(_max_workers, max_capacity_new, soft_max_capacity_new);
 451   _old_generation = new ShenandoahOldGeneration(_max_workers, max_capacity_old, soft_max_capacity_old);
 452   _global_generation = new ShenandoahGlobalGeneration(_max_workers);
 453 }
 454 
 455 void ShenandoahHeap::initialize_heuristics() {
 456   if (ShenandoahGCMode != NULL) {
 457     if (strcmp(ShenandoahGCMode, "satb") == 0) {
 458       _gc_mode = new ShenandoahSATBMode();
 459     } else if (strcmp(ShenandoahGCMode, "iu") == 0) {
 460       _gc_mode = new ShenandoahIUMode();
 461     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 462       _gc_mode = new ShenandoahPassiveMode();
 463     } else if (strcmp(ShenandoahGCMode, "generational") == 0) {
 464       _gc_mode = new ShenandoahGenerationalMode();
 465     } else {
 466       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 467     }
 468   } else {
 469     vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)");
 470   }
 471   _gc_mode->initialize_flags();
 472   if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 473     vm_exit_during_initialization(
 474             err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 475                     _gc_mode->name()));
 476   }
 477   if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
 478     vm_exit_during_initialization(
 479             err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 480                     _gc_mode->name()));
 481   }

 482 
 483   _global_generation->initialize_heuristics(_gc_mode);
 484   if (mode()->is_generational()) {
 485     _young_generation->initialize_heuristics(_gc_mode);
 486     _old_generation->initialize_heuristics(_gc_mode);
 487 
 488     ShenandoahEvacWaste = ShenandoahGenerationalEvacWaste;








 489   }
 490 }
 491 
 492 #ifdef _MSC_VER
 493 #pragma warning( push )
 494 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 495 #endif
 496 
 497 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 498   CollectedHeap(),
 499   _gc_generation(NULL),
 500   _prep_for_mixed_evac_in_progress(false),
 501   _initial_size(0),
 502   _used(0),
 503   _committed(0),
 504   _max_workers(MAX3(ConcGCThreads, ParallelGCThreads, 1U)),

 505   _workers(NULL),
 506   _safepoint_workers(NULL),
 507   _heap_region_special(false),
 508   _num_regions(0),
 509   _regions(NULL),
 510   _update_refs_iterator(this),
 511   _alloc_supplement_reserve(0),
 512   _promotion_reserve(0),
 513   _old_evac_reserve(0),
 514   _old_evac_expended(0),
 515   _young_evac_reserve(0),
 516   _captured_old_usage(0),
 517   _previous_promotion(0),
 518   _cancel_requested_time(0),
 519   _young_generation(NULL),
 520   _global_generation(NULL),
 521   _old_generation(NULL),
 522   _control_thread(NULL),
 523   _regulator_thread(NULL),
 524   _shenandoah_policy(policy),


 525   _free_set(NULL),
 526   _pacer(NULL),
 527   _verifier(NULL),
 528   _phase_timings(NULL),
 529   _monitoring_support(NULL),
 530   _memory_pool(NULL),
 531   _young_gen_memory_pool(NULL),
 532   _old_gen_memory_pool(NULL),
 533   _stw_memory_manager("Shenandoah Pauses", "end of GC pause"),
 534   _cycle_memory_manager("Shenandoah Cycles", "end of GC cycle"),
 535   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 536   _soft_ref_policy(),
 537   _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),

 538   _marking_context(NULL),
 539   _bitmap_size(0),
 540   _bitmap_regions_per_slice(0),
 541   _bitmap_bytes_per_slice(0),
 542   _bitmap_region_special(false),
 543   _aux_bitmap_region_special(false),
 544   _liveness_cache(NULL),
 545   _collection_set(NULL),
 546   _card_scan(NULL)
 547 {

















 548 }
 549 
 550 #ifdef _MSC_VER
 551 #pragma warning( pop )
 552 #endif
 553 





























 554 void ShenandoahHeap::print_on(outputStream* st) const {
 555   st->print_cr("Shenandoah Heap");
 556   st->print_cr(" " SIZE_FORMAT "%s max, " SIZE_FORMAT "%s soft max, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
 557                byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
 558                byte_size_in_proper_unit(soft_max_capacity()), proper_unit_for_byte_size(soft_max_capacity()),
 559                byte_size_in_proper_unit(committed()),    proper_unit_for_byte_size(committed()),
 560                byte_size_in_proper_unit(used()),         proper_unit_for_byte_size(used()));
 561   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
 562                num_regions(),
 563                byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
 564                proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
 565 
 566   st->print("Status: ");
 567   if (has_forwarded_objects())                 st->print("has forwarded objects, ");
 568   if (is_concurrent_old_mark_in_progress())    st->print("old marking, ");
 569   if (is_concurrent_young_mark_in_progress())  st->print("young marking, ");
 570   if (is_evacuation_in_progress())             st->print("evacuating, ");
 571   if (is_update_refs_in_progress())            st->print("updating refs, ");
 572   if (is_degenerated_gc_in_progress())         st->print("degenerated gc, ");
 573   if (is_full_gc_in_progress())                st->print("full gc, ");
 574   if (is_full_gc_move_in_progress())           st->print("full gc move, ");
 575   if (is_concurrent_weak_root_in_progress())   st->print("concurrent weak roots, ");
 576   if (is_concurrent_strong_root_in_progress() &&
 577       !is_concurrent_weak_root_in_progress())  st->print("concurrent strong roots, ");
 578 
 579   if (cancelled_gc()) {
 580     st->print("cancelled");
 581   } else {
 582     st->print("not cancelled");
 583   }
 584   st->cr();
 585 
 586   st->print_cr("Reserved region:");
 587   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 588                p2i(reserved_region().start()),
 589                p2i(reserved_region().end()));

 612     assert(thread->is_Worker_thread(), "Only worker thread expected");
 613     ShenandoahThreadLocalData::initialize_gclab(thread);
 614   }
 615 };
 616 
 617 void ShenandoahHeap::post_initialize() {
 618   CollectedHeap::post_initialize();
 619   MutexLocker ml(Threads_lock);
 620 
 621   ShenandoahInitWorkerGCLABClosure init_gclabs;
 622   _workers->threads_do(&init_gclabs);
 623 
 624   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 625   // Now, we will let WorkerThreads to initialize gclab when new worker is created.
 626   _workers->set_initialize_gclab();
 627   if (_safepoint_workers != NULL) {
 628     _safepoint_workers->threads_do(&init_gclabs);
 629     _safepoint_workers->set_initialize_gclab();
 630   }
 631 


 632   JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());
 633 }
 634 
 635 
 636 ShenandoahOldHeuristics* ShenandoahHeap::old_heuristics() {
 637   return (ShenandoahOldHeuristics*) _old_generation->heuristics();
 638 }
 639 
 640 bool ShenandoahHeap::doing_mixed_evacuations() {
 641   return old_heuristics()->unprocessed_old_collection_candidates() > 0;
 642 }
 643 
 644 bool ShenandoahHeap::is_gc_generation_young() const {
 645   return _gc_generation != NULL && _gc_generation->generation_mode() == YOUNG;
 646 }
 647 
 648 // There are three JVM parameters for setting young gen capacity:
 649 //    NewSize, MaxNewSize, NewRatio.
 650 //
 651 // If only NewSize is set, it assigns a fixed size and the other two parameters are ignored.
 652 // Otherwise NewRatio applies.
 653 //
 654 // If NewSize is set in any combination, it provides a lower bound.
 655 //
 656 // If MaxNewSize is set it provides an upper bound.
 657 // If this bound is smaller than NewSize, it supersedes,
 658 // resulting in a fixed size given by MaxNewSize.
 659 size_t ShenandoahHeap::young_generation_capacity(size_t capacity) {
 660   if (FLAG_IS_CMDLINE(NewSize) && !FLAG_IS_CMDLINE(MaxNewSize) && !FLAG_IS_CMDLINE(NewRatio)) {
 661     capacity = MIN2(NewSize, capacity);
 662   } else {
 663     capacity /= NewRatio + 1;
 664     if (FLAG_IS_CMDLINE(NewSize)) {
 665       capacity = MAX2(NewSize, capacity);
 666     }
 667     if (FLAG_IS_CMDLINE(MaxNewSize)) {
 668       capacity = MIN2(MaxNewSize, capacity);
 669     }
 670   }
 671   return capacity;
 672 }
 673 
 674 size_t ShenandoahHeap::used() const {
 675   return Atomic::load(&_used);
 676 }
 677 
 678 size_t ShenandoahHeap::committed() const {
 679   return Atomic::load(&_committed);
 680 }
 681 
 682 void ShenandoahHeap::increase_committed(size_t bytes) {
 683   shenandoah_assert_heaplocked_or_safepoint();
 684   _committed += bytes;
 685 }
 686 
 687 void ShenandoahHeap::decrease_committed(size_t bytes) {
 688   shenandoah_assert_heaplocked_or_safepoint();
 689   _committed -= bytes;
 690 }
 691 
 692 void ShenandoahHeap::increase_used(size_t bytes) {
 693   Atomic::add(&_used, bytes, memory_order_relaxed);
 694 }
 695 
 696 void ShenandoahHeap::set_used(size_t bytes) {
 697   Atomic::store(&_used, bytes);
 698 }
 699 
 700 void ShenandoahHeap::decrease_used(size_t bytes) {
 701   assert(used() >= bytes, "never decrease heap size by more than we've left");
 702   Atomic::sub(&_used, bytes, memory_order_relaxed);
 703 }
 704 




 705 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
 706   size_t bytes = words * HeapWordSize;
 707   if (!waste) {
 708     increase_used(bytes);
 709   }
 710 
 711   if (ShenandoahPacing) {
 712     control_thread()->pacing_notify_alloc(words);
 713     if (waste) {
 714       pacer()->claim_for_alloc(words, true);
 715     }
 716   }
 717 }
 718 
 719 size_t ShenandoahHeap::capacity() const {
 720   return committed();
 721 }
 722 
 723 size_t ShenandoahHeap::max_capacity() const {
 724   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 725 }
 726 
 727 size_t ShenandoahHeap::soft_max_capacity() const {
 728   size_t v = Atomic::load(&_soft_max_size);
 729   assert(min_capacity() <= v && v <= max_capacity(),
 730          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 731          min_capacity(), v, max_capacity());
 732   return v;
 733 }
 734 
 735 void ShenandoahHeap::set_soft_max_capacity(size_t v) {
 736   assert(min_capacity() <= v && v <= max_capacity(),
 737          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 738          min_capacity(), v, max_capacity());
 739   Atomic::store(&_soft_max_size, v);
 740 
 741   if (mode()->is_generational()) {
 742     size_t soft_max_capacity_young = young_generation_capacity(_soft_max_size);
 743     size_t soft_max_capacity_old = _soft_max_size - soft_max_capacity_young;
 744     _young_generation->set_soft_max_capacity(soft_max_capacity_young);
 745     _old_generation->set_soft_max_capacity(soft_max_capacity_old);
 746   }
 747 }
 748 
 749 size_t ShenandoahHeap::min_capacity() const {
 750   return _minimum_size;
 751 }
 752 
 753 size_t ShenandoahHeap::initial_capacity() const {
 754   return _initial_size;
 755 }
 756 
 757 bool ShenandoahHeap::is_in(const void* p) const {
 758   HeapWord* heap_base = (HeapWord*) base();
 759   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 760   return p >= heap_base && p < last_region_end;
 761 }
 762 
 763 bool ShenandoahHeap::is_in_young(const void* p) const {
 764   return is_in(p) && heap_region_containing(p)->affiliation() == ShenandoahRegionAffiliation::YOUNG_GENERATION;
 765 }
 766 
 767 bool ShenandoahHeap::is_in_old(const void* p) const {
 768   return is_in(p) && heap_region_containing(p)->affiliation() == ShenandoahRegionAffiliation::OLD_GENERATION;
 769 }
 770 
 771 bool ShenandoahHeap::is_in_active_generation(oop obj) const {
 772   if (!mode()->is_generational()) {
 773     // everything is the same single generation
 774     return true;
 775   }
 776 
 777   if (active_generation() == NULL) {
 778     // no collection is happening, only expect this to be called
 779     // when concurrent processing is active, but that could change
 780     return false;
 781   }
 782 
 783   return active_generation()->contains(obj);
 784 }
 785 
 786 void ShenandoahHeap::op_uncommit(double shrink_before, size_t shrink_until) {
 787   assert (ShenandoahUncommit, "should be enabled");
 788 
 789   // Application allocates from the beginning of the heap, and GC allocates at
 790   // the end of it. It is more efficient to uncommit from the end, so that applications
 791   // could enjoy the near committed regions. GC allocations are much less frequent,
 792   // and therefore can accept the committing costs.
 793 
 794   size_t count = 0;
 795   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
 796     ShenandoahHeapRegion* r = get_region(i - 1);
 797     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
 798       ShenandoahHeapLocker locker(lock());
 799       if (r->is_empty_committed()) {
 800         if (committed() < shrink_until + ShenandoahHeapRegion::region_size_bytes()) {
 801           break;
 802         }
 803 
 804         r->make_uncommitted();
 805         count++;
 806       }
 807     }
 808     SpinPause(); // allow allocators to take the lock
 809   }
 810 
 811   if (count > 0) {
 812     control_thread()->notify_heap_changed();
 813     regulator_thread()->notify_heap_changed();
 814   }
 815 }
 816 
 817 void ShenandoahHeap::handle_old_evacuation(HeapWord* obj, size_t words, bool promotion) {
 818   // Only register the copy of the object that won the evacuation race.
 819   card_scan()->register_object_wo_lock(obj);
 820 
 821   // Mark the entire range of the evacuated object as dirty.  At next remembered set scan,
 822   // we will clear dirty bits that do not hold interesting pointers.  It's more efficient to
 823   // do this in batch, in a background GC thread than to try to carefully dirty only cards
 824   // that hold interesting pointers right now.
 825   card_scan()->mark_range_as_dirty(obj, words);
 826 
 827   if (promotion) {
 828     // This evacuation was a promotion, track this as allocation against old gen
 829     old_generation()->increase_allocated(words * HeapWordSize);
 830   }
 831 }
 832 
 833 void ShenandoahHeap::handle_old_evacuation_failure() {
 834   if (_old_gen_oom_evac.try_set()) {
 835     log_info(gc)("Old gen evac failure.");
 836   }
 837 }
 838 
 839 void ShenandoahHeap::handle_promotion_failure() {
 840   old_heuristics()->handle_promotion_failure();
 841 }
 842 
 843 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 844   // New object should fit the GCLAB size
 845   size_t min_size = MAX2(size, PLAB::min_size());
 846 
 847   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
 848   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
 849 
 850   // Limit growth of GCLABs to ShenandoahMaxEvacLABRatio * the minimum size.  This enables more equitable distribution of
 851   // available evacuation buidget between the many threads that are coordinating in the evacuation effort.
 852   if (ShenandoahMaxEvacLABRatio > 0) {
 853     new_size = MIN2(new_size, PLAB::min_size() * ShenandoahMaxEvacLABRatio);
 854   }
 855   new_size = MIN2(new_size, PLAB::max_size());
 856   new_size = MAX2(new_size, PLAB::min_size());
 857 
 858   // Record new heuristic value even if we take any shortcut. This captures
 859   // the case when moderately-sized objects always take a shortcut. At some point,
 860   // heuristics should catch up with them.
 861   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
 862 
 863   if (new_size < size) {
 864     // New size still does not fit the object. Fall back to shared allocation.
 865     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
 866     return NULL;
 867   }
 868 
 869   // Retire current GCLAB, and allocate a new one.
 870   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 871   gclab->retire();
 872 
 873   size_t actual_size = 0;
 874   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);

 878 
 879   assert (size <= actual_size, "allocation should fit");
 880 
 881   if (ZeroTLAB) {
 882     // ..and clear it.
 883     Copy::zero_to_words(gclab_buf, actual_size);
 884   } else {
 885     // ...and zap just allocated object.
 886 #ifdef ASSERT
 887     // Skip mangling the space corresponding to the object header to
 888     // ensure that the returned space is not considered parsable by
 889     // any concurrent GC thread.
 890     size_t hdr_size = oopDesc::header_size();
 891     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 892 #endif // ASSERT
 893   }
 894   gclab->set_buf(gclab_buf, actual_size);
 895   return gclab->allocate(size);
 896 }
 897 
 898 // Establish a new PLAB and allocate size HeapWords within it.
 899 HeapWord* ShenandoahHeap::allocate_from_plab_slow(Thread* thread, size_t size, bool is_promotion) {
 900   // New object should fit the PLAB size
 901   size_t min_size = MAX2(size, PLAB::min_size());
 902 
 903   // Figure out size of new PLAB, looking back at heuristics. Expand aggressively.
 904   size_t new_size = ShenandoahThreadLocalData::plab_size(thread) * 2;
 905   // Limit growth of PLABs to ShenandoahMaxEvacLABRatio * the minimum size.  This enables more equitable distribution of
 906   // available evacuation buidget between the many threads that are coordinating in the evacuation effort.
 907   if (ShenandoahMaxEvacLABRatio > 0) {
 908     new_size = MIN2(new_size, PLAB::min_size() * ShenandoahMaxEvacLABRatio);
 909   }
 910   new_size = MIN2(new_size, PLAB::max_size());
 911   new_size = MAX2(new_size, PLAB::min_size());
 912 
 913   size_t unalignment = new_size % CardTable::card_size_in_words();
 914   if (unalignment != 0) {
 915     new_size = new_size - unalignment + CardTable::card_size_in_words();
 916   }
 917 
 918   // Record new heuristic value even if we take any shortcut. This captures
 919   // the case when moderately-sized objects always take a shortcut. At some point,
 920   // heuristics should catch up with them.  Note that the requested new_size may
 921   // not be honored, but we remember that this is the preferred size.
 922   ShenandoahThreadLocalData::set_plab_size(thread, new_size);
 923 
 924   if (new_size < size) {
 925     // New size still does not fit the object. Fall back to shared allocation.
 926     // This avoids retiring perfectly good PLABs, when we encounter a large object.
 927     return NULL;
 928   }
 929 
 930   // Retire current PLAB, and allocate a new one.
 931   PLAB* plab = ShenandoahThreadLocalData::plab(thread);
 932   // CAUTION: retire_plab may register the remnant filler object with the remembered set scanner without a lock.  This
 933   // is safe iff it is assured that each PLAB is a whole-number multiple of card-mark memory size and each PLAB is
 934   // aligned with the start of a card's memory range.
 935   retire_plab(plab);
 936 
 937   size_t actual_size = 0;
 938   // allocate_new_plab resets plab_evacuated and plab_promoted and disables promotions if old-gen available is
 939   // less than the remaining evacuation need.
 940   HeapWord* plab_buf = allocate_new_plab(min_size, new_size, &actual_size);
 941   if (plab_buf == NULL) {
 942     return NULL;
 943   }
 944 
 945   assert (size <= actual_size, "allocation should fit");
 946 
 947   if (ZeroTLAB) {
 948     // ..and clear it.
 949     Copy::zero_to_words(plab_buf, actual_size);
 950   } else {
 951     // ...and zap just allocated object.
 952 #ifdef ASSERT
 953     // Skip mangling the space corresponding to the object header to
 954     // ensure that the returned space is not considered parsable by
 955     // any concurrent GC thread.
 956     size_t hdr_size = oopDesc::header_size();
 957     Copy::fill_to_words(plab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 958 #endif // ASSERT
 959   }
 960   plab->set_buf(plab_buf, actual_size);
 961 
 962   if (is_promotion && !ShenandoahThreadLocalData::allow_plab_promotions(thread)) {
 963     return nullptr;
 964   }
 965   return plab->allocate(size);
 966 }
 967 
 968 // TODO: It is probably most efficient to register all objects (both promotions and evacuations) that were allocated within
 969 // this plab at the time we retire the plab.  A tight registration loop will run within both code and data caches.  This change
 970 // would allow smaller and faster in-line implementation of alloc_from_plab().  Since plabs are aligned on card-table boundaries,
 971 // this object registration loop can be performed without acquiring a lock.
 972 void ShenandoahHeap::retire_plab(PLAB* plab) {
 973   if (!mode()->is_generational()) {
 974     plab->retire();
 975   } else {
 976     Thread* thread = Thread::current();
 977     size_t evacuated = ShenandoahThreadLocalData::get_plab_evacuated(thread);
 978     // We don't enforce limits on get_plab_promoted(thread).  Promotion uses any memory not required for evacuation.
 979     expend_old_evac(evacuated);
 980     size_t waste = plab->waste();
 981     HeapWord* top = plab->top();
 982     plab->retire();
 983     if (top != NULL && plab->waste() > waste && is_in_old(top)) {
 984       // If retiring the plab created a filler object, then we
 985       // need to register it with our card scanner so it can
 986       // safely walk the region backing the plab.
 987       log_debug(gc)("retire_plab() is registering remnant of size " SIZE_FORMAT " at " PTR_FORMAT,
 988                     plab->waste() - waste, p2i(top));
 989       card_scan()->register_object_wo_lock(top);
 990     }
 991   }
 992 }
 993 
 994 void ShenandoahHeap::cancel_old_gc() {
 995   shenandoah_assert_safepoint();
 996   assert(_old_generation != NULL, "Should only have mixed collections in generation mode.");
 997   log_info(gc)("Terminating old gc cycle.");
 998 
 999   // Stop marking
1000   old_generation()->cancel_marking();
1001   // Stop coalescing undead objects
1002   set_concurrent_prep_for_mixed_evacuation_in_progress(false);
1003   // Stop tracking old regions
1004   old_heuristics()->abandon_collection_candidates();
1005   // Remove old generation access to young generation mark queues
1006   young_generation()->set_old_gen_task_queues(nullptr);
1007 }
1008 
1009 bool ShenandoahHeap::is_old_gc_active() {
1010   return is_concurrent_old_mark_in_progress()
1011       || is_concurrent_prep_for_mixed_evacuation_in_progress()
1012       || old_heuristics()->unprocessed_old_or_hidden_collection_candidates() > 0
1013       || young_generation()->old_gen_task_queues() != nullptr;
1014 }
1015 
1016 void ShenandoahHeap::coalesce_and_fill_old_regions() {
1017   class ShenandoahGlobalCoalesceAndFill : public ShenandoahHeapRegionClosure {
1018    public:
1019     virtual void heap_region_do(ShenandoahHeapRegion* region) override {
1020       // old region is not in the collection set and was not immediately trashed
1021       if (region->is_old() && region->is_active() && !region->is_humongous()) {
1022         // Reset the coalesce and fill boundary because this is a global collect
1023         // and cannot be preempted by young collects. We want to be sure the entire
1024         // region is coalesced here and does not resume from a previously interrupted
1025         // or completed coalescing.
1026         region->begin_preemptible_coalesce_and_fill();
1027         region->oop_fill_and_coalesce();
1028       }
1029     }
1030 
1031     virtual bool is_thread_safe() override {
1032       return true;
1033     }
1034   };
1035   ShenandoahGlobalCoalesceAndFill coalesce;
1036   parallel_heap_region_iterate(&coalesce);
1037 }
1038 
1039 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
1040                                             size_t requested_size,
1041                                             size_t* actual_size) {
1042   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
1043   HeapWord* res = allocate_memory(req, false);
1044   if (res != NULL) {
1045     *actual_size = req.actual_size();
1046   } else {
1047     *actual_size = 0;
1048   }
1049   return res;
1050 }
1051 
1052 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
1053                                              size_t word_size,
1054                                              size_t* actual_size) {
1055   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
1056   HeapWord* res = allocate_memory(req, false);
1057   if (res != NULL) {
1058     *actual_size = req.actual_size();
1059   } else {
1060     *actual_size = 0;
1061   }
1062   return res;
1063 }
1064 
1065 HeapWord* ShenandoahHeap::allocate_new_plab(size_t min_size,
1066                                             size_t word_size,
1067                                             size_t* actual_size) {
1068   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_plab(min_size, word_size);
1069   // Note that allocate_memory() sets a thread-local flag to prohibit further promotions by this thread
1070   // if we are at risk of exceeding the old-gen evacuation budget.
1071   HeapWord* res = allocate_memory(req, false);
1072   if (res != NULL) {
1073     *actual_size = req.actual_size();
1074   } else {
1075     *actual_size = 0;
1076   }
1077   return res;
1078 }
1079 
1080 // is_promotion is true iff this allocation is known for sure to hold the result of young-gen evacuation
1081 // to old-gen.  plab allocates arre not known as such, since they may hold old-gen evacuations.
1082 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req, bool is_promotion) {
1083   intptr_t pacer_epoch = 0;
1084   bool in_new_region = false;
1085   HeapWord* result = NULL;
1086 
1087   if (req.is_mutator_alloc()) {
1088     if (ShenandoahPacing) {
1089       pacer()->pace_for_alloc(req.size());
1090       pacer_epoch = pacer()->epoch();
1091     }
1092 
1093     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
1094       result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1095     }
1096 
1097     // Allocation failed, block until control thread reacted, then retry allocation.
1098     //
1099     // It might happen that one of the threads requesting allocation would unblock
1100     // way later after GC happened, only to fail the second allocation, because
1101     // other threads have already depleted the free storage. In this case, a better
1102     // strategy is to try again, as long as GC makes progress.
1103     //
1104     // Then, we need to make sure the allocation was retried after at least one
1105     // Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
1106 
1107     size_t tries = 0;
1108 
1109     while (result == NULL && _progress_last_gc.is_set()) {
1110       tries++;
1111       control_thread()->handle_alloc_failure(req);
1112       result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1113     }
1114 
1115     while (result == NULL && tries <= ShenandoahFullGCThreshold) {
1116       tries++;
1117       control_thread()->handle_alloc_failure(req);
1118       result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1119     }
1120 
1121   } else {
1122     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
1123     result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1124     // Do not call handle_alloc_failure() here, because we cannot block.
1125     // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
1126   }
1127 
1128   if (in_new_region) {
1129     control_thread()->notify_heap_changed();
1130     regulator_thread()->notify_heap_changed();
1131   }
1132 
1133   if (result != NULL) {
1134     ShenandoahGeneration* alloc_generation = generation_for(req.affiliation());
1135     size_t requested = req.size();
1136     size_t actual = req.actual_size();
1137     size_t actual_bytes = actual * HeapWordSize;
1138 
1139     assert (req.is_lab_alloc() || (requested == actual),
1140             "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
1141             ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
1142 
1143     if (req.is_mutator_alloc()) {
1144       notify_mutator_alloc_words(actual, false);
1145       alloc_generation->increase_allocated(actual_bytes);
1146 
1147       // If we requested more than we were granted, give the rest back to pacer.
1148       // This only matters if we are in the same pacing epoch: do not try to unpace
1149       // over the budget for the other phase.
1150       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
1151         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
1152       }
1153     } else {
1154       increase_used(actual_bytes);
1155     }
1156   }
1157 
1158   return result;
1159 }
1160 
1161 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region, bool is_promotion) {
1162   size_t requested_bytes = req.size() * HeapWordSize;
1163 
1164   ShenandoahHeapLocker locker(lock());
1165   if (mode()->is_generational()) {
1166     if (req.affiliation() == YOUNG_GENERATION) {
1167       if (req.is_mutator_alloc()) {
1168         if (requested_bytes >= young_generation()->adjusted_available()) {
1169           // We know this is not a GCLAB.  This must be a TLAB or a shared allocation.  Reject the allocation request if
1170           // exceeds established capacity limits.
1171           return nullptr;
1172         }
1173       }
1174     } else {                    // reg.affiliation() == OLD_GENERATION
1175       assert(req.type() != ShenandoahAllocRequest::_alloc_gclab, "GCLAB pertains only to young-gen memory");
1176 
1177       if (req.type() ==  ShenandoahAllocRequest::_alloc_plab) {
1178         // We've already retired this thread's previously exhausted PLAB and have accounted for how that PLAB's
1179         // memory was allotted.
1180         Thread* thread = Thread::current();
1181         ShenandoahThreadLocalData::reset_plab_evacuated(thread);
1182         ShenandoahThreadLocalData::reset_plab_promoted(thread);
1183 
1184         // Conservatively, assume this entire PLAB will be used for promotion.  Act as if we need to serve the
1185         // rest of evacuation need from as-yet unallocated old-gen memory.
1186         size_t remaining_evac_need = get_old_evac_reserve() - get_old_evac_expended();
1187         size_t evac_available = old_generation()->adjusted_available() - requested_bytes;
1188         if (remaining_evac_need >= evac_available) {
1189           // Disable promotions within this thread because the entirety of this PLAB must be available to hold
1190           // old-gen evacuations.
1191           ShenandoahThreadLocalData::disable_plab_promotions(thread);
1192         } else {
1193           ShenandoahThreadLocalData::enable_plab_promotions(thread);
1194         }
1195       } else if (is_promotion) {
1196         // This is a shared alloc for promotion
1197         Thread* thread = Thread::current();
1198         size_t remaining_evac_need = get_old_evac_reserve() - get_old_evac_expended();
1199         size_t evac_available = old_generation()->adjusted_available() - requested_bytes;
1200         if (remaining_evac_need >= evac_available) {
1201           return nullptr;       // We need to reserve the remaining memory for evacuation so defer the promotion
1202         }
1203         // Else, we'll allow the allocation to proceed.  (Since we hold heap lock, the tested condition remains true.)
1204       } else {
1205         // This is a shared allocation for evacuation.  Memory has already been reserved for this purpose.
1206       }
1207     }
1208   }
1209 
1210   HeapWord* result = _free_set->allocate(req, in_new_region);
1211   if (result != NULL) {
1212     if (req.affiliation() == ShenandoahRegionAffiliation::OLD_GENERATION) {
1213       // Register the newly allocated object while we're holding the global lock since there's no synchronization
1214       // built in to the implementation of register_object().  There are potential races when multiple independent
1215       // threads are allocating objects, some of which might span the same card region.  For example, consider
1216       // a card table's memory region within which three objects are being allocated by three different threads:
1217       //
1218       // objects being "concurrently" allocated:
1219       //    [-----a------][-----b-----][--------------c------------------]
1220       //            [---- card table memory range --------------]
1221       //
1222       // Before any objects are allocated, this card's memory range holds no objects.  Note that:
1223       //   allocation of object a wants to set the has-object, first-start, and last-start attributes of the preceding card region.
1224       //   allocation of object b wants to set the has-object, first-start, and last-start attributes of this card region.
1225       //   allocation of object c also wants to set the has-object, first-start, and last-start attributes of this card region.
1226       //
1227       // The thread allocating b and the thread allocating c can "race" in various ways, resulting in confusion, such as last-start
1228       // representing object b while first-start represents object c.  This is why we need to require all register_object()
1229       // invocations to be "mutually exclusive" with respect to each card's memory range.
1230       ShenandoahHeap::heap()->card_scan()->register_object(result);
1231     }
1232   }
1233   return result;
1234 }
1235 
1236 HeapWord* ShenandoahHeap::mem_allocate(size_t size,
1237                                         bool*  gc_overhead_limit_was_exceeded) {
1238   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
1239   return allocate_memory(req, false);
1240 }
1241 
1242 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
1243                                                              size_t size,
1244                                                              Metaspace::MetadataType mdtype) {
1245   MetaWord* result;
1246 
1247   // Inform metaspace OOM to GC heuristics if class unloading is possible.
1248   ShenandoahHeuristics* h = global_generation()->heuristics();
1249   if (h->can_unload_classes()) {
1250     h->record_metaspace_oom();
1251   }
1252 
1253   // Expand and retry allocation
1254   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
1255   if (result != NULL) {
1256     return result;
1257   }
1258 
1259   // Start full GC
1260   collect(GCCause::_metadata_GC_clear_soft_refs);
1261 
1262   // Retry allocation
1263   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
1264   if (result != NULL) {
1265     return result;
1266   }
1267 
1268   // Expand and retry allocation
1269   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);

1308 
1309   void work(uint worker_id) {
1310     if (_concurrent) {
1311       ShenandoahConcurrentWorkerSession worker_session(worker_id);
1312       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
1313       ShenandoahEvacOOMScope oom_evac_scope;
1314       do_work();
1315     } else {
1316       ShenandoahParallelWorkerSession worker_session(worker_id);
1317       ShenandoahEvacOOMScope oom_evac_scope;
1318       do_work();
1319     }
1320   }
1321 
1322 private:
1323   void do_work() {
1324     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
1325     ShenandoahHeapRegion* r;
1326     while ((r =_cs->claim_next()) != NULL) {
1327       assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());
1328 
1329       _sh->marked_object_iterate(r, &cl);
1330 
1331       if (ShenandoahPacing) {
1332         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
1333       }
1334       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1335         break;
1336       }
1337     }
1338   }
1339 };
1340 
1341 // Unlike ShenandoahEvacuationTask, this iterates over all regions rather than just the collection set.
1342 // This is needed in order to promote humongous start regions if age() >= tenure threshold.
1343 class ShenandoahGenerationalEvacuationTask : public WorkerTask {
1344 private:
1345   ShenandoahHeap* const _sh;
1346   ShenandoahRegionIterator *_regions;
1347   bool _concurrent;
1348 public:
1349   ShenandoahGenerationalEvacuationTask(ShenandoahHeap* sh,
1350                                        ShenandoahRegionIterator* iterator,
1351                                        bool concurrent) :
1352     WorkerTask("Shenandoah Evacuation"),
1353     _sh(sh),
1354     _regions(iterator),
1355     _concurrent(concurrent)
1356   {}
1357 
1358   void work(uint worker_id) {
1359     if (_concurrent) {
1360       ShenandoahConcurrentWorkerSession worker_session(worker_id);
1361       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
1362       ShenandoahEvacOOMScope oom_evac_scope;
1363       do_work();
1364     } else {
1365       ShenandoahParallelWorkerSession worker_session(worker_id);
1366       ShenandoahEvacOOMScope oom_evac_scope;
1367       do_work();
1368     }
1369   }
1370 
1371 private:
1372   void do_work() {
1373     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
1374     ShenandoahHeapRegion* r;
1375     while ((r = _regions->next()) != nullptr) {
1376       log_debug(gc)("GenerationalEvacuationTask do_work(), looking at %s region " SIZE_FORMAT ", (age: %d) [%s, %s]",
1377                     r->is_old()? "old": r->is_young()? "young": "free", r->index(), r->age(),
1378                     r->is_active()? "active": "inactive",
1379                     r->is_humongous()? (r->is_humongous_start()? "humongous_start": "humongous_continuation"): "regular");
1380       if (r->is_cset()) {
1381         assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());
1382         _sh->marked_object_iterate(r, &cl);
1383         if (ShenandoahPacing) {
1384           _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
1385         }
1386       } else if (r->is_young() && r->is_active() && r->is_humongous_start() && (r->age() > InitialTenuringThreshold)) {
1387         // We promote humongous_start regions along with their affiliated continuations during evacuation rather than
1388         // doing this work during a safepoint.  We cannot put humongous regions into the collection set because that
1389         // triggers the load-reference barrier (LRB) to copy on reference fetch.
1390         r->promote_humongous();
1391       }
1392       // else, region is free, or OLD, or not in collection set, or humongous_continuation,
1393       // or is young humongous_start that is too young to be promoted
1394 
1395       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1396         break;
1397       }
1398     }
1399   }
1400 };
1401 
1402 void ShenandoahHeap::evacuate_collection_set(bool concurrent) {
1403   if (ShenandoahHeap::heap()->mode()->is_generational()) {
1404     ShenandoahRegionIterator regions;
1405     ShenandoahGenerationalEvacuationTask task(this, &regions, concurrent);
1406     workers()->run_task(&task);
1407   } else {
1408     ShenandoahEvacuationTask task(this, _collection_set, concurrent);
1409     workers()->run_task(&task);
1410   }
1411 }
1412 
1413 void ShenandoahHeap::trash_cset_regions() {
1414   ShenandoahHeapLocker locker(lock());
1415 
1416   ShenandoahCollectionSet* set = collection_set();
1417   ShenandoahHeapRegion* r;
1418   set->clear_current_index();
1419   while ((r = set->next()) != NULL) {
1420     r->make_trash();
1421   }
1422   collection_set()->clear();
1423 }
1424 
1425 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1426   st->print_cr("Heap Regions:");
1427   st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
1428   st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
1429   st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start, UWM=update watermark");
1430   st->print_cr("SN=alloc sequence number");
1431 
1432   for (size_t i = 0; i < num_regions(); i++) {
1433     get_region(i)->print_on(st);
1434   }
1435 }
1436 
1437 size_t ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
1438   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1439 
1440   oop humongous_obj = cast_to_oop(start->bottom());
1441   size_t size = humongous_obj->size();
1442   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
1443   size_t index = start->index() + required_regions - 1;
1444 
1445   assert(!start->has_live(), "liveness must be zero");
1446 
1447   for(size_t i = 0; i < required_regions; i++) {
1448     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
1449     // as it expects that every region belongs to a humongous region starting with a humongous start region.
1450     ShenandoahHeapRegion* region = get_region(index --);
1451 
1452     assert(region->is_humongous(), "expect correct humongous start or continuation");
1453     assert(!region->is_cset(), "Humongous region should not be in collection set");
1454 
1455     region->make_trash_immediate();
1456   }
1457   return required_regions;
1458 }
1459 
1460 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {
1461 public:
1462   ShenandoahCheckCleanGCLABClosure() {}
1463   void do_thread(Thread* thread) {
1464     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1465     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1466     assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");
1467 
1468     PLAB* plab = ShenandoahThreadLocalData::plab(thread);
1469     assert(plab != NULL, "PLAB should be initialized for %s", thread->name());
1470     assert(plab->words_remaining() == 0, "PLAB should not need retirement");
1471   }
1472 };
1473 
1474 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1475 private:
1476   bool const _resize;
1477 public:
1478   ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}
1479   void do_thread(Thread* thread) {
1480     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1481     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1482     gclab->retire();
1483     if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1484       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1485     }
1486 
1487     PLAB* plab = ShenandoahThreadLocalData::plab(thread);
1488     assert(plab != NULL, "PLAB should be initialized for %s", thread->name());
1489     // TODO; Retiring a PLAB disables it so it cannot support future allocations.  This is overkill.  For old-gen
1490     // regions, the important thing is to make the memory parsable by the remembered-set scanning code that drives
1491     // the update-refs processing that follows.  After the updating of old-gen references is done, it is ok to carve
1492     // this remnant object into smaller pieces during the subsequent evacuation pass, as long as the PLAB is made parsable
1493     // again before the next update-refs phase.
1494     ShenandoahHeap::heap()->retire_plab(plab);
1495     if (_resize && ShenandoahThreadLocalData::plab_size(thread) > 0) {
1496       ShenandoahThreadLocalData::set_plab_size(thread, 0);
1497     }
1498   }
1499 };
1500 
1501 void ShenandoahHeap::labs_make_parsable() {
1502   assert(UseTLAB, "Only call with UseTLAB");
1503 
1504   ShenandoahRetireGCLABClosure cl(false);
1505 
1506   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1507     ThreadLocalAllocBuffer& tlab = t->tlab();
1508     tlab.make_parsable();
1509     cl.do_thread(t);
1510   }
1511 
1512   workers()->threads_do(&cl);
1513 }
1514 
1515 void ShenandoahHeap::tlabs_retire(bool resize) {
1516   assert(UseTLAB, "Only call with UseTLAB");
1517   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");

1535   }
1536   workers()->threads_do(&cl);
1537 #endif
1538 }
1539 
1540 void ShenandoahHeap::gclabs_retire(bool resize) {
1541   assert(UseTLAB, "Only call with UseTLAB");
1542   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1543 
1544   ShenandoahRetireGCLABClosure cl(resize);
1545   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1546     cl.do_thread(t);
1547   }
1548   workers()->threads_do(&cl);
1549 
1550   if (safepoint_workers() != NULL) {
1551     safepoint_workers()->threads_do(&cl);
1552   }
1553 }
1554 
1555 class ShenandoahTagGCLABClosure : public ThreadClosure {
1556 public:
1557   void do_thread(Thread* thread) {
1558     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1559     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1560     if (gclab->words_remaining() > 0) {
1561       ShenandoahHeapRegion* r = ShenandoahHeap::heap()->heap_region_containing(gclab->allocate(0));
1562       r->set_young_lab_flag();
1563     }
1564   }
1565 };
1566 
1567 void ShenandoahHeap::set_young_lab_region_flags() {
1568   if (!UseTLAB) {
1569     return;
1570   }
1571   for (size_t i = 0; i < _num_regions; i++) {
1572     _regions[i]->clear_young_lab_flags();
1573   }
1574   ShenandoahTagGCLABClosure cl;
1575   workers()->threads_do(&cl);
1576   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1577     cl.do_thread(t);
1578     ThreadLocalAllocBuffer& tlab = t->tlab();
1579     if (tlab.end() != NULL) {
1580       ShenandoahHeapRegion* r = heap_region_containing(tlab.start());
1581       r->set_young_lab_flag();
1582     }
1583   }
1584 }
1585 
1586 // Returns size in bytes
1587 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1588   if (ShenandoahElasticTLAB) {
1589     // With Elastic TLABs, return the max allowed size, and let the allocation path
1590     // figure out the safe size for current allocation.
1591     return ShenandoahHeapRegion::max_tlab_size_bytes();
1592   } else {
1593     return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1594   }
1595 }
1596 
1597 size_t ShenandoahHeap::max_tlab_size() const {
1598   // Returns size in words
1599   return ShenandoahHeapRegion::max_tlab_size_words();
1600 }
1601 
1602 void ShenandoahHeap::collect(GCCause::Cause cause) {
1603   control_thread()->request_gc(cause);
1604 }
1605 

1962       if (start >= max) break;
1963 
1964       for (size_t i = cur; i < end; i++) {
1965         ShenandoahHeapRegion* current = _heap->get_region(i);
1966         _blk->heap_region_do(current);
1967       }
1968     }
1969   }
1970 };
1971 
1972 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1973   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1974   if (num_regions() > ShenandoahParallelRegionStride) {
1975     ShenandoahParallelHeapRegionTask task(blk);
1976     workers()->run_task(&task);
1977   } else {
1978     heap_region_iterate(blk);
1979   }
1980 }
1981 























1982 class ShenandoahRendezvousClosure : public HandshakeClosure {
1983 public:
1984   inline ShenandoahRendezvousClosure() : HandshakeClosure("ShenandoahRendezvous") {}
1985   inline void do_thread(Thread* thread) {}
1986 };
1987 
1988 void ShenandoahHeap::rendezvous_threads() {
1989   ShenandoahRendezvousClosure cl;
1990   Handshake::execute(&cl);
1991 }
1992 
1993 void ShenandoahHeap::recycle_trash() {
1994   free_set()->recycle_trash();
1995 }
1996 



































































































1997 void ShenandoahHeap::do_class_unloading() {
1998   _unloader.unload();
1999 }
2000 
2001 void ShenandoahHeap::stw_weak_refs(bool full_gc) {
2002   // Weak refs processing
2003   ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs
2004                                                 : ShenandoahPhaseTimings::degen_gc_weakrefs;
2005   ShenandoahTimingsTracker t(phase);
2006   ShenandoahGCWorkerPhase worker_phase(phase);
2007   active_generation()->ref_processor()->process_references(phase, workers(), false /* concurrent */);
2008 }
2009 
2010 void ShenandoahHeap::prepare_update_heap_references(bool concurrent) {
2011   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2012 
2013   // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to
2014   // make them parsable for update code to work correctly. Plus, we can compute new sizes
2015   // for future GCLABs here.
2016   if (UseTLAB) {
2017     ShenandoahGCPhase phase(concurrent ?
2018                             ShenandoahPhaseTimings::init_update_refs_manage_gclabs :
2019                             ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);
2020     gclabs_retire(ResizeTLAB);
2021   }
2022 
2023   _update_refs_iterator.reset();
2024 }
2025 
2026 void ShenandoahHeap::set_gc_state_all_threads(char state) {
2027   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
2028     ShenandoahThreadLocalData::set_gc_state(t, state);
2029   }
2030 }
2031 
2032 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
2033   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
2034   _gc_state.set_cond(mask, value);
2035   set_gc_state_all_threads(_gc_state.raw_value());
2036 }
2037 
2038 void ShenandoahHeap::set_concurrent_young_mark_in_progress(bool in_progress) {
2039   if (has_forwarded_objects()) {
2040     set_gc_state_mask(YOUNG_MARKING | UPDATEREFS, in_progress);
2041   } else {
2042     set_gc_state_mask(YOUNG_MARKING, in_progress);
2043   }
2044 
2045   manage_satb_barrier(in_progress);
2046 }
2047 
2048 void ShenandoahHeap::set_concurrent_old_mark_in_progress(bool in_progress) {
2049   if (has_forwarded_objects()) {
2050     set_gc_state_mask(OLD_MARKING | UPDATEREFS, in_progress);
2051   } else {
2052     set_gc_state_mask(OLD_MARKING, in_progress);
2053   }
2054 
2055   manage_satb_barrier(in_progress);
2056 }
2057 
2058 void ShenandoahHeap::set_concurrent_prep_for_mixed_evacuation_in_progress(bool in_progress) {
2059   // Unlike other set-gc-state functions, this may happen outside safepoint.
2060   // Is only set and queried by control thread, so no coherence issues.
2061   _prep_for_mixed_evac_in_progress = in_progress;
2062 }
2063 
2064 bool ShenandoahHeap::is_concurrent_prep_for_mixed_evacuation_in_progress() {
2065   return _prep_for_mixed_evac_in_progress;
2066 }
2067 
2068 void ShenandoahHeap::set_aging_cycle(bool in_progress) {
2069   _is_aging_cycle.set_cond(in_progress);
2070 }
2071 
2072 void ShenandoahHeap::manage_satb_barrier(bool active) {
2073   if (is_concurrent_mark_in_progress()) {
2074     // Ignore request to deactivate barrier while concurrent mark is in progress.
2075     // Do not attempt to re-activate the barrier if it is already active.
2076     if (active && !ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2077       ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2078     }
2079   } else {
2080     // No concurrent marking is in progress so honor request to deactivate,
2081     // but only if the barrier is already active.
2082     if (!active && ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2083       ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2084     }
2085   }
2086 }
2087 
2088 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
2089   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
2090   set_gc_state_mask(EVACUATION, in_progress);
2091 }
2092 
2093 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {
2094   if (in_progress) {
2095     _concurrent_strong_root_in_progress.set();
2096   } else {
2097     _concurrent_strong_root_in_progress.unset();
2098   }
2099 }
2100 
2101 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {
2102   set_gc_state_mask(WEAK_ROOTS, cond);
2103 }
2104 
2105 GCTracer* ShenandoahHeap::tracer() {

2110   return _free_set->used();
2111 }
2112 
2113 bool ShenandoahHeap::try_cancel_gc() {
2114   while (true) {
2115     jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
2116     if (prev == CANCELLABLE) return true;
2117     else if (prev == CANCELLED) return false;
2118     assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");
2119     assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");
2120     Thread* thread = Thread::current();
2121     if (thread->is_Java_thread()) {
2122       // We need to provide a safepoint here, otherwise we might
2123       // spin forever if a SP is pending.
2124       ThreadBlockInVM sp(JavaThread::cast(thread));
2125       SpinPause();
2126     }
2127   }
2128 }
2129 
2130 void ShenandoahHeap::cancel_concurrent_mark() {
2131   _young_generation->cancel_marking();
2132   _old_generation->cancel_marking();
2133   _global_generation->cancel_marking();
2134 
2135   ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking();
2136 }
2137 
2138 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
2139   if (try_cancel_gc()) {
2140     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
2141     log_info(gc)("%s", msg.buffer());
2142     Events::log(Thread::current(), "%s", msg.buffer());
2143     _cancel_requested_time = os::elapsedTime();
2144     if (cause == GCCause::_shenandoah_upgrade_to_full_gc) {
2145       _upgraded_to_full = true;
2146     }
2147   }
2148 }
2149 
2150 uint ShenandoahHeap::max_workers() {
2151   return _max_workers;
2152 }
2153 
2154 void ShenandoahHeap::stop() {
2155   // The shutdown sequence should be able to terminate when GC is running.
2156 
2157   // Step 0a. Stop requesting collections.
2158   regulator_thread()->stop();
2159 
2160   // Step 0. Notify policy to disable event recording.
2161   _shenandoah_policy->record_shutdown();
2162 
2163   // Step 1. Notify control thread that we are in shutdown.
2164   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
2165   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
2166   control_thread()->prepare_for_graceful_shutdown();
2167 
2168   // Step 2. Notify GC workers that we are cancelling GC.
2169   cancel_gc(GCCause::_shenandoah_stop_vm);
2170 
2171   // Step 3. Wait until GC worker exits normally.
2172   control_thread()->stop();
2173 }
2174 
2175 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
2176   if (!unload_classes()) return;
2177   // Unload classes and purge SystemDictionary.
2178   {
2179     ShenandoahPhaseTimings::Phase phase = full_gc ?

2244 }
2245 
2246 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2247   set_gc_state_mask(HAS_FORWARDED, cond);
2248 }
2249 
2250 void ShenandoahHeap::set_unload_classes(bool uc) {
2251   _unload_classes.set_cond(uc);
2252 }
2253 
2254 bool ShenandoahHeap::unload_classes() const {
2255   return _unload_classes.is_set();
2256 }
2257 
2258 address ShenandoahHeap::in_cset_fast_test_addr() {
2259   ShenandoahHeap* heap = ShenandoahHeap::heap();
2260   assert(heap->collection_set() != NULL, "Sanity");
2261   return (address) heap->collection_set()->biased_map_address();
2262 }
2263 




2264 address ShenandoahHeap::gc_state_addr() {
2265   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
2266 }
2267 




2268 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2269   if (mode()->is_generational()) {
2270     young_generation()->reset_bytes_allocated_since_gc_start();
2271     old_generation()->reset_bytes_allocated_since_gc_start();
2272   }
2273 
2274   global_generation()->reset_bytes_allocated_since_gc_start();
2275 }
2276 
2277 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2278   _degenerated_gc_in_progress.set_cond(in_progress);
2279 }
2280 
2281 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2282   _full_gc_in_progress.set_cond(in_progress);
2283 }
2284 
2285 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2286   assert (is_full_gc_in_progress(), "should be");
2287   _full_gc_move_in_progress.set_cond(in_progress);
2288 }
2289 
2290 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2291   set_gc_state_mask(UPDATEREFS, in_progress);
2292 }
2293 
2294 void ShenandoahHeap::register_nmethod(nmethod* nm) {

2323     if (r->is_active()) {
2324       if (r->is_pinned()) {
2325         if (r->pin_count() == 0) {
2326           r->make_unpinned();
2327         }
2328       } else {
2329         if (r->pin_count() > 0) {
2330           r->make_pinned();
2331         }
2332       }
2333     }
2334   }
2335 
2336   assert_pinned_region_status();
2337 }
2338 
2339 #ifdef ASSERT
2340 void ShenandoahHeap::assert_pinned_region_status() {
2341   for (size_t i = 0; i < num_regions(); i++) {
2342     ShenandoahHeapRegion* r = get_region(i);
2343     if (active_generation()->contains(r)) {
2344       assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
2345              "Region " SIZE_FORMAT " pinning status is inconsistent", i);
2346     }
2347   }
2348 }
2349 #endif
2350 
2351 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {
2352   return _gc_timer;
2353 }
2354 
2355 void ShenandoahHeap::prepare_concurrent_roots() {
2356   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2357   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
2358   set_concurrent_strong_root_in_progress(!collection_set()->is_empty());
2359   set_concurrent_weak_root_in_progress(true);
2360   if (unload_classes()) {
2361     _unloader.prepare();
2362   }
2363 }
2364 
2365 void ShenandoahHeap::finish_concurrent_roots() {
2366   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");

2386       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2387     } else {
2388       // Use ConcGCThreads outside safepoints
2389       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2390     }
2391   }
2392 }
2393 #endif
2394 
2395 ShenandoahVerifier* ShenandoahHeap::verifier() {
2396   guarantee(ShenandoahVerify, "Should be enabled");
2397   assert (_verifier != NULL, "sanity");
2398   return _verifier;
2399 }
2400 
2401 template<bool CONCURRENT>
2402 class ShenandoahUpdateHeapRefsTask : public WorkerTask {
2403 private:
2404   ShenandoahHeap* _heap;
2405   ShenandoahRegionIterator* _regions;
2406 
2407 public:
2408   explicit ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :
2409     WorkerTask("Shenandoah Update References"),
2410     _heap(ShenandoahHeap::heap()),
2411     _regions(regions)
2412   {
2413   }
2414 
2415   void work(uint worker_id) {
2416     if (CONCURRENT) {
2417       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2418       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2419       do_work<ShenandoahConcUpdateRefsClosure>(worker_id);
2420     } else {
2421       ShenandoahParallelWorkerSession worker_session(worker_id);
2422       do_work<ShenandoahSTWUpdateRefsClosure>(worker_id);
2423     }
2424   }
2425 
2426 private:
2427   template<class T>
2428   void do_work(uint worker_id) {
2429     T cl;
2430     ShenandoahHeapRegion* r = _regions->next();
2431 
2432     // We update references for global, old, and young collections.
2433     assert(_heap->active_generation()->is_mark_complete(), "Expected complete marking");
2434     ShenandoahMarkingContext* const ctx = _heap->marking_context();
2435     bool is_mixed = _heap->collection_set()->has_old_regions();
2436     while (r != NULL) {
2437       HeapWord* update_watermark = r->get_update_watermark();
2438       assert (update_watermark >= r->bottom(), "sanity");
2439 
2440       log_debug(gc)("ShenandoahUpdateHeapRefsTask::do_work(%u) looking at region " SIZE_FORMAT, worker_id, r->index());
2441       if (r->is_active() && !r->is_cset()) {
2442         if (!_heap->mode()->is_generational() || (r->affiliation() == ShenandoahRegionAffiliation::YOUNG_GENERATION)) {
2443           _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2444         } else if (r->affiliation() == ShenandoahRegionAffiliation::OLD_GENERATION) {
2445           if (_heap->active_generation()->generation_mode() == GLOBAL) {
2446             _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2447           } else {
2448             // Old region in a young cycle or mixed cycle.
2449             if (!is_mixed) {
2450               // This is a young evac..
2451               _heap->card_scan()->process_region(r, &cl, true);
2452             } else {
2453               // This is a _mixed_evac.
2454               //
2455               // TODO: For _mixed_evac, consider building an old-gen remembered set that allows restricted updating
2456               // within old-gen HeapRegions.  This remembered set can be constructed by old-gen concurrent marking
2457               // and augmented by card marking.  For example, old-gen concurrent marking can remember for each old-gen
2458               // card which other old-gen regions it refers to: none, one-other specifically, multiple-other non-specific.
2459               // Update-references when _mixed_evac processess each old-gen memory range that has a traditional DIRTY
2460               // card or if the "old-gen remembered set" indicates that this card holds pointers specifically to an
2461               // old-gen region in the most recent collection set, or if this card holds pointers to other non-specific
2462               // old-gen heap regions.
2463               if (r->is_humongous()) {
2464                 r->oop_iterate_humongous(&cl);
2465               } else {
2466                 // This is a mixed evacuation.  Old regions that are candidates for collection have not been coalesced
2467                 // and filled.  Use mark bits to find objects that need to be updated.
2468                 //
2469                 // Future TODO: establish a second remembered set to identify which old-gen regions point to other old-gen
2470                 // regions which are in the collection set for a particular mixed evacuation.
2471                 HeapWord *p = r->bottom();
2472                 ShenandoahObjectToOopBoundedClosure<T> objs(&cl, p, update_watermark);
2473 
2474                 // Anything beyond update_watermark was allocated during evacuation.  Thus, it is known to not hold
2475                 // references to collection set objects.
2476                 while (p < update_watermark) {
2477                   oop obj = cast_to_oop(p);
2478                   if (ctx->is_marked(obj)) {
2479                     objs.do_object(obj);
2480                     p += obj->size();
2481                   } else {
2482                     // This object is not marked so we don't scan it.
2483                     HeapWord* tams = ctx->top_at_mark_start(r);
2484                     if (p >= tams) {
2485                       p += obj->size();
2486                     } else {
2487                       p = ctx->get_next_marked_addr(p, tams);
2488                     }
2489                   }
2490                 }
2491               }
2492             }
2493           }
2494         } else {
2495           // Because updating of references runs concurrently, it is possible that a FREE inactive region transitions
2496           // to a non-free active region while this loop is executing.  Whenever this happens, the changing of a region's
2497           // active status may propagate at a different speed than the changing of the region's affiliation.
2498 
2499           // When we reach this control point, it is because a race has allowed a region's is_active() status to be seen
2500           // by this thread before the region's affiliation() is seen by this thread.
2501 
2502           // It's ok for this race to occur because the newly transformed region does not have any references to be
2503           // updated.
2504 
2505           assert(r->get_update_watermark() == r->bottom(),
2506                  "%s Region " SIZE_FORMAT " is_active but not recognized as YOUNG or OLD so must be newly transitioned from FREE",
2507                  affiliation_name(r->affiliation()), r->index());
2508         }
2509       }
2510       if (ShenandoahPacing) {
2511         _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom()));
2512       }
2513       if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
2514         return;
2515       }
2516       r = _regions->next();
2517     }
2518   }
2519 };
2520 
2521 void ShenandoahHeap::update_heap_references(bool concurrent) {
2522   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2523 
2524   if (concurrent) {
2525     ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);
2526     workers()->run_task(&task);
2527   } else {
2528     ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);
2529     workers()->run_task(&task);
2530   }
2531 }
2532 
2533 
2534 class ShenandoahFinalUpdateRefsUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
2535 private:
2536   ShenandoahMarkingContext* _ctx;
2537   ShenandoahHeapLock* const _lock;
2538   bool _is_generational;
2539 
2540 public:
2541   ShenandoahFinalUpdateRefsUpdateRegionStateClosure(
2542     ShenandoahMarkingContext* ctx) : _ctx(ctx), _lock(ShenandoahHeap::heap()->lock()),
2543                                      _is_generational(ShenandoahHeap::heap()->mode()->is_generational()) { }
2544 
2545   void heap_region_do(ShenandoahHeapRegion* r) {
2546 
2547     // Maintenance of region age must follow evacuation in order to account for evacuation allocations within survivor
2548     // regions.  We consult region age during the subsequent evacuation to determine whether certain objects need to
2549     // be promoted.
2550     if (_is_generational && r->is_young()) {
2551       HeapWord *tams = _ctx->top_at_mark_start(r);
2552       HeapWord *top = r->top();
2553 
2554       // Allocations move the watermark when top moves.  However compacting
2555       // objects will sometimes lower top beneath the watermark, after which,
2556       // attempts to read the watermark will assert out (watermark should not be
2557       // higher than top).
2558       if (top > tams) {
2559         // There have been allocations in this region since the start of the cycle.
2560         // Any objects new to this region must not assimilate elevated age.
2561         r->reset_age();
2562       } else if (ShenandoahHeap::heap()->is_aging_cycle()) {
2563         r->increment_age();
2564       }
2565     }
2566 
2567     // Drop unnecessary "pinned" state from regions that does not have CP marks
2568     // anymore, as this would allow trashing them.

2569     if (r->is_active()) {
2570       if (r->is_pinned()) {
2571         if (r->pin_count() == 0) {
2572           ShenandoahHeapLocker locker(_lock);
2573           r->make_unpinned();
2574         }
2575       } else {
2576         if (r->pin_count() > 0) {
2577           ShenandoahHeapLocker locker(_lock);
2578           r->make_pinned();
2579         }
2580       }
2581     }
2582   }
2583 
2584   bool is_thread_safe() { return true; }
2585 };
2586 
2587 void ShenandoahHeap::update_heap_region_states(bool concurrent) {
2588   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2589   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2590 
2591   {
2592     ShenandoahGCPhase phase(concurrent ?
2593                             ShenandoahPhaseTimings::final_update_refs_update_region_states :
2594                             ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);
2595     ShenandoahFinalUpdateRefsUpdateRegionStateClosure cl (active_generation()->complete_marking_context());
2596     parallel_heap_region_iterate(&cl);
2597 
2598     assert_pinned_region_status();
2599   }
2600 
2601   {
2602     ShenandoahGCPhase phase(concurrent ?
2603                             ShenandoahPhaseTimings::final_update_refs_trash_cset :
2604                             ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);
2605     trash_cset_regions();
2606   }
2607 }
2608 
2609 void ShenandoahHeap::rebuild_free_set(bool concurrent) {
2610   {
2611     ShenandoahGCPhase phase(concurrent ?
2612                             ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :
2613                             ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);
2614     ShenandoahHeapLocker locker(lock());
2615     _free_set->rebuild();

2709   EventMark em("%s", msg);
2710 
2711   op_uncommit(shrink_before, shrink_until);
2712 }
2713 
2714 void ShenandoahHeap::try_inject_alloc_failure() {
2715   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2716     _inject_alloc_failure.set();
2717     os::naked_short_sleep(1);
2718     if (cancelled_gc()) {
2719       log_info(gc)("Allocation failure was successfully injected");
2720     }
2721   }
2722 }
2723 
2724 bool ShenandoahHeap::should_inject_alloc_failure() {
2725   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2726 }
2727 
2728 void ShenandoahHeap::initialize_serviceability() {
2729   if (mode()->is_generational()) {
2730     _young_gen_memory_pool = new ShenandoahYoungGenMemoryPool(this);
2731     _old_gen_memory_pool = new ShenandoahOldGenMemoryPool(this);
2732     _cycle_memory_manager.add_pool(_young_gen_memory_pool);
2733     _cycle_memory_manager.add_pool(_old_gen_memory_pool);
2734     _stw_memory_manager.add_pool(_young_gen_memory_pool);
2735     _stw_memory_manager.add_pool(_old_gen_memory_pool);
2736   } else {
2737     _memory_pool = new ShenandoahMemoryPool(this);
2738     _cycle_memory_manager.add_pool(_memory_pool);
2739     _stw_memory_manager.add_pool(_memory_pool);
2740   }
2741 }
2742 
2743 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2744   GrowableArray<GCMemoryManager*> memory_managers(2);
2745   memory_managers.append(&_cycle_memory_manager);
2746   memory_managers.append(&_stw_memory_manager);
2747   return memory_managers;
2748 }
2749 
2750 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2751   GrowableArray<MemoryPool*> memory_pools(1);
2752   if (mode()->is_generational()) {
2753     memory_pools.append(_young_gen_memory_pool);
2754     memory_pools.append(_old_gen_memory_pool);
2755   } else {
2756     memory_pools.append(_memory_pool);
2757   }
2758   return memory_pools;
2759 }
2760 
2761 MemoryUsage ShenandoahHeap::memory_usage() {
2762   return MemoryUsage(_initial_size, used(), committed(), max_capacity());
2763 }
2764 
2765 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2766   _heap(ShenandoahHeap::heap()),
2767   _index(0) {}
2768 
2769 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2770   _heap(heap),
2771   _index(0) {}
2772 
2773 void ShenandoahRegionIterator::reset() {
2774   _index = 0;
2775 }
2776 
2777 bool ShenandoahRegionIterator::has_next() const {
2778   return _index < _heap->num_regions();
2779 }
2780 
2781 char ShenandoahHeap::gc_state() const {
2782   return _gc_state.raw_value();
2783 }
2784 
2785 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2786 #ifdef ASSERT
2787   assert(_liveness_cache != NULL, "sanity");
2788   assert(worker_id < _max_workers, "sanity");
2789   for (uint i = 0; i < num_regions(); i++) {
2790     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2791   }
2792 #endif
2793   return _liveness_cache[worker_id];
2794 }
2795 
2796 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2797   assert(worker_id < _max_workers, "sanity");
2798   assert(_liveness_cache != NULL, "sanity");
2799   ShenandoahLiveData* ld = _liveness_cache[worker_id];
2800 
2801   for (uint i = 0; i < num_regions(); i++) {
2802     ShenandoahLiveData live = ld[i];
2803     if (live > 0) {
2804       ShenandoahHeapRegion* r = get_region(i);
2805       r->increase_live_data_gc_words(live);
2806       ld[i] = 0;
2807     }
2808   }
2809 }
2810 
2811 void ShenandoahHeap::transfer_old_pointers_from_satb() {
2812   ((ShenandoahOldGeneration*) _old_generation)->transfer_pointers_from_satb();
2813 }
2814 
2815 template<>
2816 void ShenandoahGenerationRegionClosure<YOUNG>::heap_region_do(ShenandoahHeapRegion* region) {
2817   // Visit young and free regions
2818   if (region->affiliation() != OLD_GENERATION) {
2819     _cl->heap_region_do(region);
2820   }
2821 }
2822 
2823 template<>
2824 void ShenandoahGenerationRegionClosure<OLD>::heap_region_do(ShenandoahHeapRegion* region) {
2825   // Visit old and free regions
2826   if (region->affiliation() != YOUNG_GENERATION) {
2827     _cl->heap_region_do(region);
2828   }
2829 }
2830 
2831 template<>
2832 void ShenandoahGenerationRegionClosure<GLOBAL>::heap_region_do(ShenandoahHeapRegion* region) {
2833   _cl->heap_region_do(region);
2834 }
2835 
2836 // Assure that the remember set has a dirty card everywhere there is an interesting pointer.
2837 // This examines the read_card_table between bottom() and top() since all PLABS are retired
2838 // before the safepoint for init_mark.  Actually, we retire them before update-references and don't
2839 // restore them until the start of evacuation.
2840 void ShenandoahHeap::verify_rem_set_at_mark() {
2841   shenandoah_assert_safepoint();
2842   assert(mode()->is_generational(), "Only verify remembered set for generational operational modes");
2843 
2844   ShenandoahRegionIterator iterator;
2845   RememberedScanner* scanner = card_scan();
2846   ShenandoahVerifyRemSetClosure check_interesting_pointers(true);
2847   ShenandoahMarkingContext* ctx;
2848 
2849   log_debug(gc)("Verifying remembered set at %s mark", doing_mixed_evacuations()? "mixed": "young");
2850 
2851   if (doing_mixed_evacuations() ||
2852       is_concurrent_prep_for_mixed_evacuation_in_progress() || active_generation()->generation_mode() == GLOBAL) {
2853     ctx = complete_marking_context();
2854   } else {
2855     ctx = nullptr;
2856   }
2857 
2858   while (iterator.has_next()) {
2859     ShenandoahHeapRegion* r = iterator.next();
2860     if (r == nullptr)
2861       break;
2862     if (r->is_old() && r->is_active()) {
2863       HeapWord* obj_addr = r->bottom();
2864       if (r->is_humongous_start()) {
2865         oop obj = cast_to_oop(obj_addr);
2866         if (!ctx || ctx->is_marked(obj)) {
2867           // For humongous objects, the typical object is an array, so the following checks may be overkill
2868           // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2869           // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2870           if (!scanner->is_card_dirty(obj_addr) || obj->is_objArray()) {
2871             obj->oop_iterate(&check_interesting_pointers);
2872           }
2873           // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2874         }
2875         // else, this humongous object is not marked so no need to verify its internal pointers
2876         if (!scanner->verify_registration(obj_addr, ctx)) {
2877           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL,
2878                                           "Verify init-mark remembered set violation", "object not properly registered", __FILE__, __LINE__);
2879         }
2880       } else if (!r->is_humongous()) {
2881         HeapWord* top = r->top();
2882         while (obj_addr < top) {
2883           oop obj = cast_to_oop(obj_addr);
2884           // ctx->is_marked() returns true if mark bit set (TAMS not relevant during init mark)
2885           if (!ctx || ctx->is_marked(obj)) {
2886             // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2887             // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2888             if (!scanner->is_card_dirty(obj_addr) || obj->is_objArray()) {
2889               obj->oop_iterate(&check_interesting_pointers);
2890             }
2891             // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2892             if (!scanner->verify_registration(obj_addr, ctx)) {
2893               ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL,
2894                                             "Verify init-mark remembered set violation", "object not properly registered", __FILE__, __LINE__);
2895             }
2896             obj_addr += obj->size();
2897           } else {
2898             // This object is not live so we don't verify dirty cards contained therein
2899             assert(ctx->top_at_mark_start(r) == top, "Expect tams == top at start of mark.");
2900             obj_addr = ctx->get_next_marked_addr(obj_addr, top);
2901           }
2902         }
2903       } // else, we ignore humongous continuation region
2904     } // else, this is not an OLD region so we ignore it
2905   } // all regions have been processed
2906 }
2907 
2908 void ShenandoahHeap::help_verify_region_rem_set(ShenandoahHeapRegion* r, ShenandoahMarkingContext* ctx, HeapWord* from,
2909                                                 HeapWord* top, HeapWord* registration_watermark, const char* message) {
2910   RememberedScanner* scanner = card_scan();
2911   ShenandoahVerifyRemSetClosure check_interesting_pointers(false);
2912 
2913   HeapWord* obj_addr = from;
2914   if (r->is_humongous_start()) {
2915     oop obj = cast_to_oop(obj_addr);
2916     if (!ctx || ctx->is_marked(obj)) {
2917       size_t card_index = scanner->card_index_for_addr(obj_addr);
2918       // For humongous objects, the typical object is an array, so the following checks may be overkill
2919       // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2920       // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2921       if (!scanner->is_write_card_dirty(card_index) || obj->is_objArray()) {
2922         obj->oop_iterate(&check_interesting_pointers);
2923       }
2924       // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2925     }
2926     // else, this humongous object is not live so no need to verify its internal pointers
2927 
2928     if ((obj_addr < registration_watermark) && !scanner->verify_registration(obj_addr, ctx)) {
2929       ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL, message,
2930                                        "object not properly registered", __FILE__, __LINE__);
2931     }
2932   } else if (!r->is_humongous()) {
2933     while (obj_addr < top) {
2934       oop obj = cast_to_oop(obj_addr);
2935       // ctx->is_marked() returns true if mark bit set or if obj above TAMS.
2936       if (!ctx || ctx->is_marked(obj)) {
2937         size_t card_index = scanner->card_index_for_addr(obj_addr);
2938         // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2939         // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2940         if (!scanner->is_write_card_dirty(card_index) || obj->is_objArray()) {
2941           obj->oop_iterate(&check_interesting_pointers);
2942         }
2943         // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2944 
2945         if ((obj_addr < registration_watermark) && !scanner->verify_registration(obj_addr, ctx)) {
2946           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL, message,
2947                                            "object not properly registered", __FILE__, __LINE__);
2948         }
2949         obj_addr += obj->size();
2950       } else {
2951         // This object is not live so we don't verify dirty cards contained therein
2952         HeapWord* tams = ctx->top_at_mark_start(r);
2953         obj_addr = ctx->get_next_marked_addr(obj_addr, tams);
2954       }
2955     }
2956   }
2957 }
2958 
2959 void ShenandoahHeap::verify_rem_set_after_full_gc() {
2960   shenandoah_assert_safepoint();
2961   assert(mode()->is_generational(), "Only verify remembered set for generational operational modes");
2962 
2963   ShenandoahRegionIterator iterator;
2964 
2965   while (iterator.has_next()) {
2966     ShenandoahHeapRegion* r = iterator.next();
2967     if (r == nullptr)
2968       break;
2969     if (r->is_old() && !r->is_cset()) {
2970       help_verify_region_rem_set(r, nullptr, r->bottom(), r->top(), r->top(), "Remembered set violation at end of Full GC");
2971     }
2972   }
2973 }
2974 
2975 // Assure that the remember set has a dirty card everywhere there is an interesting pointer.  Even though
2976 // the update-references scan of remembered set only examines cards up to update_watermark, the remembered
2977 // set should be valid through top.  This examines the write_card_table between bottom() and top() because
2978 // all PLABS are retired immediately before the start of update refs.
2979 void ShenandoahHeap::verify_rem_set_at_update_ref() {
2980   shenandoah_assert_safepoint();
2981   assert(mode()->is_generational(), "Only verify remembered set for generational operational modes");
2982 
2983   ShenandoahRegionIterator iterator;
2984   ShenandoahMarkingContext* ctx;
2985 
2986   if (doing_mixed_evacuations() ||
2987       is_concurrent_prep_for_mixed_evacuation_in_progress() || active_generation()->generation_mode() == GLOBAL) {
2988     ctx = complete_marking_context();
2989   } else {
2990     ctx = nullptr;
2991   }
2992 
2993   while (iterator.has_next()) {
2994     ShenandoahHeapRegion* r = iterator.next();
2995     if (r == nullptr)
2996       break;
2997     if (r->is_old() && !r->is_cset()) {
2998       help_verify_region_rem_set(r, ctx, r->bottom(), r->top(), r->get_update_watermark(),
2999                                  "Remembered set violation at init-update-references");
3000     }
3001   }
3002 }
3003 
3004 ShenandoahGeneration* ShenandoahHeap::generation_for(ShenandoahRegionAffiliation affiliation) const {
3005   if (!mode()->is_generational()) {
3006     return global_generation();
3007   } else if (affiliation == YOUNG_GENERATION) {
3008     return young_generation();
3009   } else if (affiliation == OLD_GENERATION) {
3010     return old_generation();
3011   }
3012 
3013   ShouldNotReachHere();
3014   return nullptr;
3015 }
< prev index next >