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