1 /*
   2  * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "classfile/classLoaderDataGraph.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/parallel/objectStartArray.inline.hpp"
  34 #include "gc/parallel/parallelArguments.hpp"
  35 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  36 #include "gc/parallel/parMarkBitMap.inline.hpp"
  37 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
  38 #include "gc/parallel/psCompactionManager.inline.hpp"
  39 #include "gc/parallel/psOldGen.hpp"
  40 #include "gc/parallel/psParallelCompact.inline.hpp"
  41 #include "gc/parallel/psPromotionManager.inline.hpp"
  42 #include "gc/parallel/psRootType.hpp"
  43 #include "gc/parallel/psScavenge.hpp"
  44 #include "gc/parallel/psStringDedup.hpp"
  45 #include "gc/parallel/psYoungGen.hpp"
  46 #include "gc/shared/classUnloadingContext.hpp"
  47 #include "gc/shared/fullGCForwarding.inline.hpp"
  48 #include "gc/shared/gcCause.hpp"
  49 #include "gc/shared/gcHeapSummary.hpp"
  50 #include "gc/shared/gcId.hpp"
  51 #include "gc/shared/gcLocker.hpp"
  52 #include "gc/shared/gcTimer.hpp"
  53 #include "gc/shared/gcTrace.hpp"
  54 #include "gc/shared/gcTraceTime.inline.hpp"
  55 #include "gc/shared/gcVMOperations.hpp"
  56 #include "gc/shared/isGCActiveMark.hpp"
  57 #include "gc/shared/oopStorage.inline.hpp"
  58 #include "gc/shared/oopStorageSet.inline.hpp"
  59 #include "gc/shared/oopStorageSetParState.inline.hpp"
  60 #include "gc/shared/parallelCleaning.hpp"
  61 #include "gc/shared/preservedMarks.inline.hpp"
  62 #include "gc/shared/referencePolicy.hpp"
  63 #include "gc/shared/referenceProcessor.hpp"
  64 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
  65 #include "gc/shared/spaceDecorator.hpp"
  66 #include "gc/shared/taskTerminator.hpp"
  67 #include "gc/shared/weakProcessor.inline.hpp"
  68 #include "gc/shared/workerPolicy.hpp"
  69 #include "gc/shared/workerThread.hpp"
  70 #include "gc/shared/workerUtils.hpp"
  71 #include "logging/log.hpp"
  72 #include "memory/iterator.inline.hpp"
  73 #include "memory/memoryReserver.hpp"
  74 #include "memory/metaspaceUtils.hpp"
  75 #include "memory/resourceArea.hpp"
  76 #include "memory/universe.hpp"
  77 #include "nmt/memTracker.hpp"
  78 #include "oops/access.inline.hpp"
  79 #include "oops/flatArrayKlass.inline.hpp"
  80 #include "oops/instanceClassLoaderKlass.inline.hpp"
  81 #include "oops/instanceKlass.inline.hpp"
  82 #include "oops/instanceMirrorKlass.inline.hpp"
  83 #include "oops/methodData.hpp"
  84 #include "oops/objArrayKlass.inline.hpp"
  85 #include "oops/oop.inline.hpp"
  86 #include "runtime/arguments.hpp"
  87 #include "runtime/atomicAccess.hpp"
  88 #include "runtime/handles.inline.hpp"
  89 #include "runtime/java.hpp"
  90 #include "runtime/safepoint.hpp"
  91 #include "runtime/threads.hpp"
  92 #include "runtime/vmThread.hpp"
  93 #include "services/memoryService.hpp"
  94 #include "utilities/align.hpp"
  95 #include "utilities/debug.hpp"
  96 #include "utilities/events.hpp"
  97 #include "utilities/formatBuffer.hpp"
  98 #include "utilities/macros.hpp"
  99 #include "utilities/stack.inline.hpp"
 100 #if INCLUDE_JVMCI
 101 #include "jvmci/jvmci.hpp"
 102 #endif
 103 
 104 #include <math.h>
 105 
 106 // All sizes are in HeapWords.
 107 const size_t ParallelCompactData::Log2RegionSize  = 16; // 64K words
 108 const size_t ParallelCompactData::RegionSize      = (size_t)1 << Log2RegionSize;
 109 static_assert(ParallelCompactData::RegionSize >= BitsPerWord, "region-start bit word-aligned");
 110 const size_t ParallelCompactData::RegionSizeBytes =
 111   RegionSize << LogHeapWordSize;
 112 const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
 113 const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
 114 const size_t ParallelCompactData::RegionAddrMask       = ~RegionAddrOffsetMask;
 115 
 116 const ParallelCompactData::RegionData::region_sz_t
 117 ParallelCompactData::RegionData::dc_shift = 27;
 118 
 119 const ParallelCompactData::RegionData::region_sz_t
 120 ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
 121 
 122 const ParallelCompactData::RegionData::region_sz_t
 123 ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
 124 
 125 const ParallelCompactData::RegionData::region_sz_t
 126 ParallelCompactData::RegionData::los_mask = ~dc_mask;
 127 
 128 const ParallelCompactData::RegionData::region_sz_t
 129 ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
 130 
 131 const ParallelCompactData::RegionData::region_sz_t
 132 ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
 133 
 134 bool ParallelCompactData::RegionData::is_clear() {
 135   return (_destination == nullptr) &&
 136          (_source_region == 0) &&
 137          (_partial_obj_addr == nullptr) &&
 138          (_partial_obj_size == 0) &&
 139          (_dc_and_los == 0) &&
 140          (_shadow_state == 0);
 141 }
 142 
 143 #ifdef ASSERT
 144 void ParallelCompactData::RegionData::verify_clear() {
 145   assert(_destination == nullptr, "inv");
 146   assert(_source_region == 0, "inv");
 147   assert(_partial_obj_addr == nullptr, "inv");
 148   assert(_partial_obj_size == 0, "inv");
 149   assert(_dc_and_los == 0, "inv");
 150   assert(_shadow_state == 0, "inv");
 151 }
 152 #endif
 153 
 154 SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
 155 
 156 SpanSubjectToDiscoveryClosure PSParallelCompact::_span_based_discoverer;
 157 ReferenceProcessor* PSParallelCompact::_ref_processor = nullptr;
 158 
 159 void SplitInfo::record(size_t split_region_idx, HeapWord* split_point, size_t preceding_live_words) {
 160   assert(split_region_idx != 0, "precondition");
 161 
 162   // Obj denoted by split_point will be deferred to the next space.
 163   assert(split_point != nullptr, "precondition");
 164 
 165   const ParallelCompactData& sd = PSParallelCompact::summary_data();
 166 
 167   PSParallelCompact::RegionData* split_region_ptr = sd.region(split_region_idx);
 168   assert(preceding_live_words < split_region_ptr->data_size(), "inv");
 169 
 170   HeapWord* preceding_destination = split_region_ptr->destination();
 171   assert(preceding_destination != nullptr, "inv");
 172 
 173   // How many regions does the preceding part occupy
 174   uint preceding_destination_count;
 175   if (preceding_live_words == 0) {
 176     preceding_destination_count = 0;
 177   } else {
 178     // -1 so that the ending address doesn't fall on the region-boundary
 179     if (sd.region_align_down(preceding_destination) ==
 180         sd.region_align_down(preceding_destination + preceding_live_words - 1)) {
 181       preceding_destination_count = 1;
 182     } else {
 183       preceding_destination_count = 2;
 184     }
 185   }
 186 
 187   _split_region_idx = split_region_idx;
 188   _split_point = split_point;
 189   _preceding_live_words = preceding_live_words;
 190   _preceding_destination = preceding_destination;
 191   _preceding_destination_count = preceding_destination_count;
 192 }
 193 
 194 void SplitInfo::clear()
 195 {
 196   _split_region_idx = 0;
 197   _split_point = nullptr;
 198   _preceding_live_words = 0;
 199   _preceding_destination = nullptr;
 200   _preceding_destination_count = 0;
 201   assert(!is_valid(), "sanity");
 202 }
 203 
 204 #ifdef  ASSERT
 205 void SplitInfo::verify_clear()
 206 {
 207   assert(_split_region_idx == 0, "not clear");
 208   assert(_split_point == nullptr, "not clear");
 209   assert(_preceding_live_words == 0, "not clear");
 210   assert(_preceding_destination == nullptr, "not clear");
 211   assert(_preceding_destination_count == 0, "not clear");
 212 }
 213 #endif  // #ifdef ASSERT
 214 
 215 
 216 void PSParallelCompact::print_on(outputStream* st) {
 217   _mark_bitmap.print_on(st);
 218 }
 219 
 220 ParallelCompactData::ParallelCompactData() :
 221   _heap_start(nullptr),
 222   DEBUG_ONLY(_heap_end(nullptr) COMMA)
 223   _region_vspace(nullptr),
 224   _reserved_byte_size(0),
 225   _region_data(nullptr),
 226   _region_count(0) {}
 227 
 228 bool ParallelCompactData::initialize(MemRegion reserved_heap)
 229 {
 230   _heap_start = reserved_heap.start();
 231   const size_t heap_size = reserved_heap.word_size();
 232   DEBUG_ONLY(_heap_end = _heap_start + heap_size;)
 233 
 234   assert(region_align_down(_heap_start) == _heap_start,
 235          "region start not aligned");
 236 
 237   return initialize_region_data(heap_size);
 238 }
 239 
 240 PSVirtualSpace*
 241 ParallelCompactData::create_vspace(size_t count, size_t element_size)
 242 {
 243   const size_t raw_bytes = count * element_size;
 244   const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);
 245   const size_t granularity = os::vm_allocation_granularity();
 246   const size_t rs_align = MAX2(page_sz, granularity);
 247 
 248   _reserved_byte_size = align_up(raw_bytes, rs_align);
 249 
 250   ReservedSpace rs = MemoryReserver::reserve(_reserved_byte_size,
 251                                              rs_align,
 252                                              page_sz,
 253                                              mtGC);
 254 
 255   if (!rs.is_reserved()) {
 256     // Failed to reserve memory.
 257     return nullptr;
 258   }
 259 
 260   os::trace_page_sizes("Parallel Compact Data", raw_bytes, raw_bytes, rs.base(),
 261                        rs.size(), page_sz);
 262 
 263   MemTracker::record_virtual_memory_tag(rs, mtGC);
 264 
 265   PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
 266 
 267   if (!vspace->expand_by(_reserved_byte_size)) {
 268     // Failed to commit memory.
 269 
 270     delete vspace;
 271 
 272     // Release memory reserved in the space.
 273     MemoryReserver::release(rs);
 274 
 275     return nullptr;
 276   }
 277 
 278   return vspace;
 279 }
 280 
 281 bool ParallelCompactData::initialize_region_data(size_t heap_size)
 282 {
 283   assert(is_aligned(heap_size, RegionSize), "precondition");
 284 
 285   const size_t count = heap_size >> Log2RegionSize;
 286   _region_vspace = create_vspace(count, sizeof(RegionData));
 287   if (_region_vspace != nullptr) {
 288     _region_data = (RegionData*)_region_vspace->reserved_low_addr();
 289     _region_count = count;
 290     return true;
 291   }
 292   return false;
 293 }
 294 
 295 void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
 296   assert(beg_region <= _region_count, "beg_region out of range");
 297   assert(end_region <= _region_count, "end_region out of range");
 298 
 299   const size_t region_cnt = end_region - beg_region;
 300   memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));
 301 }
 302 
 303 // The total live words on src_region would overflow the target space, so find
 304 // the overflowing object and record the split point. The invariant is that an
 305 // obj should not cross space boundary.
 306 HeapWord* ParallelCompactData::summarize_split_space(size_t src_region,
 307                                                      SplitInfo& split_info,
 308                                                      HeapWord* const destination,
 309                                                      HeapWord* const target_end,
 310                                                      HeapWord** target_next) {
 311   assert(destination <= target_end, "sanity");
 312   assert(destination + _region_data[src_region].data_size() > target_end,
 313     "region should not fit into target space");
 314   assert(is_region_aligned(target_end), "sanity");
 315 
 316   size_t partial_obj_size = _region_data[src_region].partial_obj_size();
 317 
 318   if (destination + partial_obj_size > target_end) {
 319     assert(partial_obj_size > 0, "inv");
 320     // The overflowing obj is from a previous region.
 321     //
 322     // source-regions:
 323     //
 324     // ***************
 325     // |     A|AA    |
 326     // ***************
 327     //       ^
 328     //       | split-point
 329     //
 330     // dest-region:
 331     //
 332     // ********
 333     // |~~~~A |
 334     // ********
 335     //       ^^
 336     //       || target-space-end
 337     //       |
 338     //       | destination
 339     //
 340     // AAA would overflow target-space.
 341     //
 342     HeapWord* overflowing_obj = _region_data[src_region].partial_obj_addr();
 343     size_t split_region = addr_to_region_idx(overflowing_obj);
 344 
 345     // The number of live words before the overflowing object on this split region
 346     size_t preceding_live_words;
 347     if (is_region_aligned(overflowing_obj)) {
 348       preceding_live_words = 0;
 349     } else {
 350       // Words accounted by the overflowing object on the split region
 351       size_t overflowing_size = pointer_delta(region_align_up(overflowing_obj), overflowing_obj);
 352       preceding_live_words = region(split_region)->data_size() - overflowing_size;
 353     }
 354 
 355     split_info.record(split_region, overflowing_obj, preceding_live_words);
 356 
 357     // The [overflowing_obj, src_region_start) part has been accounted for, so
 358     // must move back the new_top, now that this overflowing obj is deferred.
 359     HeapWord* new_top = destination - pointer_delta(region_to_addr(src_region), overflowing_obj);
 360 
 361     // If the overflowing obj was relocated to its original destination,
 362     // those destination regions would have their source_region set. Now that
 363     // this overflowing obj is relocated somewhere else, reset the
 364     // source_region.
 365     {
 366       size_t range_start = addr_to_region_idx(region_align_up(new_top));
 367       size_t range_end = addr_to_region_idx(region_align_up(destination));
 368       for (size_t i = range_start; i < range_end; ++i) {
 369         region(i)->set_source_region(0);
 370       }
 371     }
 372 
 373     // Update new top of target space
 374     *target_next = new_top;
 375 
 376     return overflowing_obj;
 377   }
 378 
 379   // Obj-iteration to locate the overflowing obj
 380   HeapWord* region_start = region_to_addr(src_region);
 381   HeapWord* region_end = region_start + RegionSize;
 382   HeapWord* cur_addr = region_start + partial_obj_size;
 383   size_t live_words = partial_obj_size;
 384 
 385   while (true) {
 386     assert(cur_addr < region_end, "inv");
 387     cur_addr = PSParallelCompact::mark_bitmap()->find_obj_beg(cur_addr, region_end);
 388     // There must be an overflowing obj in this region
 389     assert(cur_addr < region_end, "inv");
 390 
 391     oop obj = cast_to_oop(cur_addr);
 392     size_t obj_size = obj->size();
 393     if (destination + live_words + obj_size > target_end) {
 394       // Found the overflowing obj
 395       split_info.record(src_region, cur_addr, live_words);
 396       *target_next = destination + live_words;
 397       return cur_addr;
 398     }
 399 
 400     live_words += obj_size;
 401     cur_addr += obj_size;
 402   }
 403 }
 404 
 405 size_t ParallelCompactData::live_words_in_space(const MutableSpace* space,
 406                                                 HeapWord** full_region_prefix_end) {
 407   size_t cur_region = addr_to_region_idx(space->bottom());
 408   const size_t end_region = addr_to_region_idx(region_align_up(space->top()));
 409   size_t live_words = 0;
 410   if (full_region_prefix_end == nullptr) {
 411     for (/* empty */; cur_region < end_region; ++cur_region) {
 412       live_words += _region_data[cur_region].data_size();
 413     }
 414   } else {
 415     bool first_set = false;
 416     for (/* empty */; cur_region < end_region; ++cur_region) {
 417       size_t live_words_in_region = _region_data[cur_region].data_size();
 418       if (!first_set && live_words_in_region < RegionSize) {
 419         *full_region_prefix_end = region_to_addr(cur_region);
 420         first_set = true;
 421       }
 422       live_words += live_words_in_region;
 423     }
 424     if (!first_set) {
 425       // All regions are full of live objs.
 426       assert(is_region_aligned(space->top()), "inv");
 427       *full_region_prefix_end = space->top();
 428     }
 429     assert(*full_region_prefix_end != nullptr, "postcondition");
 430     assert(is_region_aligned(*full_region_prefix_end), "inv");
 431     assert(*full_region_prefix_end >= space->bottom(), "in-range");
 432     assert(*full_region_prefix_end <= space->top(), "in-range");
 433   }
 434   return live_words;
 435 }
 436 
 437 bool ParallelCompactData::summarize(SplitInfo& split_info,
 438                                     HeapWord* source_beg, HeapWord* source_end,
 439                                     HeapWord** source_next,
 440                                     HeapWord* target_beg, HeapWord* target_end,
 441                                     HeapWord** target_next)
 442 {
 443   HeapWord* const source_next_val = source_next == nullptr ? nullptr : *source_next;
 444   log_develop_trace(gc, compaction)(
 445       "sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
 446       "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
 447       p2i(source_beg), p2i(source_end), p2i(source_next_val),
 448       p2i(target_beg), p2i(target_end), p2i(*target_next));
 449 
 450   size_t cur_region = addr_to_region_idx(source_beg);
 451   const size_t end_region = addr_to_region_idx(region_align_up(source_end));
 452 
 453   HeapWord *dest_addr = target_beg;
 454   for (/* empty */; cur_region < end_region; cur_region++) {
 455     size_t words = _region_data[cur_region].data_size();
 456 
 457     // Skip empty ones
 458     if (words == 0) {
 459       continue;
 460     }
 461 
 462     if (split_info.is_split(cur_region)) {
 463       assert(words > split_info.preceding_live_words(), "inv");
 464       words -= split_info.preceding_live_words();
 465     }
 466 
 467     _region_data[cur_region].set_destination(dest_addr);
 468 
 469     // If cur_region does not fit entirely into the target space, find a point
 470     // at which the source space can be 'split' so that part is copied to the
 471     // target space and the rest is copied elsewhere.
 472     if (dest_addr + words > target_end) {
 473       assert(source_next != nullptr, "source_next is null when splitting");
 474       *source_next = summarize_split_space(cur_region, split_info, dest_addr,
 475                                            target_end, target_next);
 476       return false;
 477     }
 478 
 479     uint destination_count = split_info.is_split(cur_region)
 480                              ? split_info.preceding_destination_count()
 481                              : 0;
 482 
 483     HeapWord* const last_addr = dest_addr + words - 1;
 484     const size_t dest_region_1 = addr_to_region_idx(dest_addr);
 485     const size_t dest_region_2 = addr_to_region_idx(last_addr);
 486 
 487     // Initially assume that the destination regions will be the same and
 488     // adjust the value below if necessary.  Under this assumption, if
 489     // cur_region == dest_region_2, then cur_region will be compacted
 490     // completely into itself.
 491     destination_count += cur_region == dest_region_2 ? 0 : 1;
 492     if (dest_region_1 != dest_region_2) {
 493       // Destination regions differ; adjust destination_count.
 494       destination_count += 1;
 495       // Data from cur_region will be copied to the start of dest_region_2.
 496       _region_data[dest_region_2].set_source_region(cur_region);
 497     } else if (is_region_aligned(dest_addr)) {
 498       // Data from cur_region will be copied to the start of the destination
 499       // region.
 500       _region_data[dest_region_1].set_source_region(cur_region);
 501     }
 502 
 503     _region_data[cur_region].set_destination_count(destination_count);
 504     dest_addr += words;
 505   }
 506 
 507   *target_next = dest_addr;
 508   return true;
 509 }
 510 
 511 #ifdef ASSERT
 512 void ParallelCompactData::verify_clear() {
 513   for (uint cur_idx = 0; cur_idx < region_count(); ++cur_idx) {
 514     if (!region(cur_idx)->is_clear()) {
 515       log_warning(gc)("Uncleared Region: %u", cur_idx);
 516       region(cur_idx)->verify_clear();
 517     }
 518   }
 519 }
 520 #endif  // #ifdef ASSERT
 521 
 522 STWGCTimer          PSParallelCompact::_gc_timer;
 523 ParallelOldTracer   PSParallelCompact::_gc_tracer;
 524 elapsedTimer        PSParallelCompact::_accumulated_time;
 525 unsigned int        PSParallelCompact::_maximum_compaction_gc_num = 0;
 526 CollectorCounters*  PSParallelCompact::_counters = nullptr;
 527 ParMarkBitMap       PSParallelCompact::_mark_bitmap;
 528 ParallelCompactData PSParallelCompact::_summary_data;
 529 
 530 PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
 531 
 532 class PCAdjustPointerClosure: public BasicOopIterateClosure {
 533   template <typename T>
 534   void do_oop_work(T* p) { PSParallelCompact::adjust_pointer(p); }
 535 
 536 public:
 537   virtual void do_oop(oop* p)                { do_oop_work(p); }
 538   virtual void do_oop(narrowOop* p)          { do_oop_work(p); }
 539 
 540   virtual ReferenceIterationMode reference_iteration_mode() { return DO_FIELDS; }
 541 };
 542 
 543 static PCAdjustPointerClosure pc_adjust_pointer_closure;
 544 
 545 bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
 546 
 547 void PSParallelCompact::post_initialize() {
 548   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 549   _span_based_discoverer.set_span(heap->reserved_region());
 550   _ref_processor =
 551     new ReferenceProcessor(&_span_based_discoverer,
 552                            ParallelGCThreads,   // mt processing degree
 553                            ParallelGCThreads,   // mt discovery degree
 554                            false,               // concurrent_discovery
 555                            &_is_alive_closure); // non-header is alive closure
 556 
 557   _counters = new CollectorCounters("Parallel full collection pauses", 1);
 558 
 559   // Initialize static fields in ParCompactionManager.
 560   ParCompactionManager::initialize(mark_bitmap());
 561 }
 562 
 563 bool PSParallelCompact::initialize_aux_data() {
 564   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 565   MemRegion mr = heap->reserved_region();
 566   assert(mr.byte_size() != 0, "heap should be reserved");
 567 
 568   initialize_space_info();
 569 
 570   if (!_mark_bitmap.initialize(mr)) {
 571     vm_shutdown_during_initialization(
 572       err_msg("Unable to allocate %zuKB bitmaps for parallel "
 573       "garbage collection for the requested %zuKB heap.",
 574       _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
 575     return false;
 576   }
 577 
 578   if (!_summary_data.initialize(mr)) {
 579     vm_shutdown_during_initialization(
 580       err_msg("Unable to allocate %zuKB card tables for parallel "
 581       "garbage collection for the requested %zuKB heap.",
 582       _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
 583     return false;
 584   }
 585 
 586   return true;
 587 }
 588 
 589 void PSParallelCompact::initialize_space_info()
 590 {
 591   memset(&_space_info, 0, sizeof(_space_info));
 592 
 593   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 594   PSYoungGen* young_gen = heap->young_gen();
 595 
 596   _space_info[old_space_id].set_space(heap->old_gen()->object_space());
 597   _space_info[eden_space_id].set_space(young_gen->eden_space());
 598   _space_info[from_space_id].set_space(young_gen->from_space());
 599   _space_info[to_space_id].set_space(young_gen->to_space());
 600 
 601   _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
 602 }
 603 
 604 void
 605 PSParallelCompact::clear_data_covering_space(SpaceId id)
 606 {
 607   // At this point, top is the value before GC, new_top() is the value that will
 608   // be set at the end of GC.  The marking bitmap is cleared to top; nothing
 609   // should be marked above top.  The summary data is cleared to the larger of
 610   // top & new_top.
 611   MutableSpace* const space = _space_info[id].space();
 612   HeapWord* const bot = space->bottom();
 613   HeapWord* const top = space->top();
 614   HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
 615 
 616   _mark_bitmap.clear_range(bot, top);
 617 
 618   const size_t beg_region = _summary_data.addr_to_region_idx(bot);
 619   const size_t end_region =
 620     _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
 621   _summary_data.clear_range(beg_region, end_region);
 622 
 623   // Clear the data used to 'split' regions.
 624   SplitInfo& split_info = _space_info[id].split_info();
 625   if (split_info.is_valid()) {
 626     split_info.clear();
 627   }
 628   DEBUG_ONLY(split_info.verify_clear();)
 629 }
 630 
 631 void PSParallelCompact::pre_compact()
 632 {
 633   // Update the from & to space pointers in space_info, since they are swapped
 634   // at each young gen gc.  Do the update unconditionally (even though a
 635   // promotion failure does not swap spaces) because an unknown number of young
 636   // collections will have swapped the spaces an unknown number of times.
 637   GCTraceTime(Debug, gc, phases) tm("Pre Compact", &_gc_timer);
 638   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 639   _space_info[from_space_id].set_space(heap->young_gen()->from_space());
 640   _space_info[to_space_id].set_space(heap->young_gen()->to_space());
 641 
 642   heap->increment_total_collections(true);
 643 
 644   CodeCache::on_gc_marking_cycle_start();
 645 
 646   heap->print_before_gc();
 647   heap->trace_heap_before_gc(&_gc_tracer);
 648 
 649   // Fill in TLABs
 650   heap->ensure_parsability(true);  // retire TLABs
 651 
 652   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 653     Universe::verify("Before GC");
 654   }
 655 
 656   DEBUG_ONLY(mark_bitmap()->verify_clear();)
 657   DEBUG_ONLY(summary_data().verify_clear();)
 658 }
 659 
 660 void PSParallelCompact::post_compact()
 661 {
 662   GCTraceTime(Info, gc, phases) tm("Post Compact", &_gc_timer);
 663   ParCompactionManager::remove_all_shadow_regions();
 664 
 665   CodeCache::on_gc_marking_cycle_finish();
 666   CodeCache::arm_all_nmethods();
 667 
 668   // Need to clear claim bits for the next full-gc (marking and adjust-pointers).
 669   ClassLoaderDataGraph::clear_claimed_marks();
 670 
 671   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
 672     // Clear the marking bitmap, summary data and split info.
 673     clear_data_covering_space(SpaceId(id));
 674     {
 675       MutableSpace* space = _space_info[id].space();
 676       HeapWord* top = space->top();
 677       HeapWord* new_top = _space_info[id].new_top();
 678       if (ZapUnusedHeapArea && new_top < top) {
 679         space->mangle_region(MemRegion(new_top, top));
 680       }
 681       // Update top().  Must be done after clearing the bitmap and summary data.
 682       space->set_top(new_top);
 683     }
 684   }
 685 
 686 #ifdef ASSERT
 687   {
 688     mark_bitmap()->verify_clear();
 689     summary_data().verify_clear();
 690   }
 691 #endif
 692 
 693   ParCompactionManager::flush_all_string_dedup_requests();
 694 
 695   MutableSpace* const eden_space = _space_info[eden_space_id].space();
 696   MutableSpace* const from_space = _space_info[from_space_id].space();
 697   MutableSpace* const to_space   = _space_info[to_space_id].space();
 698 
 699   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 700   bool eden_empty = eden_space->is_empty();
 701 
 702   // Update heap occupancy information which is used as input to the soft ref
 703   // clearing policy at the next gc.
 704   Universe::heap()->update_capacity_and_used_at_gc();
 705 
 706   bool young_gen_empty = eden_empty && from_space->is_empty() &&
 707     to_space->is_empty();
 708 
 709   PSCardTable* ct = heap->card_table();
 710   MemRegion old_mr = heap->old_gen()->committed();
 711   if (young_gen_empty) {
 712     ct->clear_MemRegion(old_mr);
 713   } else {
 714     ct->dirty_MemRegion(old_mr);
 715   }
 716 
 717   heap->prune_scavengable_nmethods();
 718 
 719 #if COMPILER2_OR_JVMCI
 720   DerivedPointerTable::update_pointers();
 721 #endif
 722 
 723   // Signal that we have completed a visit to all live objects.
 724   Universe::heap()->record_whole_heap_examined_timestamp();
 725 }
 726 
 727 HeapWord* PSParallelCompact::compute_dense_prefix_for_old_space(MutableSpace* old_space,
 728                                                                 HeapWord* full_region_prefix_end) {
 729   const size_t region_size = ParallelCompactData::RegionSize;
 730   const ParallelCompactData& sd = summary_data();
 731 
 732   // Iteration starts with the region *after* the full-region-prefix-end.
 733   const RegionData* const start_region = sd.addr_to_region_ptr(full_region_prefix_end);
 734   // If final region is not full, iteration stops before that region,
 735   // because fill_dense_prefix_end assumes that prefix_end <= top.
 736   const RegionData* const end_region = sd.addr_to_region_ptr(old_space->top());
 737   assert(start_region <= end_region, "inv");
 738 
 739   size_t max_waste = old_space->capacity_in_words() * (MarkSweepDeadRatio / 100.0);
 740   const RegionData* cur_region = start_region;
 741   for (/* empty */; cur_region < end_region; ++cur_region) {
 742     assert(region_size >= cur_region->data_size(), "inv");
 743     size_t dead_size = region_size - cur_region->data_size();
 744     if (max_waste < dead_size) {
 745       break;
 746     }
 747     max_waste -= dead_size;
 748   }
 749 
 750   HeapWord* const prefix_end = sd.region_to_addr(cur_region);
 751   assert(sd.is_region_aligned(prefix_end), "postcondition");
 752   assert(prefix_end >= full_region_prefix_end, "in-range");
 753   assert(prefix_end <= old_space->top(), "in-range");
 754   return prefix_end;
 755 }
 756 
 757 void PSParallelCompact::fill_dense_prefix_end(SpaceId id) {
 758   // Comparing two sizes to decide if filling is required:
 759   //
 760   // The size of the filler (min-obj-size) is 2 heap words with the default
 761   // MinObjAlignment, since both markword and klass take 1 heap word.
 762   // With +UseCompactObjectHeaders, the minimum filler size is only one word,
 763   // because the Klass* gets encoded in the mark-word.
 764   //
 765   // The size of the gap (if any) right before dense-prefix-end is
 766   // MinObjAlignment.
 767   //
 768   // Need to fill in the gap only if it's smaller than min-obj-size, and the
 769   // filler obj will extend to next region.
 770 
 771   if (MinObjAlignment >= checked_cast<int>(CollectedHeap::min_fill_size())) {
 772     return;
 773   }
 774 
 775   assert(!UseCompactObjectHeaders, "Compact headers can allocate small objects");
 776   assert(CollectedHeap::min_fill_size() == 2, "inv");
 777   HeapWord* const dense_prefix_end = dense_prefix(id);
 778   assert(_summary_data.is_region_aligned(dense_prefix_end), "precondition");
 779   assert(dense_prefix_end <= space(id)->top(), "precondition");
 780   if (dense_prefix_end == space(id)->top()) {
 781     // Must not have single-word gap right before prefix-end/top.
 782     return;
 783   }
 784   RegionData* const region_after_dense_prefix = _summary_data.addr_to_region_ptr(dense_prefix_end);
 785 
 786   if (region_after_dense_prefix->partial_obj_size() != 0 ||
 787       _mark_bitmap.is_marked(dense_prefix_end)) {
 788     // The region after the dense prefix starts with live bytes.
 789     return;
 790   }
 791 
 792   HeapWord* block_start = start_array(id)->block_start_reaching_into_card(dense_prefix_end);
 793   if (block_start == dense_prefix_end - 1) {
 794     assert(!_mark_bitmap.is_marked(block_start), "inv");
 795     // There is exactly one heap word gap right before the dense prefix end, so we need a filler object.
 796     // The filler object will extend into region_after_dense_prefix.
 797     const size_t obj_len = 2; // min-fill-size
 798     HeapWord* const obj_beg = dense_prefix_end - 1;
 799     CollectedHeap::fill_with_object(obj_beg, obj_len);
 800     _mark_bitmap.mark_obj(obj_beg);
 801     _summary_data.addr_to_region_ptr(obj_beg)->add_live_obj(1);
 802     region_after_dense_prefix->set_partial_obj_size(1);
 803     region_after_dense_prefix->set_partial_obj_addr(obj_beg);
 804     assert(start_array(id) != nullptr, "sanity");
 805     start_array(id)->update_for_block(obj_beg, obj_beg + obj_len);
 806   }
 807 }
 808 
 809 bool PSParallelCompact::check_maximum_compaction(bool should_do_max_compaction,
 810                                                  size_t total_live_words,
 811                                                  MutableSpace* const old_space,
 812                                                  HeapWord* full_region_prefix_end) {
 813 
 814   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 815 
 816   // Check System.GC
 817   bool is_max_on_system_gc = UseMaximumCompactionOnSystemGC
 818                           && GCCause::is_user_requested_gc(heap->gc_cause());
 819 
 820   // Check if all live objs are too much for old-gen.
 821   const bool is_old_gen_too_full = (total_live_words >= old_space->capacity_in_words());
 822 
 823   // If all regions in old-gen are full
 824   const bool is_region_full =
 825     full_region_prefix_end >= _summary_data.region_align_down(old_space->top());
 826 
 827   return should_do_max_compaction
 828       || is_max_on_system_gc
 829       || is_old_gen_too_full
 830       || is_region_full;
 831 }
 832 
 833 void PSParallelCompact::summary_phase(bool should_do_max_compaction)
 834 {
 835   GCTraceTime(Info, gc, phases) tm("Summary Phase", &_gc_timer);
 836 
 837   MutableSpace* const old_space = _space_info[old_space_id].space();
 838   {
 839     size_t total_live_words = 0;
 840     HeapWord* full_region_prefix_end = nullptr;
 841     {
 842       // old-gen
 843       size_t live_words = _summary_data.live_words_in_space(old_space,
 844                                                             &full_region_prefix_end);
 845       total_live_words += live_words;
 846     }
 847     // young-gen
 848     for (uint i = eden_space_id; i < last_space_id; ++i) {
 849       const MutableSpace* space = _space_info[i].space();
 850       size_t live_words = _summary_data.live_words_in_space(space);
 851       total_live_words += live_words;
 852       _space_info[i].set_new_top(space->bottom() + live_words);
 853       _space_info[i].set_dense_prefix(space->bottom());
 854     }
 855 
 856     should_do_max_compaction = check_maximum_compaction(should_do_max_compaction,
 857                                                         total_live_words,
 858                                                         old_space,
 859                                                         full_region_prefix_end);
 860     {
 861       GCTraceTime(Info, gc, phases) tm("Summary Phase: expand", &_gc_timer);
 862       // Try to expand old-gen in order to fit all live objs and waste.
 863       size_t target_capacity_bytes = total_live_words * HeapWordSize
 864                                    + old_space->capacity_in_bytes() * (MarkSweepDeadRatio / 100);
 865       ParallelScavengeHeap::heap()->old_gen()->try_expand_till_size(target_capacity_bytes);
 866     }
 867 
 868     HeapWord* dense_prefix_end = should_do_max_compaction
 869                                  ? full_region_prefix_end
 870                                  : compute_dense_prefix_for_old_space(old_space,
 871                                                                       full_region_prefix_end);
 872     SpaceId id = old_space_id;
 873     _space_info[id].set_dense_prefix(dense_prefix_end);
 874 
 875     if (dense_prefix_end != old_space->bottom()) {
 876       fill_dense_prefix_end(id);
 877     }
 878 
 879     // Compacting objs in [dense_prefix_end, old_space->top())
 880     _summary_data.summarize(_space_info[id].split_info(),
 881                             dense_prefix_end, old_space->top(), nullptr,
 882                             dense_prefix_end, old_space->end(),
 883                             _space_info[id].new_top_addr());
 884   }
 885 
 886   // Summarize the remaining spaces in the young gen.  The initial target space
 887   // is the old gen.  If a space does not fit entirely into the target, then the
 888   // remainder is compacted into the space itself and that space becomes the new
 889   // target.
 890   SpaceId dst_space_id = old_space_id;
 891   HeapWord* dst_space_end = old_space->end();
 892   HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
 893   for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
 894     const MutableSpace* space = _space_info[id].space();
 895     const size_t live = pointer_delta(_space_info[id].new_top(),
 896                                       space->bottom());
 897     const size_t available = pointer_delta(dst_space_end, *new_top_addr);
 898 
 899     if (live > 0 && live <= available) {
 900       // All the live data will fit.
 901       bool done = _summary_data.summarize(_space_info[id].split_info(),
 902                                           space->bottom(), space->top(),
 903                                           nullptr,
 904                                           *new_top_addr, dst_space_end,
 905                                           new_top_addr);
 906       assert(done, "space must fit into old gen");
 907 
 908       // Reset the new_top value for the space.
 909       _space_info[id].set_new_top(space->bottom());
 910     } else if (live > 0) {
 911       // Attempt to fit part of the source space into the target space.
 912       HeapWord* next_src_addr = nullptr;
 913       bool done = _summary_data.summarize(_space_info[id].split_info(),
 914                                           space->bottom(), space->top(),
 915                                           &next_src_addr,
 916                                           *new_top_addr, dst_space_end,
 917                                           new_top_addr);
 918       assert(!done, "space should not fit into old gen");
 919       assert(next_src_addr != nullptr, "sanity");
 920 
 921       // The source space becomes the new target, so the remainder is compacted
 922       // within the space itself.
 923       dst_space_id = SpaceId(id);
 924       dst_space_end = space->end();
 925       new_top_addr = _space_info[id].new_top_addr();
 926       done = _summary_data.summarize(_space_info[id].split_info(),
 927                                      next_src_addr, space->top(),
 928                                      nullptr,
 929                                      space->bottom(), dst_space_end,
 930                                      new_top_addr);
 931       assert(done, "space must fit when compacted into itself");
 932       assert(*new_top_addr <= space->top(), "usage should not grow");
 933     }
 934   }
 935 }
 936 
 937 bool PSParallelCompact::invoke(bool clear_all_soft_refs, bool should_do_max_compaction) {
 938   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 939   assert(Thread::current() == (Thread*)VMThread::vm_thread(),
 940          "should be in vm thread");
 941   assert(ref_processor() != nullptr, "Sanity");
 942 
 943   SvcGCMarker sgcm(SvcGCMarker::FULL);
 944   IsSTWGCActiveMark mark;
 945 
 946   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 947 
 948   GCIdMark gc_id_mark;
 949   _gc_timer.register_gc_start();
 950   _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
 951 
 952   GCCause::Cause gc_cause = heap->gc_cause();
 953   PSOldGen* old_gen = heap->old_gen();
 954   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
 955 
 956   // Make sure data structures are sane, make the heap parsable, and do other
 957   // miscellaneous bookkeeping.
 958   pre_compact();
 959 
 960   const PreGenGCValues pre_gc_values = heap->get_pre_gc_values();
 961 
 962   {
 963     const uint active_workers =
 964       WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().max_workers(),
 965                                         ParallelScavengeHeap::heap()->workers().active_workers(),
 966                                         Threads::number_of_non_daemon_threads());
 967     ParallelScavengeHeap::heap()->workers().set_active_workers(active_workers);
 968 
 969     GCTraceCPUTime tcpu(&_gc_tracer);
 970     GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause, true);
 971 
 972     heap->pre_full_gc_dump(&_gc_timer);
 973 
 974     TraceCollectorStats tcs(counters());
 975     TraceMemoryManagerStats tms(heap->old_gc_manager(), gc_cause, "end of major GC");
 976 
 977     if (log_is_enabled(Debug, gc, heap, exit)) {
 978       accumulated_time()->start();
 979     }
 980 
 981     // Let the size policy know we're starting
 982     size_policy->major_collection_begin();
 983 
 984 #if COMPILER2_OR_JVMCI
 985     DerivedPointerTable::clear();
 986 #endif
 987 
 988     ref_processor()->start_discovery(clear_all_soft_refs);
 989 
 990     marking_phase(&_gc_tracer);
 991 
 992     summary_phase(should_do_max_compaction);
 993 
 994 #if COMPILER2_OR_JVMCI
 995     assert(DerivedPointerTable::is_active(), "Sanity");
 996     DerivedPointerTable::set_active(false);
 997 #endif
 998 
 999     forward_to_new_addr();
1000 
1001     adjust_pointers();
1002 
1003     compact();
1004 
1005     ParCompactionManager::_preserved_marks_set->restore(&ParallelScavengeHeap::heap()->workers());
1006 
1007     ParCompactionManager::verify_all_region_stack_empty();
1008 
1009     // Reset the mark bitmap, summary data, and do other bookkeeping.  Must be
1010     // done before resizing.
1011     post_compact();
1012 
1013     size_policy->major_collection_end();
1014 
1015     size_policy->sample_old_gen_used_bytes(MAX2(pre_gc_values.old_gen_used(), old_gen->used_in_bytes()));
1016 
1017     if (UseAdaptiveSizePolicy) {
1018       heap->resize_after_full_gc();
1019     }
1020 
1021     heap->resize_all_tlabs();
1022 
1023     // Resize the metaspace capacity after a collection
1024     MetaspaceGC::compute_new_size();
1025 
1026     if (log_is_enabled(Debug, gc, heap, exit)) {
1027       accumulated_time()->stop();
1028     }
1029 
1030     heap->print_heap_change(pre_gc_values);
1031 
1032     // Track memory usage and detect low memory
1033     MemoryService::track_memory_usage();
1034     heap->update_counters();
1035 
1036     heap->post_full_gc_dump(&_gc_timer);
1037 
1038     size_policy->record_gc_pause_end_instant();
1039   }
1040 
1041   heap->gc_epilogue(true);
1042 
1043   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
1044     Universe::verify("After GC");
1045   }
1046 
1047   heap->print_after_gc();
1048   heap->trace_heap_after_gc(&_gc_tracer);
1049 
1050   _gc_timer.register_gc_end();
1051 
1052   _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
1053   _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
1054 
1055   return true;
1056 }
1057 
1058 class PCAddThreadRootsMarkingTaskClosure : public ThreadClosure {
1059   ParCompactionManager* _cm;
1060 
1061 public:
1062   PCAddThreadRootsMarkingTaskClosure(ParCompactionManager* cm) : _cm(cm) { }
1063   void do_thread(Thread* thread) {
1064     ResourceMark rm;
1065 
1066     MarkingNMethodClosure mark_and_push_in_blobs(&_cm->_mark_and_push_closure);
1067 
1068     thread->oops_do(&_cm->_mark_and_push_closure, &mark_and_push_in_blobs);
1069 
1070     // Do the real work
1071     _cm->follow_marking_stacks();
1072   }
1073 };
1074 
1075 void steal_marking_work(TaskTerminator& terminator, uint worker_id) {
1076   assert(ParallelScavengeHeap::heap()->is_stw_gc_active(), "called outside gc");
1077 
1078   ParCompactionManager* cm =
1079     ParCompactionManager::gc_thread_compaction_manager(worker_id);
1080 
1081   do {
1082     ScannerTask task;
1083     if (ParCompactionManager::steal(worker_id, task)) {
1084       cm->follow_contents(task, true);
1085     }
1086     cm->follow_marking_stacks();
1087   } while (!terminator.offer_termination());
1088 }
1089 
1090 class MarkFromRootsTask : public WorkerTask {
1091   NMethodMarkingScope _nmethod_marking_scope;
1092   ThreadsClaimTokenScope _threads_claim_token_scope;
1093   OopStorageSetStrongParState<false /* concurrent */, false /* is_const */> _oop_storage_set_par_state;
1094   TaskTerminator _terminator;
1095   uint _active_workers;
1096 
1097 public:
1098   MarkFromRootsTask(uint active_workers) :
1099       WorkerTask("MarkFromRootsTask"),
1100       _nmethod_marking_scope(),
1101       _threads_claim_token_scope(),
1102       _terminator(active_workers, ParCompactionManager::marking_stacks()),
1103       _active_workers(active_workers) {}
1104 
1105   virtual void work(uint worker_id) {
1106     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1107     cm->create_marking_stats_cache();
1108     {
1109       CLDToOopClosure cld_closure(&cm->_mark_and_push_closure, ClassLoaderData::_claim_stw_fullgc_mark);
1110       ClassLoaderDataGraph::always_strong_cld_do(&cld_closure);
1111 
1112       // Do the real work
1113       cm->follow_marking_stacks();
1114     }
1115 
1116     {
1117       PCAddThreadRootsMarkingTaskClosure closure(cm);
1118       Threads::possibly_parallel_threads_do(_active_workers > 1 /* is_par */, &closure);
1119     }
1120 
1121     // Mark from OopStorages
1122     {
1123       _oop_storage_set_par_state.oops_do(&cm->_mark_and_push_closure);
1124       // Do the real work
1125       cm->follow_marking_stacks();
1126     }
1127 
1128     if (_active_workers > 1) {
1129       steal_marking_work(_terminator, worker_id);
1130     }
1131   }
1132 };
1133 
1134 class ParallelCompactRefProcProxyTask : public RefProcProxyTask {
1135   TaskTerminator _terminator;
1136 
1137 public:
1138   ParallelCompactRefProcProxyTask(uint max_workers)
1139     : RefProcProxyTask("ParallelCompactRefProcProxyTask", max_workers),
1140       _terminator(_max_workers, ParCompactionManager::marking_stacks()) {}
1141 
1142   void work(uint worker_id) override {
1143     assert(worker_id < _max_workers, "sanity");
1144     ParCompactionManager* cm = (_tm == RefProcThreadModel::Single) ? ParCompactionManager::get_vmthread_cm() : ParCompactionManager::gc_thread_compaction_manager(worker_id);
1145     BarrierEnqueueDiscoveredFieldClosure enqueue;
1146     ParCompactionManager::FollowStackClosure complete_gc(cm, (_tm == RefProcThreadModel::Single) ? nullptr : &_terminator, worker_id);
1147     _rp_task->rp_work(worker_id, PSParallelCompact::is_alive_closure(), &cm->_mark_and_push_closure, &enqueue, &complete_gc);
1148   }
1149 
1150   void prepare_run_task_hook() override {
1151     _terminator.reset_for_reuse(_queue_count);
1152   }
1153 };
1154 
1155 static void flush_marking_stats_cache(const uint num_workers) {
1156   for (uint i = 0; i < num_workers; ++i) {
1157     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(i);
1158     cm->flush_and_destroy_marking_stats_cache();
1159   }
1160 }
1161 
1162 class PSParallelCleaningTask : public WorkerTask {
1163   bool                    _unloading_occurred;
1164   CodeCacheUnloadingTask  _code_cache_task;
1165   // Prune dead klasses from subklass/sibling/implementor lists.
1166   KlassCleaningTask       _klass_cleaning_task;
1167 
1168 public:
1169   PSParallelCleaningTask(bool unloading_occurred) :
1170     WorkerTask("PS Parallel Cleaning"),
1171     _unloading_occurred(unloading_occurred),
1172     _code_cache_task(unloading_occurred),
1173     _klass_cleaning_task() {}
1174 
1175   void work(uint worker_id) {
1176 #if INCLUDE_JVMCI
1177     if (EnableJVMCI && worker_id == 0) {
1178       // Serial work; only first worker.
1179       // Clean JVMCI metadata handles.
1180       JVMCI::do_unloading(_unloading_occurred);
1181     }
1182 #endif
1183 
1184     // Do first pass of code cache cleaning.
1185     _code_cache_task.work(worker_id);
1186 
1187     // Clean all klasses that were not unloaded.
1188     // The weak metadata in klass doesn't need to be
1189     // processed if there was no unloading.
1190     if (_unloading_occurred) {
1191       _klass_cleaning_task.work();
1192     }
1193   }
1194 };
1195 
1196 void PSParallelCompact::marking_phase(ParallelOldTracer *gc_tracer) {
1197   // Recursively traverse all live objects and mark them
1198   GCTraceTime(Info, gc, phases) tm("Marking Phase", &_gc_timer);
1199 
1200   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
1201 
1202   ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_mark);
1203   {
1204     GCTraceTime(Debug, gc, phases) tm("Par Mark", &_gc_timer);
1205 
1206     MarkFromRootsTask task(active_gc_threads);
1207     ParallelScavengeHeap::heap()->workers().run_task(&task);
1208   }
1209 
1210   // Process reference objects found during marking
1211   {
1212     GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
1213 
1214     ReferenceProcessorStats stats;
1215     ReferenceProcessorPhaseTimes pt(&_gc_timer, ref_processor()->max_num_queues());
1216 
1217     ParallelCompactRefProcProxyTask task(ref_processor()->max_num_queues());
1218     stats = ref_processor()->process_discovered_references(task, &ParallelScavengeHeap::heap()->workers(), pt);
1219 
1220     gc_tracer->report_gc_reference_stats(stats);
1221     pt.print_all_references();
1222   }
1223 
1224   {
1225     GCTraceTime(Debug, gc, phases) tm("Flush Marking Stats", &_gc_timer);
1226 
1227     flush_marking_stats_cache(active_gc_threads);
1228   }
1229 
1230   // This is the point where the entire marking should have completed.
1231   ParCompactionManager::verify_all_marking_stack_empty();
1232 
1233   {
1234     GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
1235     WeakProcessor::weak_oops_do(&ParallelScavengeHeap::heap()->workers(),
1236                                 is_alive_closure(),
1237                                 &do_nothing_cl,
1238                                 1);
1239   }
1240 
1241   {
1242     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
1243 
1244     ClassUnloadingContext ctx(active_gc_threads /* num_nmethod_unlink_workers */,
1245                               false /* unregister_nmethods_during_purge */,
1246                               false /* lock_nmethod_free_separately */);
1247 
1248     {
1249       CodeCache::UnlinkingScope scope(is_alive_closure());
1250 
1251       // Follow system dictionary roots and unload classes.
1252       bool unloading_occurred = SystemDictionary::do_unloading(&_gc_timer);
1253 
1254       PSParallelCleaningTask task{unloading_occurred};
1255       ParallelScavengeHeap::heap()->workers().run_task(&task);
1256     }
1257 
1258     {
1259       GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", gc_timer());
1260       // Release unloaded nmethod's memory.
1261       ctx.purge_nmethods();
1262     }
1263     {
1264       GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", &_gc_timer);
1265       ParallelScavengeHeap::heap()->prune_unlinked_nmethods();
1266     }
1267     {
1268       GCTraceTime(Debug, gc, phases) t("Free Code Blobs", gc_timer());
1269       ctx.free_nmethods();
1270     }
1271     {
1272       // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1273       GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", gc_timer());
1274       ClassLoaderDataGraph::purge(true /* at_safepoint */);
1275       DEBUG_ONLY(MetaspaceUtils::verify();)
1276     }
1277   }
1278 
1279   {
1280     GCTraceTime(Debug, gc, phases) tm("Report Object Count", &_gc_timer);
1281     _gc_tracer.report_object_count_after_gc(is_alive_closure(), &ParallelScavengeHeap::heap()->workers());
1282   }
1283 #if TASKQUEUE_STATS
1284   ParCompactionManager::print_and_reset_taskqueue_stats();
1285 #endif
1286 }
1287 
1288 template<typename Func>
1289 void PSParallelCompact::adjust_in_space_helper(SpaceId id, volatile uint* claim_counter, Func&& on_stripe) {
1290   MutableSpace* sp = PSParallelCompact::space(id);
1291   HeapWord* const bottom = sp->bottom();
1292   HeapWord* const top = sp->top();
1293   if (bottom == top) {
1294     return;
1295   }
1296 
1297   const uint num_regions_per_stripe = 2;
1298   const size_t region_size = ParallelCompactData::RegionSize;
1299   const size_t stripe_size = num_regions_per_stripe * region_size;
1300 
1301   while (true) {
1302     uint counter = AtomicAccess::fetch_then_add(claim_counter, num_regions_per_stripe);
1303     HeapWord* cur_stripe = bottom + counter * region_size;
1304     if (cur_stripe >= top) {
1305       break;
1306     }
1307     HeapWord* stripe_end = MIN2(cur_stripe + stripe_size, top);
1308     on_stripe(cur_stripe, stripe_end);
1309   }
1310 }
1311 
1312 void PSParallelCompact::adjust_in_old_space(volatile uint* claim_counter) {
1313   // Regions in old-space shouldn't be split.
1314   assert(!_space_info[old_space_id].split_info().is_valid(), "inv");
1315 
1316   auto scan_obj_with_limit = [&] (HeapWord* obj_start, HeapWord* left, HeapWord* right) {
1317     assert(mark_bitmap()->is_marked(obj_start), "inv");
1318     oop obj = cast_to_oop(obj_start);
1319     return obj->oop_iterate_size(&pc_adjust_pointer_closure, MemRegion(left, right));
1320   };
1321 
1322   adjust_in_space_helper(old_space_id, claim_counter, [&] (HeapWord* stripe_start, HeapWord* stripe_end) {
1323     assert(_summary_data.is_region_aligned(stripe_start), "inv");
1324     RegionData* cur_region = _summary_data.addr_to_region_ptr(stripe_start);
1325     HeapWord* obj_start;
1326     if (cur_region->partial_obj_size() != 0) {
1327       obj_start = cur_region->partial_obj_addr();
1328       obj_start += scan_obj_with_limit(obj_start, stripe_start, stripe_end);
1329     } else {
1330       obj_start = stripe_start;
1331     }
1332 
1333     while (obj_start < stripe_end) {
1334       obj_start = mark_bitmap()->find_obj_beg(obj_start, stripe_end);
1335       if (obj_start >= stripe_end) {
1336         break;
1337       }
1338       obj_start += scan_obj_with_limit(obj_start, stripe_start, stripe_end);
1339     }
1340   });
1341 }
1342 
1343 void PSParallelCompact::adjust_in_young_space(SpaceId id, volatile uint* claim_counter) {
1344   adjust_in_space_helper(id, claim_counter, [](HeapWord* stripe_start, HeapWord* stripe_end) {
1345     HeapWord* obj_start = stripe_start;
1346     while (obj_start < stripe_end) {
1347       obj_start = mark_bitmap()->find_obj_beg(obj_start, stripe_end);
1348       if (obj_start >= stripe_end) {
1349         break;
1350       }
1351       oop obj = cast_to_oop(obj_start);
1352       obj_start += obj->oop_iterate_size(&pc_adjust_pointer_closure);
1353     }
1354   });
1355 }
1356 
1357 void PSParallelCompact::adjust_pointers_in_spaces(uint worker_id, volatile uint* claim_counters) {
1358   auto start_time = Ticks::now();
1359   adjust_in_old_space(&claim_counters[0]);
1360   for (uint id = eden_space_id; id < last_space_id; ++id) {
1361     adjust_in_young_space(SpaceId(id), &claim_counters[id]);
1362   }
1363   log_trace(gc, phases)("adjust_pointers_in_spaces worker %u: %.3f ms", worker_id, (Ticks::now() - start_time).seconds() * 1000);
1364 }
1365 
1366 class PSAdjustTask final : public WorkerTask {
1367   ThreadsClaimTokenScope                     _threads_claim_token_scope;
1368   WeakProcessor::Task                        _weak_proc_task;
1369   OopStorageSetStrongParState<false, false>  _oop_storage_iter;
1370   uint                                       _nworkers;
1371   volatile bool                              _code_cache_claimed;
1372   volatile uint _claim_counters[PSParallelCompact::last_space_id] = {};
1373 
1374   bool try_claim_code_cache_task() {
1375     return AtomicAccess::load(&_code_cache_claimed) == false
1376         && AtomicAccess::cmpxchg(&_code_cache_claimed, false, true) == false;
1377   }
1378 
1379 public:
1380   PSAdjustTask(uint nworkers) :
1381     WorkerTask("PSAdjust task"),
1382     _threads_claim_token_scope(),
1383     _weak_proc_task(nworkers),
1384     _oop_storage_iter(),
1385     _nworkers(nworkers),
1386     _code_cache_claimed(false) {
1387 
1388     ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_adjust);
1389   }
1390 
1391   void work(uint worker_id) {
1392     {
1393       // Pointers in heap.
1394       ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1395       cm->preserved_marks()->adjust_during_full_gc();
1396 
1397       PSParallelCompact::adjust_pointers_in_spaces(worker_id, _claim_counters);
1398     }
1399 
1400     {
1401       // All (strong and weak) CLDs.
1402       CLDToOopClosure cld_closure(&pc_adjust_pointer_closure, ClassLoaderData::_claim_stw_fullgc_adjust);
1403       ClassLoaderDataGraph::cld_do(&cld_closure);
1404     }
1405 
1406     {
1407       // Threads stack frames. No need to visit on-stack nmethods, because all
1408       // nmethods are visited in one go via CodeCache::nmethods_do.
1409       ResourceMark rm;
1410       Threads::possibly_parallel_oops_do(_nworkers > 1, &pc_adjust_pointer_closure, nullptr);
1411       if (try_claim_code_cache_task()) {
1412         NMethodToOopClosure adjust_code(&pc_adjust_pointer_closure, NMethodToOopClosure::FixRelocations);
1413         CodeCache::nmethods_do(&adjust_code);
1414       }
1415     }
1416 
1417     {
1418       // VM internal strong and weak roots.
1419       _oop_storage_iter.oops_do(&pc_adjust_pointer_closure);
1420       AlwaysTrueClosure always_alive;
1421       _weak_proc_task.work(worker_id, &always_alive, &pc_adjust_pointer_closure);
1422     }
1423   }
1424 };
1425 
1426 void PSParallelCompact::adjust_pointers() {
1427   // Adjust the pointers to reflect the new locations
1428   GCTraceTime(Info, gc, phases) tm("Adjust Pointers", &_gc_timer);
1429   uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
1430   PSAdjustTask task(nworkers);
1431   ParallelScavengeHeap::heap()->workers().run_task(&task);
1432 }
1433 
1434 // Split [start, end) evenly for a number of workers and return the
1435 // range for worker_id.
1436 static void split_regions_for_worker(size_t start, size_t end,
1437                                      uint worker_id, uint num_workers,
1438                                      size_t* worker_start, size_t* worker_end) {
1439   assert(start < end, "precondition");
1440   assert(num_workers > 0, "precondition");
1441   assert(worker_id < num_workers, "precondition");
1442 
1443   size_t num_regions = end - start;
1444   size_t num_regions_per_worker = num_regions / num_workers;
1445   size_t remainder = num_regions % num_workers;
1446   // The first few workers will get one extra.
1447   *worker_start = start + worker_id * num_regions_per_worker
1448                   + MIN2(checked_cast<size_t>(worker_id), remainder);
1449   *worker_end = *worker_start + num_regions_per_worker
1450                 + (worker_id < remainder ? 1 : 0);
1451 }
1452 
1453 static bool safe_to_read_header(size_t words) {
1454   precond(words > 0);
1455 
1456   // Safe to read if we have enough words for the full header, i.e., both
1457   // markWord and Klass pointer.
1458   const bool safe = words >= (size_t)oopDesc::header_size();
1459 
1460   // If using Compact Object Headers, the full header is inside the markWord,
1461   // so will always be safe to read
1462   assert(!UseCompactObjectHeaders || safe, "Compact Object Headers should always be safe");
1463 
1464   return safe;
1465 }
1466 
1467 void PSParallelCompact::forward_to_new_addr() {
1468   GCTraceTime(Info, gc, phases) tm("Forward", &_gc_timer);
1469   uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
1470 
1471   struct ForwardTask final : public WorkerTask {
1472     uint _num_workers;
1473 
1474     explicit ForwardTask(uint num_workers) :
1475       WorkerTask("PSForward task"),
1476       _num_workers(num_workers) {}
1477 
1478     static bool should_preserve_mark(oop obj, HeapWord* end_addr) {
1479       size_t remaining_words = pointer_delta(end_addr, cast_from_oop<HeapWord*>(obj));
1480 
1481       if (Arguments::is_valhalla_enabled() && !safe_to_read_header(remaining_words)) {
1482         // When using Valhalla, it might be necessary to preserve the Valhalla-
1483         // specific bits in the markWord. If the entire object header is
1484         // copied, the correct markWord (with the appropriate Valhalla bits)
1485         // can be safely read from the Klass. However, if the full header is
1486         // not copied, we cannot safely read the Klass to obtain this information.
1487         // In such cases, we always preserve the markWord to ensure that all
1488         // relevant bits, including Valhalla-specific ones, are retained.
1489         return true;
1490       } else {
1491         return obj->mark().must_be_preserved();
1492       }
1493     }
1494 
1495     static void forward_objs_in_range(ParCompactionManager* cm,
1496                                       HeapWord* start,
1497                                       HeapWord* end,
1498                                       HeapWord* destination) {
1499       HeapWord* cur_addr = start;
1500       HeapWord* new_addr = destination;
1501 
1502       while (cur_addr < end) {
1503         cur_addr = mark_bitmap()->find_obj_beg(cur_addr, end);
1504         if (cur_addr >= end) {
1505           return;
1506         }
1507         assert(mark_bitmap()->is_marked(cur_addr), "inv");
1508         oop obj = cast_to_oop(cur_addr);
1509 
1510         if (new_addr != cur_addr) {
1511           if (should_preserve_mark(obj, end)) {
1512             cm->preserved_marks()->push_always(obj, obj->mark());
1513           }
1514 
1515           FullGCForwarding::forward_to(obj, cast_to_oop(new_addr));
1516         }
1517         size_t obj_size = obj->size();
1518         new_addr += obj_size;
1519         cur_addr += obj_size;
1520       }
1521     }
1522 
1523     void work(uint worker_id) override {
1524       ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1525       for (uint id = old_space_id; id < last_space_id; ++id) {
1526         MutableSpace* sp = PSParallelCompact::space(SpaceId(id));
1527         HeapWord* dense_prefix_addr = dense_prefix(SpaceId(id));
1528         HeapWord* top = sp->top();
1529 
1530         if (dense_prefix_addr == top) {
1531           // Empty space
1532           continue;
1533         }
1534 
1535         const SplitInfo& split_info = _space_info[SpaceId(id)].split_info();
1536         size_t dense_prefix_region = _summary_data.addr_to_region_idx(dense_prefix_addr);
1537         size_t top_region = _summary_data.addr_to_region_idx(_summary_data.region_align_up(top));
1538         size_t start_region;
1539         size_t end_region;
1540         split_regions_for_worker(dense_prefix_region, top_region,
1541                                  worker_id, _num_workers,
1542                                  &start_region, &end_region);
1543         for (size_t cur_region = start_region; cur_region < end_region; ++cur_region) {
1544           RegionData* region_ptr = _summary_data.region(cur_region);
1545           size_t partial_obj_size = region_ptr->partial_obj_size();
1546 
1547           if (partial_obj_size == ParallelCompactData::RegionSize) {
1548             // No obj-start
1549             continue;
1550           }
1551 
1552           HeapWord* region_start = _summary_data.region_to_addr(cur_region);
1553           HeapWord* region_end = region_start + ParallelCompactData::RegionSize;
1554 
1555           if (split_info.is_split(cur_region)) {
1556             // Part 1: will be relocated to space-1
1557             HeapWord* preceding_destination = split_info.preceding_destination();
1558             HeapWord* split_point = split_info.split_point();
1559             forward_objs_in_range(cm, region_start + partial_obj_size, split_point, preceding_destination + partial_obj_size);
1560 
1561             // Part 2: will be relocated to space-2
1562             HeapWord* destination = region_ptr->destination();
1563             forward_objs_in_range(cm, split_point, region_end, destination);
1564           } else {
1565             HeapWord* destination = region_ptr->destination();
1566             forward_objs_in_range(cm, region_start + partial_obj_size, region_end, destination + partial_obj_size);
1567           }
1568         }
1569       }
1570     }
1571   } task(nworkers);
1572 
1573   ParallelScavengeHeap::heap()->workers().run_task(&task);
1574   DEBUG_ONLY(verify_forward();)
1575 }
1576 
1577 #ifdef ASSERT
1578 void PSParallelCompact::verify_forward() {
1579   HeapWord* const old_dense_prefix_addr = dense_prefix(SpaceId(old_space_id));
1580   // The destination addr for the first live obj after dense-prefix.
1581   HeapWord* bump_ptr = old_dense_prefix_addr
1582                      + _summary_data.addr_to_region_ptr(old_dense_prefix_addr)->partial_obj_size();
1583   SpaceId bump_ptr_space = old_space_id;
1584 
1585   for (uint id = old_space_id; id < last_space_id; ++id) {
1586     MutableSpace* sp = PSParallelCompact::space(SpaceId(id));
1587     // Only verify objs after dense-prefix, because those before dense-prefix are not moved (forwarded).
1588     HeapWord* cur_addr = dense_prefix(SpaceId(id));
1589     HeapWord* top = sp->top();
1590 
1591     while (cur_addr < top) {
1592       cur_addr = mark_bitmap()->find_obj_beg(cur_addr, top);
1593       if (cur_addr >= top) {
1594         break;
1595       }
1596       assert(mark_bitmap()->is_marked(cur_addr), "inv");
1597       assert(bump_ptr <= _space_info[bump_ptr_space].new_top(), "inv");
1598       // Move to the space containing cur_addr
1599       if (bump_ptr == _space_info[bump_ptr_space].new_top()) {
1600         bump_ptr = space(space_id(cur_addr))->bottom();
1601         bump_ptr_space = space_id(bump_ptr);
1602       }
1603       oop obj = cast_to_oop(cur_addr);
1604       if (cur_addr == bump_ptr) {
1605         assert(!FullGCForwarding::is_forwarded(obj), "inv");
1606       } else {
1607         assert(FullGCForwarding::forwardee(obj) == cast_to_oop(bump_ptr), "inv");
1608       }
1609       bump_ptr += obj->size();
1610       cur_addr += obj->size();
1611     }
1612   }
1613 }
1614 #endif
1615 
1616 // Helper class to print 8 region numbers per line and then print the total at the end.
1617 class FillableRegionLogger : public StackObj {
1618 private:
1619   Log(gc, compaction) log;
1620   static const int LineLength = 8;
1621   size_t _regions[LineLength];
1622   int _next_index;
1623   bool _enabled;
1624   size_t _total_regions;
1625 public:
1626   FillableRegionLogger() : _next_index(0), _enabled(log_develop_is_enabled(Trace, gc, compaction)), _total_regions(0) { }
1627   ~FillableRegionLogger() {
1628     log.trace("%zu initially fillable regions", _total_regions);
1629   }
1630 
1631   void print_line() {
1632     if (!_enabled || _next_index == 0) {
1633       return;
1634     }
1635     FormatBuffer<> line("Fillable: ");
1636     for (int i = 0; i < _next_index; i++) {
1637       line.append(" %7zu", _regions[i]);
1638     }
1639     log.trace("%s", line.buffer());
1640     _next_index = 0;
1641   }
1642 
1643   void handle(size_t region) {
1644     if (!_enabled) {
1645       return;
1646     }
1647     _regions[_next_index++] = region;
1648     if (_next_index == LineLength) {
1649       print_line();
1650     }
1651     _total_regions++;
1652   }
1653 };
1654 
1655 void PSParallelCompact::prepare_region_draining_tasks(uint parallel_gc_threads)
1656 {
1657   GCTraceTime(Trace, gc, phases) tm("Drain Task Setup", &_gc_timer);
1658 
1659   // Find the threads that are active
1660   uint worker_id = 0;
1661 
1662   // Find all regions that are available (can be filled immediately) and
1663   // distribute them to the thread stacks.  The iteration is done in reverse
1664   // order (high to low) so the regions will be removed in ascending order.
1665 
1666   const ParallelCompactData& sd = PSParallelCompact::summary_data();
1667 
1668   // id + 1 is used to test termination so unsigned  can
1669   // be used with an old_space_id == 0.
1670   FillableRegionLogger region_logger;
1671   for (unsigned int id = last_space_id - 1; id + 1 > old_space_id; --id) {
1672     SpaceInfo* const space_info = _space_info + id;
1673     HeapWord* const new_top = space_info->new_top();
1674 
1675     const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
1676     const size_t end_region =
1677       sd.addr_to_region_idx(sd.region_align_up(new_top));
1678 
1679     for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
1680       if (sd.region(cur)->claim_unsafe()) {
1681         ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1682         bool result = sd.region(cur)->mark_normal();
1683         assert(result, "Must succeed at this point.");
1684         cm->region_stack()->push(cur);
1685         region_logger.handle(cur);
1686         // Assign regions to tasks in round-robin fashion.
1687         if (++worker_id == parallel_gc_threads) {
1688           worker_id = 0;
1689         }
1690       }
1691     }
1692     region_logger.print_line();
1693   }
1694 }
1695 
1696 static void compaction_with_stealing_work(TaskTerminator* terminator, uint worker_id) {
1697   assert(ParallelScavengeHeap::heap()->is_stw_gc_active(), "called outside gc");
1698 
1699   ParCompactionManager* cm =
1700     ParCompactionManager::gc_thread_compaction_manager(worker_id);
1701 
1702   // Drain the stacks that have been preloaded with regions
1703   // that are ready to fill.
1704 
1705   cm->drain_region_stacks();
1706 
1707   guarantee(cm->region_stack()->is_empty(), "Not empty");
1708 
1709   size_t region_index = 0;
1710 
1711   while (true) {
1712     if (ParCompactionManager::steal(worker_id, region_index)) {
1713       PSParallelCompact::fill_and_update_region(cm, region_index);
1714       cm->drain_region_stacks();
1715     } else if (PSParallelCompact::steal_unavailable_region(cm, region_index)) {
1716       // Fill and update an unavailable region with the help of a shadow region
1717       PSParallelCompact::fill_and_update_shadow_region(cm, region_index);
1718       cm->drain_region_stacks();
1719     } else {
1720       if (terminator->offer_termination()) {
1721         break;
1722       }
1723       // Go around again.
1724     }
1725   }
1726 }
1727 
1728 class FillDensePrefixAndCompactionTask: public WorkerTask {
1729   TaskTerminator _terminator;
1730 
1731 public:
1732   FillDensePrefixAndCompactionTask(uint active_workers) :
1733       WorkerTask("FillDensePrefixAndCompactionTask"),
1734       _terminator(active_workers, ParCompactionManager::region_task_queues()) {
1735   }
1736 
1737   virtual void work(uint worker_id) {
1738     if (worker_id == 0) {
1739       auto start = Ticks::now();
1740       PSParallelCompact::fill_dead_objs_in_dense_prefix();
1741       log_trace(gc, phases)("Fill dense prefix by worker 0: %.3f ms", (Ticks::now() - start).seconds() * 1000);
1742     }
1743     compaction_with_stealing_work(&_terminator, worker_id);
1744   }
1745 };
1746 
1747 void PSParallelCompact::fill_range_in_dense_prefix(HeapWord* start, HeapWord* end) {
1748 #ifdef ASSERT
1749   {
1750     assert(start < end, "precondition");
1751     assert(mark_bitmap()->find_obj_beg(start, end) == end, "precondition");
1752     HeapWord* bottom = _space_info[old_space_id].space()->bottom();
1753     if (start != bottom) {
1754       // The preceding live obj.
1755       HeapWord* obj_start = mark_bitmap()->find_obj_beg_reverse(bottom, start);
1756       HeapWord* obj_end = obj_start + cast_to_oop(obj_start)->size();
1757       assert(obj_end == start, "precondition");
1758     }
1759   }
1760 #endif
1761 
1762   CollectedHeap::fill_with_objects(start, pointer_delta(end, start));
1763   HeapWord* addr = start;
1764   do {
1765     size_t size = cast_to_oop(addr)->size();
1766     start_array(old_space_id)->update_for_block(addr, addr + size);
1767     addr += size;
1768   } while (addr < end);
1769 }
1770 
1771 void PSParallelCompact::fill_dead_objs_in_dense_prefix() {
1772   ParMarkBitMap* bitmap = mark_bitmap();
1773 
1774   HeapWord* const bottom = _space_info[old_space_id].space()->bottom();
1775   HeapWord* const prefix_end = dense_prefix(old_space_id);
1776 
1777   const size_t region_size = ParallelCompactData::RegionSize;
1778 
1779   // Fill dead space in [start_addr, end_addr)
1780   HeapWord* const start_addr = bottom;
1781   HeapWord* const end_addr   = prefix_end;
1782 
1783   for (HeapWord* cur_addr = start_addr; cur_addr < end_addr; /* empty */) {
1784     RegionData* cur_region_ptr = _summary_data.addr_to_region_ptr(cur_addr);
1785     if (cur_region_ptr->data_size() == region_size) {
1786       // Full; no dead space. Next region.
1787       if (_summary_data.is_region_aligned(cur_addr)) {
1788         cur_addr += region_size;
1789       } else {
1790         cur_addr = _summary_data.region_align_up(cur_addr);
1791       }
1792       continue;
1793     }
1794 
1795     // Fill dead space inside cur_region.
1796     if (_summary_data.is_region_aligned(cur_addr)) {
1797       cur_addr += cur_region_ptr->partial_obj_size();
1798     }
1799 
1800     HeapWord* region_end_addr = _summary_data.region_align_up(cur_addr + 1);
1801     assert(region_end_addr <= end_addr, "inv");
1802     while (cur_addr < region_end_addr) {
1803       // Use end_addr to allow filler-obj to cross region boundary.
1804       HeapWord* live_start = bitmap->find_obj_beg(cur_addr, end_addr);
1805       if (cur_addr != live_start) {
1806         // Found dead space [cur_addr, live_start).
1807         fill_range_in_dense_prefix(cur_addr, live_start);
1808       }
1809       if (live_start >= region_end_addr) {
1810         cur_addr = live_start;
1811         break;
1812       }
1813       assert(bitmap->is_marked(live_start), "inv");
1814       cur_addr = live_start + cast_to_oop(live_start)->size();
1815     }
1816   }
1817 }
1818 
1819 void PSParallelCompact::compact() {
1820   GCTraceTime(Info, gc, phases) tm("Compaction Phase", &_gc_timer);
1821 
1822   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
1823 
1824   initialize_shadow_regions(active_gc_threads);
1825   prepare_region_draining_tasks(active_gc_threads);
1826 
1827   {
1828     GCTraceTime(Trace, gc, phases) tm("Par Compact", &_gc_timer);
1829 
1830     FillDensePrefixAndCompactionTask task(active_gc_threads);
1831     ParallelScavengeHeap::heap()->workers().run_task(&task);
1832 
1833 #ifdef  ASSERT
1834     verify_filler_in_dense_prefix();
1835 
1836     // Verify that all regions have been processed.
1837     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1838       verify_complete(SpaceId(id));
1839     }
1840 #endif
1841   }
1842 }
1843 
1844 #ifdef  ASSERT
1845 void PSParallelCompact::verify_filler_in_dense_prefix() {
1846   HeapWord* bottom = _space_info[old_space_id].space()->bottom();
1847   HeapWord* dense_prefix_end = dense_prefix(old_space_id);
1848 
1849   const size_t region_size = ParallelCompactData::RegionSize;
1850 
1851   for (HeapWord* cur_addr = bottom; cur_addr < dense_prefix_end; /* empty */) {
1852     RegionData* cur_region_ptr = _summary_data.addr_to_region_ptr(cur_addr);
1853     if (cur_region_ptr->data_size() == region_size) {
1854       // Full; no dead space. Next region.
1855       if (_summary_data.is_region_aligned(cur_addr)) {
1856         cur_addr += region_size;
1857       } else {
1858         cur_addr = _summary_data.region_align_up(cur_addr);
1859       }
1860       continue;
1861     }
1862 
1863     // This region contains filler objs.
1864     if (_summary_data.is_region_aligned(cur_addr)) {
1865       cur_addr += cur_region_ptr->partial_obj_size();
1866     }
1867 
1868     HeapWord* region_end_addr = _summary_data.region_align_up(cur_addr + 1);
1869     assert(region_end_addr <= dense_prefix_end, "inv");
1870 
1871     while (cur_addr < region_end_addr) {
1872       oop obj = cast_to_oop(cur_addr);
1873       oopDesc::verify(obj);
1874       if (!mark_bitmap()->is_marked(cur_addr)) {
1875         Klass* k = cast_to_oop(cur_addr)->klass();
1876         assert(k == Universe::fillerArrayKlass() || k == vmClasses::FillerObject_klass(), "inv");
1877       }
1878       cur_addr += obj->size();
1879     }
1880   }
1881 }
1882 
1883 void PSParallelCompact::verify_complete(SpaceId space_id) {
1884   // All Regions served as compaction targets, from dense_prefix() to
1885   // new_top(), should be marked as filled and all Regions between new_top()
1886   // and top() should be available (i.e., should have been emptied).
1887   ParallelCompactData& sd = summary_data();
1888   SpaceInfo si = _space_info[space_id];
1889   HeapWord* new_top_addr = sd.region_align_up(si.new_top());
1890   HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
1891   const size_t beg_region = sd.addr_to_region_idx(si.dense_prefix());
1892   const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
1893   const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
1894 
1895   size_t cur_region;
1896   for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
1897     const RegionData* const c = sd.region(cur_region);
1898     assert(c->completed(), "region %zu not filled: destination_count=%u",
1899            cur_region, c->destination_count());
1900   }
1901 
1902   for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
1903     const RegionData* const c = sd.region(cur_region);
1904     assert(c->available(), "region %zu not empty: destination_count=%u",
1905            cur_region, c->destination_count());
1906   }
1907 }
1908 #endif  // #ifdef ASSERT
1909 
1910 // Return the SpaceId for the space containing addr.  If addr is not in the
1911 // heap, last_space_id is returned.  In debug mode it expects the address to be
1912 // in the heap and asserts such.
1913 PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
1914   assert(ParallelScavengeHeap::heap()->is_in_reserved(addr), "addr not in the heap");
1915 
1916   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1917     if (_space_info[id].space()->contains(addr)) {
1918       return SpaceId(id);
1919     }
1920   }
1921 
1922   assert(false, "no space contains the addr");
1923   return last_space_id;
1924 }
1925 
1926 // Skip over count live words starting from beg, and return the address of the
1927 // next live word. Callers must also ensure that there are enough live words in
1928 // the range [beg, end) to skip.
1929 HeapWord* PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
1930 {
1931   ParMarkBitMap* m = mark_bitmap();
1932   HeapWord* cur_addr = beg;
1933   while (true) {
1934     cur_addr = m->find_obj_beg(cur_addr, end);
1935     assert(cur_addr < end, "inv");
1936     size_t obj_size = cast_to_oop(cur_addr)->size();
1937     // Strictly greater-than
1938     if (obj_size > count) {
1939       return cur_addr + count;
1940     }
1941     count -= obj_size;
1942     cur_addr += obj_size;
1943   }
1944 }
1945 
1946 // On starting to fill a destination region (dest-region), we need to know the
1947 // location of the word that will be at the start of the dest-region after
1948 // compaction. A dest-region can have one or more source regions, but only the
1949 // first source-region contains this location. This location is retrieved by
1950 // calling `first_src_addr` on a dest-region.
1951 // Conversely, a source-region has a dest-region which holds the destination of
1952 // the first live word on this source-region, based on which the destination
1953 // for the rest of live words can be derived.
1954 //
1955 // Note:
1956 // There is some complication due to space-boundary-fragmentation (an obj can't
1957 // cross space-boundary) -- a source-region may be split and behave like two
1958 // distinct regions with their own dest-region, as depicted below.
1959 //
1960 // source-region: region-n
1961 //
1962 // **********************
1963 // |     A|A~~~~B|B     |
1964 // **********************
1965 //    n-1     n     n+1
1966 //
1967 // AA, BB denote two live objs. ~~~~ denotes unknown number of live objs.
1968 //
1969 // Assuming the dest-region for region-n is the final region before
1970 // old-space-end and its first-live-word is the middle of AA, the heap content
1971 // will look like the following after compaction:
1972 //
1973 // **************                  *************
1974 //      A|A~~~~ |                  |BB    |
1975 // **************                  *************
1976 //              ^                  ^
1977 //              | old-space-end    | eden-space-start
1978 //
1979 // Therefore, in this example, region-n will have two dest-regions:
1980 // 1. the final region in old-space
1981 // 2. the first region in eden-space.
1982 // To handle this special case, we introduce the concept of split-region, whose
1983 // contents are relocated to two spaces. `SplitInfo` captures all necessary
1984 // info about the split, the first part, spliting-point, and the second part.
1985 HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
1986                                             SpaceId src_space_id,
1987                                             size_t src_region_idx)
1988 {
1989   const size_t RegionSize = ParallelCompactData::RegionSize;
1990   const ParallelCompactData& sd = summary_data();
1991   assert(sd.is_region_aligned(dest_addr), "precondition");
1992 
1993   const RegionData* const src_region_ptr = sd.region(src_region_idx);
1994   assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
1995 
1996   const size_t partial_obj_size = src_region_ptr->partial_obj_size();
1997   HeapWord* const src_region_destination = src_region_ptr->destination();
1998 
1999   HeapWord* const region_start = sd.region_to_addr(src_region_idx);
2000   HeapWord* const region_end = sd.region_to_addr(src_region_idx) + RegionSize;
2001 
2002   // Identify the actual destination for the first live words on this region,
2003   // taking split-region into account.
2004   HeapWord* region_start_destination;
2005   const SplitInfo& split_info = _space_info[src_space_id].split_info();
2006   if (split_info.is_split(src_region_idx)) {
2007     // The second part of this split region; use the recorded split point.
2008     if (dest_addr == src_region_destination) {
2009       return split_info.split_point();
2010     }
2011     region_start_destination = split_info.preceding_destination();
2012   } else {
2013     region_start_destination = src_region_destination;
2014   }
2015 
2016   // Calculate the offset to be skipped
2017   size_t words_to_skip = pointer_delta(dest_addr, region_start_destination);
2018 
2019   HeapWord* result;
2020   if (partial_obj_size > words_to_skip) {
2021     result = region_start + words_to_skip;
2022   } else {
2023     words_to_skip -= partial_obj_size;
2024     result = skip_live_words(region_start + partial_obj_size, region_end, words_to_skip);
2025   }
2026 
2027   if (split_info.is_split(src_region_idx)) {
2028     assert(result < split_info.split_point(), "postcondition");
2029   } else {
2030     assert(result < region_end, "postcondition");
2031   }
2032 
2033   return result;
2034 }
2035 
2036 void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
2037                                                      SpaceId src_space_id,
2038                                                      size_t beg_region,
2039                                                      HeapWord* end_addr)
2040 {
2041   ParallelCompactData& sd = summary_data();
2042 
2043 #ifdef ASSERT
2044   MutableSpace* const src_space = _space_info[src_space_id].space();
2045   HeapWord* const beg_addr = sd.region_to_addr(beg_region);
2046   assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
2047          "src_space_id does not match beg_addr");
2048   assert(src_space->contains(end_addr) || end_addr == src_space->end(),
2049          "src_space_id does not match end_addr");
2050 #endif // #ifdef ASSERT
2051 
2052   RegionData* const beg = sd.region(beg_region);
2053   RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));
2054 
2055   // Regions up to new_top() are enqueued if they become available.
2056   HeapWord* const new_top = _space_info[src_space_id].new_top();
2057   RegionData* const enqueue_end =
2058     sd.addr_to_region_ptr(sd.region_align_up(new_top));
2059 
2060   for (RegionData* cur = beg; cur < end; ++cur) {
2061     assert(cur->data_size() > 0, "region must have live data");
2062     cur->decrement_destination_count();
2063     if (cur < enqueue_end && cur->available() && cur->claim()) {
2064       if (cur->mark_normal()) {
2065         cm->push_region(sd.region(cur));
2066       } else if (cur->mark_copied()) {
2067         // Try to copy the content of the shadow region back to its corresponding
2068         // heap region if the shadow region is filled. Otherwise, the GC thread
2069         // fills the shadow region will copy the data back (see
2070         // MoveAndUpdateShadowClosure::complete_region).
2071         copy_back(sd.region_to_addr(cur->shadow_region()), sd.region_to_addr(cur));
2072         ParCompactionManager::push_shadow_region_mt_safe(cur->shadow_region());
2073         cur->set_completed();
2074       }
2075     }
2076   }
2077 }
2078 
2079 size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
2080                                           SpaceId& src_space_id,
2081                                           HeapWord*& src_space_top,
2082                                           HeapWord* end_addr)
2083 {
2084   ParallelCompactData& sd = PSParallelCompact::summary_data();
2085 
2086   size_t src_region_idx = 0;
2087 
2088   // Skip empty regions (if any) up to the top of the space.
2089   HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
2090   RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
2091   HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
2092   const RegionData* const top_region_ptr = sd.addr_to_region_ptr(top_aligned_up);
2093 
2094   while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
2095     ++src_region_ptr;
2096   }
2097 
2098   if (src_region_ptr < top_region_ptr) {
2099     // Found the first non-empty region in the same space.
2100     src_region_idx = sd.region(src_region_ptr);
2101     closure.set_source(sd.region_to_addr(src_region_idx));
2102     return src_region_idx;
2103   }
2104 
2105   // Switch to a new source space and find the first non-empty region.
2106   uint space_id = src_space_id + 1;
2107   assert(space_id < last_space_id, "not enough spaces");
2108 
2109   for (/* empty */; space_id < last_space_id; ++space_id) {
2110     HeapWord* bottom = _space_info[space_id].space()->bottom();
2111     HeapWord* top = _space_info[space_id].space()->top();
2112     // Skip empty space
2113     if (bottom == top) {
2114       continue;
2115     }
2116 
2117     // Identify the first region that contains live words in this space
2118     size_t cur_region = sd.addr_to_region_idx(bottom);
2119     size_t end_region = sd.addr_to_region_idx(sd.region_align_up(top));
2120 
2121     for (/* empty */ ; cur_region < end_region; ++cur_region) {
2122       RegionData* cur = sd.region(cur_region);
2123       if (cur->live_obj_size() > 0) {
2124         HeapWord* region_start_addr = sd.region_to_addr(cur_region);
2125 
2126         src_space_id = SpaceId(space_id);
2127         src_space_top = top;
2128         closure.set_source(region_start_addr);
2129         return cur_region;
2130       }
2131     }
2132   }
2133 
2134   ShouldNotReachHere();
2135 }
2136 
2137 HeapWord* PSParallelCompact::partial_obj_end(HeapWord* region_start_addr) {
2138   ParallelCompactData& sd = summary_data();
2139   assert(sd.is_region_aligned(region_start_addr), "precondition");
2140 
2141   // Use per-region partial_obj_size to locate the end of the obj, that extends
2142   // to region_start_addr.
2143   size_t start_region_idx = sd.addr_to_region_idx(region_start_addr);
2144   size_t end_region_idx = sd.region_count();
2145   size_t accumulated_size = 0;
2146   for (size_t region_idx = start_region_idx; region_idx < end_region_idx; ++region_idx) {
2147     size_t cur_partial_obj_size = sd.region(region_idx)->partial_obj_size();
2148     accumulated_size += cur_partial_obj_size;
2149     if (cur_partial_obj_size != ParallelCompactData::RegionSize) {
2150       break;
2151     }
2152   }
2153   return region_start_addr + accumulated_size;
2154 }
2155 
2156 static markWord safe_mark_word_prototype(HeapWord* cur_addr, HeapWord* end_addr) {
2157   // If the original markWord contains bits that cannot be reconstructed because
2158   // the header cannot be safely read, a placeholder is used. In this case,
2159   // the correct markWord is preserved before compaction and restored after
2160   // compaction completes.
2161   size_t remaining_words = pointer_delta(end_addr, cur_addr);
2162 
2163   if (UseCompactObjectHeaders || (Arguments::is_valhalla_enabled() && safe_to_read_header(remaining_words))) {
2164     return cast_to_oop(cur_addr)->klass()->prototype_header();
2165   } else {
2166     return markWord::prototype();
2167   }
2168 }
2169 
2170 // Use region_idx as the destination region, and evacuate all live objs on its
2171 // source regions to this destination region.
2172 void PSParallelCompact::fill_region(ParCompactionManager* cm, MoveAndUpdateClosure& closure, size_t region_idx)
2173 {
2174   ParMarkBitMap* const bitmap = mark_bitmap();
2175   ParallelCompactData& sd = summary_data();
2176   RegionData* const region_ptr = sd.region(region_idx);
2177 
2178   // Get the source region and related info.
2179   size_t src_region_idx = region_ptr->source_region();
2180   SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
2181   HeapWord* src_space_top = _space_info[src_space_id].space()->top();
2182   HeapWord* dest_addr = sd.region_to_addr(region_idx);
2183 
2184   closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
2185 
2186   // Adjust src_region_idx to prepare for decrementing destination counts (the
2187   // destination count is not decremented when a region is copied to itself).
2188   if (src_region_idx == region_idx) {
2189     src_region_idx += 1;
2190   }
2191 
2192   // source-region:
2193   //
2194   // **********
2195   // |   ~~~  |
2196   // **********
2197   //      ^
2198   //      |-- closure.source() / first_src_addr
2199   //
2200   //
2201   // ~~~ : live words
2202   //
2203   // destination-region:
2204   //
2205   // **********
2206   // |        |
2207   // **********
2208   // ^
2209   // |-- region-start
2210   if (bitmap->is_unmarked(closure.source())) {
2211     // An object overflows the previous destination region, so this
2212     // destination region should copy the remainder of the object or as much as
2213     // will fit.
2214     HeapWord* const old_src_addr = closure.source();
2215     {
2216       HeapWord* region_start = sd.region_align_down(closure.source());
2217       HeapWord* obj_start = bitmap->find_obj_beg_reverse(region_start, closure.source());
2218       HeapWord* obj_end;
2219       if (obj_start != closure.source()) {
2220         assert(bitmap->is_marked(obj_start), "inv");
2221         // Found the actual obj-start, try to find the obj-end using either
2222         // size() if this obj is completely contained in the current region.
2223         HeapWord* next_region_start = region_start + ParallelCompactData::RegionSize;
2224         HeapWord* partial_obj_start = (next_region_start >= src_space_top)
2225                                       ? nullptr
2226                                       : sd.addr_to_region_ptr(next_region_start)->partial_obj_addr();
2227         // This obj extends to next region iff partial_obj_addr of the *next*
2228         // region is the same as obj-start.
2229         if (partial_obj_start == obj_start) {
2230           // This obj extends to next region.
2231           obj_end = partial_obj_end(next_region_start);
2232         } else {
2233           // Completely contained in this region; safe to use size().
2234           obj_end = obj_start + cast_to_oop(obj_start)->size();
2235         }
2236       } else {
2237         // This obj extends to current region.
2238         obj_end = partial_obj_end(region_start);
2239       }
2240       size_t partial_obj_size = pointer_delta(obj_end, closure.source());
2241       closure.copy_partial_obj(partial_obj_size);
2242     }
2243 
2244     if (closure.is_full()) {
2245       decrement_destination_counts(cm, src_space_id, src_region_idx, closure.source());
2246       closure.complete_region(dest_addr, region_ptr);
2247       return;
2248     }
2249 
2250     // Finished copying without using up the current destination-region
2251     HeapWord* const end_addr = sd.region_align_down(closure.source());
2252     if (sd.region_align_down(old_src_addr) != end_addr) {
2253       assert(sd.region_align_up(old_src_addr) == end_addr, "only one region");
2254       // The partial object was copied from more than one source region.
2255       decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2256 
2257       // Move to the next source region, possibly switching spaces as well.  All
2258       // args except end_addr may be modified.
2259       src_region_idx = next_src_region(closure, src_space_id, src_space_top, end_addr);
2260     }
2261   }
2262 
2263   // Handle the rest obj-by-obj, where we know obj-start.
2264   do {
2265     HeapWord* cur_addr = closure.source();
2266     HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
2267                                     src_space_top);
2268     // To handle the case where the final obj in source region extends to next region.
2269     HeapWord* final_obj_start = (end_addr == src_space_top)
2270                                 ? nullptr
2271                                 : sd.addr_to_region_ptr(end_addr)->partial_obj_addr();
2272     // Apply closure on objs inside [cur_addr, end_addr)
2273     do {
2274       cur_addr = bitmap->find_obj_beg(cur_addr, end_addr);
2275       if (cur_addr == end_addr) {
2276         break;
2277       }
2278       size_t obj_size;
2279       if (final_obj_start == cur_addr) {
2280         obj_size = pointer_delta(partial_obj_end(end_addr), cur_addr);
2281       } else {
2282         // This obj doesn't extend into next region; size() is safe to use.
2283         obj_size = cast_to_oop(cur_addr)->size();
2284       }
2285 
2286       markWord mark = safe_mark_word_prototype(cur_addr, end_addr);
2287 
2288       // Perform the move and update of the object
2289       closure.do_addr(cur_addr, obj_size, mark);
2290 
2291       cur_addr += obj_size;
2292     } while (cur_addr < end_addr && !closure.is_full());
2293 
2294     if (closure.is_full()) {
2295       decrement_destination_counts(cm, src_space_id, src_region_idx, closure.source());
2296       closure.complete_region(dest_addr, region_ptr);
2297       return;
2298     }
2299 
2300     decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2301 
2302     // Move to the next source region, possibly switching spaces as well.  All
2303     // args except end_addr may be modified.
2304     src_region_idx = next_src_region(closure, src_space_id, src_space_top, end_addr);
2305   } while (true);
2306 }
2307 
2308 void PSParallelCompact::fill_and_update_region(ParCompactionManager* cm, size_t region_idx)
2309 {
2310   MoveAndUpdateClosure cl(mark_bitmap(), region_idx);
2311   fill_region(cm, cl, region_idx);
2312 }
2313 
2314 void PSParallelCompact::fill_and_update_shadow_region(ParCompactionManager* cm, size_t region_idx)
2315 {
2316   // Get a shadow region first
2317   ParallelCompactData& sd = summary_data();
2318   RegionData* const region_ptr = sd.region(region_idx);
2319   size_t shadow_region = ParCompactionManager::pop_shadow_region_mt_safe(region_ptr);
2320   // The InvalidShadow return value indicates the corresponding heap region is available,
2321   // so use MoveAndUpdateClosure to fill the normal region. Otherwise, use
2322   // MoveAndUpdateShadowClosure to fill the acquired shadow region.
2323   if (shadow_region == ParCompactionManager::InvalidShadow) {
2324     MoveAndUpdateClosure cl(mark_bitmap(), region_idx);
2325     region_ptr->shadow_to_normal();
2326     return fill_region(cm, cl, region_idx);
2327   } else {
2328     MoveAndUpdateShadowClosure cl(mark_bitmap(), region_idx, shadow_region);
2329     return fill_region(cm, cl, region_idx);
2330   }
2331 }
2332 
2333 void PSParallelCompact::copy_back(HeapWord *shadow_addr, HeapWord *region_addr)
2334 {
2335   Copy::aligned_conjoint_words(shadow_addr, region_addr, _summary_data.RegionSize);
2336 }
2337 
2338 bool PSParallelCompact::steal_unavailable_region(ParCompactionManager* cm, size_t &region_idx)
2339 {
2340   size_t next = cm->next_shadow_region();
2341   ParallelCompactData& sd = summary_data();
2342   size_t old_new_top = sd.addr_to_region_idx(_space_info[old_space_id].new_top());
2343   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2344 
2345   while (next < old_new_top) {
2346     if (sd.region(next)->mark_shadow()) {
2347       region_idx = next;
2348       return true;
2349     }
2350     next = cm->move_next_shadow_region_by(active_gc_threads);
2351   }
2352 
2353   return false;
2354 }
2355 
2356 // The shadow region is an optimization to address region dependencies in full GC. The basic
2357 // idea is making more regions available by temporally storing their live objects in empty
2358 // shadow regions to resolve dependencies between them and the destination regions. Therefore,
2359 // GC threads need not wait destination regions to be available before processing sources.
2360 //
2361 // A typical workflow would be:
2362 // After draining its own stack and failing to steal from others, a GC worker would pick an
2363 // unavailable region (destination count > 0) and get a shadow region. Then the worker fills
2364 // the shadow region by copying live objects from source regions of the unavailable one. Once
2365 // the unavailable region becomes available, the data in the shadow region will be copied back.
2366 // Shadow regions are empty regions in the to-space and regions between top and end of other spaces.
2367 void PSParallelCompact::initialize_shadow_regions(uint parallel_gc_threads)
2368 {
2369   const ParallelCompactData& sd = PSParallelCompact::summary_data();
2370 
2371   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2372     SpaceInfo* const space_info = _space_info + id;
2373     MutableSpace* const space = space_info->space();
2374 
2375     const size_t beg_region =
2376       sd.addr_to_region_idx(sd.region_align_up(MAX2(space_info->new_top(), space->top())));
2377     const size_t end_region =
2378       sd.addr_to_region_idx(sd.region_align_down(space->end()));
2379 
2380     for (size_t cur = beg_region; cur < end_region; ++cur) {
2381       ParCompactionManager::push_shadow_region(cur);
2382     }
2383   }
2384 
2385   size_t beg_region = sd.addr_to_region_idx(_space_info[old_space_id].dense_prefix());
2386   for (uint i = 0; i < parallel_gc_threads; i++) {
2387     ParCompactionManager *cm = ParCompactionManager::gc_thread_compaction_manager(i);
2388     cm->set_next_shadow_region(beg_region + i);
2389   }
2390 }
2391 
2392 void MoveAndUpdateClosure::copy_partial_obj(size_t partial_obj_size)
2393 {
2394   size_t words = MIN2(partial_obj_size, words_remaining());
2395 
2396   // This test is necessary; if omitted, the pointer updates to a partial object
2397   // that crosses the dense prefix boundary could be overwritten.
2398   if (source() != copy_destination()) {
2399     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2400     Copy::aligned_conjoint_words(source(), copy_destination(), words);
2401   }
2402   update_state(words);
2403 }
2404 
2405 void MoveAndUpdateClosure::complete_region(HeapWord* dest_addr, PSParallelCompact::RegionData* region_ptr) {
2406   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::NormalRegion, "Region should be finished");
2407   region_ptr->set_completed();
2408 }
2409 
2410 void MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words, markWord mark) {
2411   assert(destination() != nullptr, "sanity");
2412   _source = addr;
2413 
2414   // The start_array must be updated even if the object is not moving.
2415   if (_start_array != nullptr) {
2416     _start_array->update_for_block(destination(), destination() + words);
2417   }
2418 
2419   // Avoid overflow
2420   words = MIN2(words, words_remaining());
2421   assert(words > 0, "inv");
2422 
2423   if (copy_destination() != source()) {
2424     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2425     assert(source() != destination(), "inv");
2426     assert(FullGCForwarding::is_forwarded(cast_to_oop(source())), "inv");
2427     assert(FullGCForwarding::forwardee(cast_to_oop(source())) == cast_to_oop(destination()), "inv");
2428     Copy::aligned_conjoint_words(source(), copy_destination(), words);
2429     cast_to_oop(copy_destination())->set_mark(mark);
2430   }
2431 
2432   update_state(words);
2433 }
2434 
2435 void MoveAndUpdateShadowClosure::complete_region(HeapWord* dest_addr, PSParallelCompact::RegionData* region_ptr) {
2436   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::ShadowRegion, "Region should be shadow");
2437   // Record the shadow region index
2438   region_ptr->set_shadow_region(_shadow);
2439   // Mark the shadow region as filled to indicate the data is ready to be
2440   // copied back
2441   region_ptr->mark_filled();
2442   // Try to copy the content of the shadow region back to its corresponding
2443   // heap region if available; the GC thread that decreases the destination
2444   // count to zero will do the copying otherwise (see
2445   // PSParallelCompact::decrement_destination_counts).
2446   if (((region_ptr->available() && region_ptr->claim()) || region_ptr->claimed()) && region_ptr->mark_copied()) {
2447     region_ptr->set_completed();
2448     PSParallelCompact::copy_back(PSParallelCompact::summary_data().region_to_addr(_shadow), dest_addr);
2449     ParCompactionManager::push_shadow_region_mt_safe(_shadow);
2450   }
2451 }