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