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