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