1 /*
   2  * Copyright (c) 2005, 2024, 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 "precompiled.hpp"
  26 #include "classfile/classLoaderDataGraph.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "compiler/oopMap.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/gcCause.hpp"
  47 #include "gc/shared/gcHeapSummary.hpp"
  48 #include "gc/shared/gcId.hpp"
  49 #include "gc/shared/gcLocker.hpp"
  50 #include "gc/shared/gcTimer.hpp"
  51 #include "gc/shared/gcTrace.hpp"
  52 #include "gc/shared/gcTraceTime.inline.hpp"
  53 #include "gc/shared/isGCActiveMark.hpp"
  54 #include "gc/shared/oopStorage.inline.hpp"
  55 #include "gc/shared/oopStorageSet.inline.hpp"
  56 #include "gc/shared/oopStorageSetParState.inline.hpp"
  57 #include "gc/shared/referencePolicy.hpp"
  58 #include "gc/shared/referenceProcessor.hpp"
  59 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
  60 #include "gc/shared/spaceDecorator.inline.hpp"
  61 #include "gc/shared/taskTerminator.hpp"
  62 #include "gc/shared/weakProcessor.inline.hpp"
  63 #include "gc/shared/workerPolicy.hpp"
  64 #include "gc/shared/workerThread.hpp"
  65 #include "gc/shared/workerUtils.hpp"
  66 #include "logging/log.hpp"
  67 #include "memory/iterator.inline.hpp"
  68 #include "memory/metaspaceUtils.hpp"
  69 #include "memory/resourceArea.hpp"
  70 #include "memory/universe.hpp"
  71 #include "nmt/memTracker.hpp"
  72 #include "oops/access.inline.hpp"
  73 #include "oops/instanceClassLoaderKlass.inline.hpp"
  74 #include "oops/instanceKlass.inline.hpp"
  75 #include "oops/instanceMirrorKlass.inline.hpp"
  76 #include "oops/methodData.hpp"
  77 #include "oops/objArrayKlass.inline.hpp"
  78 #include "oops/oop.inline.hpp"
  79 #include "runtime/atomic.hpp"
  80 #include "runtime/handles.inline.hpp"
  81 #include "runtime/java.hpp"
  82 #include "runtime/safepoint.hpp"
  83 #include "runtime/threads.hpp"
  84 #include "runtime/vmThread.hpp"
  85 #include "services/memoryService.hpp"
  86 #include "utilities/align.hpp"
  87 #include "utilities/debug.hpp"
  88 #include "utilities/events.hpp"
  89 #include "utilities/formatBuffer.hpp"
  90 #include "utilities/macros.hpp"
  91 #include "utilities/stack.inline.hpp"
  92 #if INCLUDE_JVMCI
  93 #include "jvmci/jvmci.hpp"
  94 #endif
  95 
  96 #include <math.h>
  97 
  98 // All sizes are in HeapWords.
  99 const size_t ParallelCompactData::Log2RegionSize  = 16; // 64K words
 100 const size_t ParallelCompactData::RegionSize      = (size_t)1 << Log2RegionSize;
 101 const size_t ParallelCompactData::RegionSizeBytes =
 102   RegionSize << LogHeapWordSize;
 103 const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
 104 const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
 105 const size_t ParallelCompactData::RegionAddrMask       = ~RegionAddrOffsetMask;
 106 
 107 const size_t ParallelCompactData::Log2BlockSize   = 7; // 128 words
 108 const size_t ParallelCompactData::BlockSize       = (size_t)1 << Log2BlockSize;
 109 const size_t ParallelCompactData::BlockSizeBytes  =
 110   BlockSize << LogHeapWordSize;
 111 const size_t ParallelCompactData::BlockSizeOffsetMask = BlockSize - 1;
 112 const size_t ParallelCompactData::BlockAddrOffsetMask = BlockSizeBytes - 1;
 113 const size_t ParallelCompactData::BlockAddrMask       = ~BlockAddrOffsetMask;
 114 
 115 const size_t ParallelCompactData::BlocksPerRegion = RegionSize / BlockSize;
 116 const size_t ParallelCompactData::Log2BlocksPerRegion =
 117   Log2RegionSize - Log2BlockSize;
 118 
 119 const ParallelCompactData::RegionData::region_sz_t
 120 ParallelCompactData::RegionData::dc_shift = 27;
 121 
 122 const ParallelCompactData::RegionData::region_sz_t
 123 ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
 124 
 125 const ParallelCompactData::RegionData::region_sz_t
 126 ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
 127 
 128 const ParallelCompactData::RegionData::region_sz_t
 129 ParallelCompactData::RegionData::los_mask = ~dc_mask;
 130 
 131 const ParallelCompactData::RegionData::region_sz_t
 132 ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
 133 
 134 const ParallelCompactData::RegionData::region_sz_t
 135 ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
 136 
 137 SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
 138 
 139 SpanSubjectToDiscoveryClosure PSParallelCompact::_span_based_discoverer;
 140 ReferenceProcessor* PSParallelCompact::_ref_processor = nullptr;
 141 
 142 void SplitInfo::record(size_t src_region_idx, size_t partial_obj_size,
 143                        HeapWord* destination)
 144 {
 145   assert(src_region_idx != 0, "invalid src_region_idx");
 146   assert(partial_obj_size != 0, "invalid partial_obj_size argument");
 147   assert(destination != nullptr, "invalid destination argument");
 148 
 149   _src_region_idx = src_region_idx;
 150   _partial_obj_size = partial_obj_size;
 151   _destination = destination;
 152 
 153   // These fields may not be updated below, so make sure they're clear.
 154   assert(_dest_region_addr == nullptr, "should have been cleared");
 155   assert(_first_src_addr == nullptr, "should have been cleared");
 156 
 157   // Determine the number of destination regions for the partial object.
 158   HeapWord* const last_word = destination + partial_obj_size - 1;
 159   const ParallelCompactData& sd = PSParallelCompact::summary_data();
 160   HeapWord* const beg_region_addr = sd.region_align_down(destination);
 161   HeapWord* const end_region_addr = sd.region_align_down(last_word);
 162 
 163   if (beg_region_addr == end_region_addr) {
 164     // One destination region.
 165     _destination_count = 1;
 166     if (end_region_addr == destination) {
 167       // The destination falls on a region boundary, thus the first word of the
 168       // partial object will be the first word copied to the destination region.
 169       _dest_region_addr = end_region_addr;
 170       _first_src_addr = sd.region_to_addr(src_region_idx);
 171     }
 172   } else {
 173     // Two destination regions.  When copied, the partial object will cross a
 174     // destination region boundary, so a word somewhere within the partial
 175     // object will be the first word copied to the second destination region.
 176     _destination_count = 2;
 177     _dest_region_addr = end_region_addr;
 178     const size_t ofs = pointer_delta(end_region_addr, destination);
 179     assert(ofs < _partial_obj_size, "sanity");
 180     _first_src_addr = sd.region_to_addr(src_region_idx) + ofs;
 181   }
 182 }
 183 
 184 void SplitInfo::clear()
 185 {
 186   _src_region_idx = 0;
 187   _partial_obj_size = 0;
 188   _destination = nullptr;
 189   _destination_count = 0;
 190   _dest_region_addr = nullptr;
 191   _first_src_addr = nullptr;
 192   assert(!is_valid(), "sanity");
 193 }
 194 
 195 #ifdef  ASSERT
 196 void SplitInfo::verify_clear()
 197 {
 198   assert(_src_region_idx == 0, "not clear");
 199   assert(_partial_obj_size == 0, "not clear");
 200   assert(_destination == nullptr, "not clear");
 201   assert(_destination_count == 0, "not clear");
 202   assert(_dest_region_addr == nullptr, "not clear");
 203   assert(_first_src_addr == nullptr, "not clear");
 204 }
 205 #endif  // #ifdef ASSERT
 206 
 207 
 208 void PSParallelCompact::print_on_error(outputStream* st) {
 209   _mark_bitmap.print_on_error(st);
 210 }
 211 
 212 #ifndef PRODUCT
 213 const char* PSParallelCompact::space_names[] = {
 214   "old ", "eden", "from", "to  "
 215 };
 216 
 217 void PSParallelCompact::print_region_ranges() {
 218   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 219     return;
 220   }
 221   Log(gc, compaction) log;
 222   ResourceMark rm;
 223   LogStream ls(log.trace());
 224   Universe::print_on(&ls);
 225   log.trace("space  bottom     top        end        new_top");
 226   log.trace("------ ---------- ---------- ---------- ----------");
 227 
 228   for (unsigned int id = 0; id < last_space_id; ++id) {
 229     const MutableSpace* space = _space_info[id].space();
 230     log.trace("%u %s "
 231               SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " "
 232               SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ",
 233               id, space_names[id],
 234               summary_data().addr_to_region_idx(space->bottom()),
 235               summary_data().addr_to_region_idx(space->top()),
 236               summary_data().addr_to_region_idx(space->end()),
 237               summary_data().addr_to_region_idx(_space_info[id].new_top()));
 238   }
 239 }
 240 
 241 static void
 242 print_generic_summary_region(size_t i, const ParallelCompactData::RegionData* c)
 243 {
 244 #define REGION_IDX_FORMAT        SIZE_FORMAT_W(7)
 245 #define REGION_DATA_FORMAT       SIZE_FORMAT_W(5)
 246 
 247   ParallelCompactData& sd = PSParallelCompact::summary_data();
 248   size_t dci = c->destination() ? sd.addr_to_region_idx(c->destination()) : 0;
 249   log_develop_trace(gc, compaction)(
 250       REGION_IDX_FORMAT " "
 251       REGION_IDX_FORMAT " " PTR_FORMAT " "
 252       REGION_DATA_FORMAT " " REGION_DATA_FORMAT " "
 253       REGION_DATA_FORMAT " " REGION_IDX_FORMAT " %d",
 254       i, dci, p2i(c->destination()),
 255       c->partial_obj_size(), c->live_obj_size(),
 256       c->data_size(), c->source_region(), c->destination_count());
 257 
 258 #undef  REGION_IDX_FORMAT
 259 #undef  REGION_DATA_FORMAT
 260 }
 261 
 262 void
 263 print_generic_summary_data(ParallelCompactData& summary_data,
 264                            HeapWord* const beg_addr,
 265                            HeapWord* const end_addr)
 266 {
 267   size_t total_words = 0;
 268   size_t i = summary_data.addr_to_region_idx(beg_addr);
 269   const size_t last = summary_data.addr_to_region_idx(end_addr);
 270   HeapWord* pdest = 0;
 271 
 272   while (i < last) {
 273     ParallelCompactData::RegionData* c = summary_data.region(i);
 274     if (c->data_size() != 0 || c->destination() != pdest) {
 275       print_generic_summary_region(i, c);
 276       total_words += c->data_size();
 277       pdest = c->destination();
 278     }
 279     ++i;
 280   }
 281 
 282   log_develop_trace(gc, compaction)("summary_data_bytes=" SIZE_FORMAT, total_words * HeapWordSize);
 283 }
 284 
 285 void
 286 PSParallelCompact::print_generic_summary_data(ParallelCompactData& summary_data,
 287                                               HeapWord* const beg_addr,
 288                                               HeapWord* const end_addr) {
 289   ::print_generic_summary_data(summary_data,beg_addr, end_addr);
 290 }
 291 
 292 void
 293 print_generic_summary_data(ParallelCompactData& summary_data,
 294                            SpaceInfo* space_info)
 295 {
 296   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 297     return;
 298   }
 299 
 300   for (unsigned int id = 0; id < PSParallelCompact::last_space_id; ++id) {
 301     const MutableSpace* space = space_info[id].space();
 302     print_generic_summary_data(summary_data, space->bottom(),
 303                                MAX2(space->top(), space_info[id].new_top()));
 304   }
 305 }
 306 
 307 static void
 308 print_initial_summary_data(ParallelCompactData& summary_data,
 309                            const MutableSpace* space) {
 310   if (space->top() == space->bottom()) {
 311     return;
 312   }
 313 
 314   const size_t region_size = ParallelCompactData::RegionSize;
 315   typedef ParallelCompactData::RegionData RegionData;
 316   HeapWord* const top_aligned_up = summary_data.region_align_up(space->top());
 317   const size_t end_region = summary_data.addr_to_region_idx(top_aligned_up);
 318   const RegionData* c = summary_data.region(end_region - 1);
 319   HeapWord* end_addr = c->destination() + c->data_size();
 320   const size_t live_in_space = pointer_delta(end_addr, space->bottom());
 321 
 322   // Print (and count) the full regions at the beginning of the space.
 323   size_t full_region_count = 0;
 324   size_t i = summary_data.addr_to_region_idx(space->bottom());
 325   while (i < end_region && summary_data.region(i)->data_size() == region_size) {
 326     ParallelCompactData::RegionData* c = summary_data.region(i);
 327     log_develop_trace(gc, compaction)(
 328         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
 329         i, p2i(c->destination()),
 330         c->partial_obj_size(), c->live_obj_size(),
 331         c->data_size(), c->source_region(), c->destination_count());
 332     ++full_region_count;
 333     ++i;
 334   }
 335 
 336   size_t live_to_right = live_in_space - full_region_count * region_size;
 337 
 338   double max_reclaimed_ratio = 0.0;
 339   size_t max_reclaimed_ratio_region = 0;
 340   size_t max_dead_to_right = 0;
 341   size_t max_live_to_right = 0;
 342 
 343   // Print the 'reclaimed ratio' for regions while there is something live in
 344   // the region or to the right of it.  The remaining regions are empty (and
 345   // uninteresting), and computing the ratio will result in division by 0.
 346   while (i < end_region && live_to_right > 0) {
 347     c = summary_data.region(i);
 348     HeapWord* const region_addr = summary_data.region_to_addr(i);
 349     const size_t used_to_right = pointer_delta(space->top(), region_addr);
 350     const size_t dead_to_right = used_to_right - live_to_right;
 351     const double reclaimed_ratio = double(dead_to_right) / live_to_right;
 352 
 353     if (reclaimed_ratio > max_reclaimed_ratio) {
 354             max_reclaimed_ratio = reclaimed_ratio;
 355             max_reclaimed_ratio_region = i;
 356             max_dead_to_right = dead_to_right;
 357             max_live_to_right = live_to_right;
 358     }
 359 
 360     ParallelCompactData::RegionData* c = summary_data.region(i);
 361     log_develop_trace(gc, compaction)(
 362         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d"
 363         "%12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10),
 364         i, p2i(c->destination()),
 365         c->partial_obj_size(), c->live_obj_size(),
 366         c->data_size(), c->source_region(), c->destination_count(),
 367         reclaimed_ratio, dead_to_right, live_to_right);
 368 
 369 
 370     live_to_right -= c->data_size();
 371     ++i;
 372   }
 373 
 374   // Any remaining regions are empty.  Print one more if there is one.
 375   if (i < end_region) {
 376     ParallelCompactData::RegionData* c = summary_data.region(i);
 377     log_develop_trace(gc, compaction)(
 378         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
 379          i, p2i(c->destination()),
 380          c->partial_obj_size(), c->live_obj_size(),
 381          c->data_size(), c->source_region(), c->destination_count());
 382   }
 383 
 384   log_develop_trace(gc, compaction)("max:  " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f",
 385                                     max_reclaimed_ratio_region, max_dead_to_right, max_live_to_right, max_reclaimed_ratio);
 386 }
 387 
 388 static void
 389 print_initial_summary_data(ParallelCompactData& summary_data,
 390                            SpaceInfo* space_info) {
 391   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 392     return;
 393   }
 394 
 395   unsigned int id = PSParallelCompact::old_space_id;
 396   const MutableSpace* space;
 397   do {
 398     space = space_info[id].space();
 399     print_initial_summary_data(summary_data, space);
 400   } while (++id < PSParallelCompact::eden_space_id);
 401 
 402   do {
 403     space = space_info[id].space();
 404     print_generic_summary_data(summary_data, space->bottom(), space->top());
 405   } while (++id < PSParallelCompact::last_space_id);
 406 }
 407 #endif  // #ifndef PRODUCT
 408 
 409 ParallelCompactData::ParallelCompactData() :
 410   _heap_start(nullptr),
 411   DEBUG_ONLY(_heap_end(nullptr) COMMA)
 412   _region_vspace(nullptr),
 413   _reserved_byte_size(0),
 414   _region_data(nullptr),
 415   _region_count(0),
 416   _block_vspace(nullptr),
 417   _block_data(nullptr),
 418   _block_count(0) {}
 419 
 420 bool ParallelCompactData::initialize(MemRegion reserved_heap)
 421 {
 422   _heap_start = reserved_heap.start();
 423   const size_t heap_size = reserved_heap.word_size();
 424   DEBUG_ONLY(_heap_end = _heap_start + heap_size;)
 425 
 426   assert(region_align_down(_heap_start) == _heap_start,
 427          "region start not aligned");
 428 
 429   bool result = initialize_region_data(heap_size) && initialize_block_data();
 430   return result;
 431 }
 432 
 433 PSVirtualSpace*
 434 ParallelCompactData::create_vspace(size_t count, size_t element_size)
 435 {
 436   const size_t raw_bytes = count * element_size;
 437   const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);
 438   const size_t granularity = os::vm_allocation_granularity();
 439   _reserved_byte_size = align_up(raw_bytes, MAX2(page_sz, granularity));
 440 
 441   const size_t rs_align = page_sz == os::vm_page_size() ? 0 :
 442     MAX2(page_sz, granularity);
 443   ReservedSpace rs(_reserved_byte_size, rs_align, page_sz);
 444   os::trace_page_sizes("Parallel Compact Data", raw_bytes, raw_bytes, rs.base(),
 445                        rs.size(), page_sz);
 446 
 447   MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);
 448 
 449   PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
 450   if (vspace != 0) {
 451     if (vspace->expand_by(_reserved_byte_size)) {
 452       return vspace;
 453     }
 454     delete vspace;
 455     // Release memory reserved in the space.
 456     rs.release();
 457   }
 458 
 459   return 0;
 460 }
 461 
 462 bool ParallelCompactData::initialize_region_data(size_t heap_size)
 463 {
 464   assert(is_aligned(heap_size, RegionSize), "precondition");
 465 
 466   const size_t count = heap_size >> Log2RegionSize;
 467   _region_vspace = create_vspace(count, sizeof(RegionData));
 468   if (_region_vspace != 0) {
 469     _region_data = (RegionData*)_region_vspace->reserved_low_addr();
 470     _region_count = count;
 471     return true;
 472   }
 473   return false;
 474 }
 475 
 476 bool ParallelCompactData::initialize_block_data()
 477 {
 478   assert(_region_count != 0, "region data must be initialized first");
 479   const size_t count = _region_count << Log2BlocksPerRegion;
 480   _block_vspace = create_vspace(count, sizeof(BlockData));
 481   if (_block_vspace != 0) {
 482     _block_data = (BlockData*)_block_vspace->reserved_low_addr();
 483     _block_count = count;
 484     return true;
 485   }
 486   return false;
 487 }
 488 
 489 void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
 490   assert(beg_region <= _region_count, "beg_region out of range");
 491   assert(end_region <= _region_count, "end_region out of range");
 492   assert(RegionSize % BlockSize == 0, "RegionSize not a multiple of BlockSize");
 493 
 494   const size_t region_cnt = end_region - beg_region;
 495   memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));
 496 
 497   const size_t beg_block = beg_region * BlocksPerRegion;
 498   const size_t block_cnt = region_cnt * BlocksPerRegion;
 499   memset(_block_data + beg_block, 0, block_cnt * sizeof(BlockData));
 500 }
 501 
 502 HeapWord* ParallelCompactData::partial_obj_end(size_t region_idx) const
 503 {
 504   const RegionData* cur_cp = region(region_idx);
 505   const RegionData* const end_cp = region(region_count() - 1);
 506 
 507   HeapWord* result = region_to_addr(region_idx);
 508   if (cur_cp < end_cp) {
 509     do {
 510       result += cur_cp->partial_obj_size();
 511     } while (cur_cp->partial_obj_size() == RegionSize && ++cur_cp < end_cp);
 512   }
 513   return result;
 514 }
 515 
 516 void
 517 ParallelCompactData::summarize_dense_prefix(HeapWord* beg, HeapWord* end)
 518 {
 519   assert(is_region_aligned(beg), "not RegionSize aligned");
 520   assert(is_region_aligned(end), "not RegionSize aligned");
 521 
 522   size_t cur_region = addr_to_region_idx(beg);
 523   const size_t end_region = addr_to_region_idx(end);
 524   HeapWord* addr = beg;
 525   while (cur_region < end_region) {
 526     _region_data[cur_region].set_destination(addr);
 527     _region_data[cur_region].set_destination_count(0);
 528     _region_data[cur_region].set_source_region(cur_region);
 529 
 530     // Update live_obj_size so the region appears completely full.
 531     size_t live_size = RegionSize - _region_data[cur_region].partial_obj_size();
 532     _region_data[cur_region].set_live_obj_size(live_size);
 533 
 534     ++cur_region;
 535     addr += RegionSize;
 536   }
 537 }
 538 
 539 // Find the point at which a space can be split and, if necessary, record the
 540 // split point.
 541 //
 542 // If the current src region (which overflowed the destination space) doesn't
 543 // have a partial object, the split point is at the beginning of the current src
 544 // region (an "easy" split, no extra bookkeeping required).
 545 //
 546 // If the current src region has a partial object, the split point is in the
 547 // region where that partial object starts (call it the split_region).  If
 548 // split_region has a partial object, then the split point is just after that
 549 // partial object (a "hard" split where we have to record the split data and
 550 // zero the partial_obj_size field).  With a "hard" split, we know that the
 551 // partial_obj ends within split_region because the partial object that caused
 552 // the overflow starts in split_region.  If split_region doesn't have a partial
 553 // obj, then the split is at the beginning of split_region (another "easy"
 554 // split).
 555 HeapWord*
 556 ParallelCompactData::summarize_split_space(size_t src_region,
 557                                            SplitInfo& split_info,
 558                                            HeapWord* destination,
 559                                            HeapWord* target_end,
 560                                            HeapWord** target_next)
 561 {
 562   assert(destination <= target_end, "sanity");
 563   assert(destination + _region_data[src_region].data_size() > target_end,
 564     "region should not fit into target space");
 565   assert(is_region_aligned(target_end), "sanity");
 566 
 567   size_t split_region = src_region;
 568   HeapWord* split_destination = destination;
 569   size_t partial_obj_size = _region_data[src_region].partial_obj_size();
 570 
 571   if (destination + partial_obj_size > target_end) {
 572     // The split point is just after the partial object (if any) in the
 573     // src_region that contains the start of the object that overflowed the
 574     // destination space.
 575     //
 576     // Find the start of the "overflow" object and set split_region to the
 577     // region containing it.
 578     HeapWord* const overflow_obj = _region_data[src_region].partial_obj_addr();
 579     split_region = addr_to_region_idx(overflow_obj);
 580 
 581     // Clear the source_region field of all destination regions whose first word
 582     // came from data after the split point (a non-null source_region field
 583     // implies a region must be filled).
 584     //
 585     // An alternative to the simple loop below:  clear during post_compact(),
 586     // which uses memcpy instead of individual stores, and is easy to
 587     // parallelize.  (The downside is that it clears the entire RegionData
 588     // object as opposed to just one field.)
 589     //
 590     // post_compact() would have to clear the summary data up to the highest
 591     // address that was written during the summary phase, which would be
 592     //
 593     //         max(top, max(new_top, clear_top))
 594     //
 595     // where clear_top is a new field in SpaceInfo.  Would have to set clear_top
 596     // to target_end.
 597     const RegionData* const sr = region(split_region);
 598     const size_t beg_idx =
 599       addr_to_region_idx(region_align_up(sr->destination() +
 600                                          sr->partial_obj_size()));
 601     const size_t end_idx = addr_to_region_idx(target_end);
 602 
 603     log_develop_trace(gc, compaction)("split:  clearing source_region field in [" SIZE_FORMAT ", " SIZE_FORMAT ")", beg_idx, end_idx);
 604     for (size_t idx = beg_idx; idx < end_idx; ++idx) {
 605       _region_data[idx].set_source_region(0);
 606     }
 607 
 608     // Set split_destination and partial_obj_size to reflect the split region.
 609     split_destination = sr->destination();
 610     partial_obj_size = sr->partial_obj_size();
 611   }
 612 
 613   // The split is recorded only if a partial object extends onto the region.
 614   if (partial_obj_size != 0) {
 615     _region_data[split_region].set_partial_obj_size(0);
 616     split_info.record(split_region, partial_obj_size, split_destination);
 617   }
 618 
 619   // Setup the continuation addresses.
 620   *target_next = split_destination + partial_obj_size;
 621   HeapWord* const source_next = region_to_addr(split_region) + partial_obj_size;
 622 
 623   if (log_develop_is_enabled(Trace, gc, compaction)) {
 624     const char * split_type = partial_obj_size == 0 ? "easy" : "hard";
 625     log_develop_trace(gc, compaction)("%s split:  src=" PTR_FORMAT " src_c=" SIZE_FORMAT " pos=" SIZE_FORMAT,
 626                                       split_type, p2i(source_next), split_region, partial_obj_size);
 627     log_develop_trace(gc, compaction)("%s split:  dst=" PTR_FORMAT " dst_c=" SIZE_FORMAT " tn=" PTR_FORMAT,
 628                                       split_type, p2i(split_destination),
 629                                       addr_to_region_idx(split_destination),
 630                                       p2i(*target_next));
 631 
 632     if (partial_obj_size != 0) {
 633       HeapWord* const po_beg = split_info.destination();
 634       HeapWord* const po_end = po_beg + split_info.partial_obj_size();
 635       log_develop_trace(gc, compaction)("%s split:  po_beg=" PTR_FORMAT " " SIZE_FORMAT " po_end=" PTR_FORMAT " " SIZE_FORMAT,
 636                                         split_type,
 637                                         p2i(po_beg), addr_to_region_idx(po_beg),
 638                                         p2i(po_end), addr_to_region_idx(po_end));
 639     }
 640   }
 641 
 642   return source_next;
 643 }
 644 
 645 bool ParallelCompactData::summarize(SplitInfo& split_info,
 646                                     HeapWord* source_beg, HeapWord* source_end,
 647                                     HeapWord** source_next,
 648                                     HeapWord* target_beg, HeapWord* target_end,
 649                                     HeapWord** target_next)
 650 {
 651   HeapWord* const source_next_val = source_next == nullptr ? nullptr : *source_next;
 652   log_develop_trace(gc, compaction)(
 653       "sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
 654       "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
 655       p2i(source_beg), p2i(source_end), p2i(source_next_val),
 656       p2i(target_beg), p2i(target_end), p2i(*target_next));
 657 
 658   size_t cur_region = addr_to_region_idx(source_beg);
 659   const size_t end_region = addr_to_region_idx(region_align_up(source_end));
 660 
 661   HeapWord *dest_addr = target_beg;
 662   while (cur_region < end_region) {
 663     // The destination must be set even if the region has no data.
 664     _region_data[cur_region].set_destination(dest_addr);
 665 
 666     size_t words = _region_data[cur_region].data_size();
 667     if (words > 0) {
 668       // If cur_region does not fit entirely into the target space, find a point
 669       // at which the source space can be 'split' so that part is copied to the
 670       // target space and the rest is copied elsewhere.
 671       if (dest_addr + words > target_end) {
 672         assert(source_next != nullptr, "source_next is null when splitting");
 673         *source_next = summarize_split_space(cur_region, split_info, dest_addr,
 674                                              target_end, target_next);
 675         return false;
 676       }
 677 
 678       // Compute the destination_count for cur_region, and if necessary, update
 679       // source_region for a destination region.  The source_region field is
 680       // updated if cur_region is the first (left-most) region to be copied to a
 681       // destination region.
 682       //
 683       // The destination_count calculation is a bit subtle.  A region that has
 684       // data that compacts into itself does not count itself as a destination.
 685       // This maintains the invariant that a zero count means the region is
 686       // available and can be claimed and then filled.
 687       uint destination_count = 0;
 688       if (split_info.is_split(cur_region)) {
 689         // The current region has been split:  the partial object will be copied
 690         // to one destination space and the remaining data will be copied to
 691         // another destination space.  Adjust the initial destination_count and,
 692         // if necessary, set the source_region field if the partial object will
 693         // cross a destination region boundary.
 694         destination_count = split_info.destination_count();
 695         if (destination_count == 2) {
 696           size_t dest_idx = addr_to_region_idx(split_info.dest_region_addr());
 697           _region_data[dest_idx].set_source_region(cur_region);
 698         }
 699       }
 700 
 701       HeapWord* const last_addr = dest_addr + words - 1;
 702       const size_t dest_region_1 = addr_to_region_idx(dest_addr);
 703       const size_t dest_region_2 = addr_to_region_idx(last_addr);
 704 
 705       // Initially assume that the destination regions will be the same and
 706       // adjust the value below if necessary.  Under this assumption, if
 707       // cur_region == dest_region_2, then cur_region will be compacted
 708       // completely into itself.
 709       destination_count += cur_region == dest_region_2 ? 0 : 1;
 710       if (dest_region_1 != dest_region_2) {
 711         // Destination regions differ; adjust destination_count.
 712         destination_count += 1;
 713         // Data from cur_region will be copied to the start of dest_region_2.
 714         _region_data[dest_region_2].set_source_region(cur_region);
 715       } else if (is_region_aligned(dest_addr)) {
 716         // Data from cur_region will be copied to the start of the destination
 717         // region.
 718         _region_data[dest_region_1].set_source_region(cur_region);
 719       }
 720 
 721       _region_data[cur_region].set_destination_count(destination_count);
 722       dest_addr += words;
 723     }
 724 
 725     ++cur_region;
 726   }
 727 
 728   *target_next = dest_addr;
 729   return true;
 730 }
 731 
 732 HeapWord* ParallelCompactData::calc_new_pointer(HeapWord* addr, ParCompactionManager* cm) const {
 733   assert(addr != nullptr, "Should detect null oop earlier");
 734   assert(ParallelScavengeHeap::heap()->is_in(addr), "not in heap");
 735   assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "not marked");
 736 
 737   // Region covering the object.
 738   RegionData* const region_ptr = addr_to_region_ptr(addr);
 739   HeapWord* result = region_ptr->destination();
 740 
 741   // If the entire Region is live, the new location is region->destination + the
 742   // offset of the object within in the Region.
 743 
 744   // Run some performance tests to determine if this special case pays off.  It
 745   // is worth it for pointers into the dense prefix.  If the optimization to
 746   // avoid pointer updates in regions that only point to the dense prefix is
 747   // ever implemented, this should be revisited.
 748   if (region_ptr->data_size() == RegionSize) {
 749     result += region_offset(addr);
 750     return result;
 751   }
 752 
 753   // Otherwise, the new location is region->destination + block offset + the
 754   // number of live words in the Block that are (a) to the left of addr and (b)
 755   // due to objects that start in the Block.
 756 
 757   // Fill in the block table if necessary.  This is unsynchronized, so multiple
 758   // threads may fill the block table for a region (harmless, since it is
 759   // idempotent).
 760   if (!region_ptr->blocks_filled()) {
 761     PSParallelCompact::fill_blocks(addr_to_region_idx(addr));
 762     region_ptr->set_blocks_filled();
 763   }
 764 
 765   HeapWord* const search_start = block_align_down(addr);
 766   const size_t block_offset = addr_to_block_ptr(addr)->offset();
 767 
 768   const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();
 769   const size_t live = bitmap->live_words_in_range(cm, search_start, cast_to_oop(addr));
 770   result += block_offset + live;
 771   DEBUG_ONLY(PSParallelCompact::check_new_location(addr, result));
 772   return result;
 773 }
 774 
 775 #ifdef ASSERT
 776 void ParallelCompactData::verify_clear(const PSVirtualSpace* vspace)
 777 {
 778   const size_t* const beg = (const size_t*)vspace->committed_low_addr();
 779   const size_t* const end = (const size_t*)vspace->committed_high_addr();
 780   for (const size_t* p = beg; p < end; ++p) {
 781     assert(*p == 0, "not zero");
 782   }
 783 }
 784 
 785 void ParallelCompactData::verify_clear()
 786 {
 787   verify_clear(_region_vspace);
 788   verify_clear(_block_vspace);
 789 }
 790 #endif  // #ifdef ASSERT
 791 
 792 STWGCTimer          PSParallelCompact::_gc_timer;
 793 ParallelOldTracer   PSParallelCompact::_gc_tracer;
 794 elapsedTimer        PSParallelCompact::_accumulated_time;
 795 unsigned int        PSParallelCompact::_maximum_compaction_gc_num = 0;
 796 CollectorCounters*  PSParallelCompact::_counters = nullptr;
 797 ParMarkBitMap       PSParallelCompact::_mark_bitmap;
 798 ParallelCompactData PSParallelCompact::_summary_data;
 799 
 800 PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
 801 
 802 bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
 803 
 804 void PSParallelCompact::post_initialize() {
 805   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 806   _span_based_discoverer.set_span(heap->reserved_region());
 807   _ref_processor =
 808     new ReferenceProcessor(&_span_based_discoverer,
 809                            ParallelGCThreads,   // mt processing degree
 810                            ParallelGCThreads,   // mt discovery degree
 811                            false,               // concurrent_discovery
 812                            &_is_alive_closure); // non-header is alive closure
 813 
 814   _counters = new CollectorCounters("Parallel full collection pauses", 1);
 815 
 816   // Initialize static fields in ParCompactionManager.
 817   ParCompactionManager::initialize(mark_bitmap());
 818 }
 819 
 820 bool PSParallelCompact::initialize_aux_data() {
 821   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 822   MemRegion mr = heap->reserved_region();
 823   assert(mr.byte_size() != 0, "heap should be reserved");
 824 
 825   initialize_space_info();
 826 
 827   if (!_mark_bitmap.initialize(mr)) {
 828     vm_shutdown_during_initialization(
 829       err_msg("Unable to allocate " SIZE_FORMAT "KB bitmaps for parallel "
 830       "garbage collection for the requested " SIZE_FORMAT "KB heap.",
 831       _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
 832     return false;
 833   }
 834 
 835   if (!_summary_data.initialize(mr)) {
 836     vm_shutdown_during_initialization(
 837       err_msg("Unable to allocate " SIZE_FORMAT "KB card tables for parallel "
 838       "garbage collection for the requested " SIZE_FORMAT "KB heap.",
 839       _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
 840     return false;
 841   }
 842 
 843   return true;
 844 }
 845 
 846 void PSParallelCompact::initialize_space_info()
 847 {
 848   memset(&_space_info, 0, sizeof(_space_info));
 849 
 850   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 851   PSYoungGen* young_gen = heap->young_gen();
 852 
 853   _space_info[old_space_id].set_space(heap->old_gen()->object_space());
 854   _space_info[eden_space_id].set_space(young_gen->eden_space());
 855   _space_info[from_space_id].set_space(young_gen->from_space());
 856   _space_info[to_space_id].set_space(young_gen->to_space());
 857 
 858   _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
 859 }
 860 
 861 void
 862 PSParallelCompact::clear_data_covering_space(SpaceId id)
 863 {
 864   // At this point, top is the value before GC, new_top() is the value that will
 865   // be set at the end of GC.  The marking bitmap is cleared to top; nothing
 866   // should be marked above top.  The summary data is cleared to the larger of
 867   // top & new_top.
 868   MutableSpace* const space = _space_info[id].space();
 869   HeapWord* const bot = space->bottom();
 870   HeapWord* const top = space->top();
 871   HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
 872 
 873   const idx_t beg_bit = _mark_bitmap.addr_to_bit(bot);
 874   const idx_t end_bit = _mark_bitmap.addr_to_bit(top);
 875   _mark_bitmap.clear_range(beg_bit, end_bit);
 876 
 877   const size_t beg_region = _summary_data.addr_to_region_idx(bot);
 878   const size_t end_region =
 879     _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
 880   _summary_data.clear_range(beg_region, end_region);
 881 
 882   // Clear the data used to 'split' regions.
 883   SplitInfo& split_info = _space_info[id].split_info();
 884   if (split_info.is_valid()) {
 885     split_info.clear();
 886   }
 887   DEBUG_ONLY(split_info.verify_clear();)
 888 }
 889 
 890 void PSParallelCompact::pre_compact()
 891 {
 892   // Update the from & to space pointers in space_info, since they are swapped
 893   // at each young gen gc.  Do the update unconditionally (even though a
 894   // promotion failure does not swap spaces) because an unknown number of young
 895   // collections will have swapped the spaces an unknown number of times.
 896   GCTraceTime(Debug, gc, phases) tm("Pre Compact", &_gc_timer);
 897   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 898   _space_info[from_space_id].set_space(heap->young_gen()->from_space());
 899   _space_info[to_space_id].set_space(heap->young_gen()->to_space());
 900 
 901   // Increment the invocation count
 902   heap->increment_total_collections(true);
 903 
 904   CodeCache::on_gc_marking_cycle_start();
 905 
 906   heap->print_heap_before_gc();
 907   heap->trace_heap_before_gc(&_gc_tracer);
 908 
 909   // Fill in TLABs
 910   heap->ensure_parsability(true);  // retire TLABs
 911 
 912   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 913     Universe::verify("Before GC");
 914   }
 915 
 916   DEBUG_ONLY(mark_bitmap()->verify_clear();)
 917   DEBUG_ONLY(summary_data().verify_clear();)
 918 
 919   ParCompactionManager::reset_all_bitmap_query_caches();
 920 }
 921 
 922 void PSParallelCompact::post_compact()
 923 {
 924   GCTraceTime(Info, gc, phases) tm("Post Compact", &_gc_timer);
 925   ParCompactionManager::remove_all_shadow_regions();
 926 
 927   CodeCache::on_gc_marking_cycle_finish();
 928   CodeCache::arm_all_nmethods();
 929 
 930   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
 931     // Clear the marking bitmap, summary data and split info.
 932     clear_data_covering_space(SpaceId(id));
 933     // Update top().  Must be done after clearing the bitmap and summary data.
 934     _space_info[id].publish_new_top();
 935   }
 936 
 937   ParCompactionManager::flush_all_string_dedup_requests();
 938 
 939   MutableSpace* const eden_space = _space_info[eden_space_id].space();
 940   MutableSpace* const from_space = _space_info[from_space_id].space();
 941   MutableSpace* const to_space   = _space_info[to_space_id].space();
 942 
 943   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 944   bool eden_empty = eden_space->is_empty();
 945 
 946   // Update heap occupancy information which is used as input to the soft ref
 947   // clearing policy at the next gc.
 948   Universe::heap()->update_capacity_and_used_at_gc();
 949 
 950   bool young_gen_empty = eden_empty && from_space->is_empty() &&
 951     to_space->is_empty();
 952 
 953   PSCardTable* ct = heap->card_table();
 954   MemRegion old_mr = heap->old_gen()->committed();
 955   if (young_gen_empty) {
 956     ct->clear_MemRegion(old_mr);
 957   } else {
 958     ct->dirty_MemRegion(old_mr);
 959   }
 960 
 961   {
 962     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 963     GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", gc_timer());
 964     ClassLoaderDataGraph::purge(true /* at_safepoint */);
 965     DEBUG_ONLY(MetaspaceUtils::verify();)
 966   }
 967 
 968   // Need to clear claim bits for the next mark.
 969   ClassLoaderDataGraph::clear_claimed_marks();
 970 
 971   heap->prune_scavengable_nmethods();
 972 
 973 #if COMPILER2_OR_JVMCI
 974   DerivedPointerTable::update_pointers();
 975 #endif
 976 
 977   if (ZapUnusedHeapArea) {
 978     heap->gen_mangle_unused_area();
 979   }
 980 
 981   // Signal that we have completed a visit to all live objects.
 982   Universe::heap()->record_whole_heap_examined_timestamp();
 983 }
 984 
 985 ParallelCompactData::RegionData*
 986 PSParallelCompact::first_dead_space_region(const RegionData* beg,
 987                                            const RegionData* end)
 988 {
 989   const size_t region_size = ParallelCompactData::RegionSize;
 990   ParallelCompactData& sd = summary_data();
 991   size_t left = sd.region(beg);
 992   size_t right = end > beg ? sd.region(end) - 1 : left;
 993 
 994   // Binary search.
 995   while (left < right) {
 996     // Equivalent to (left + right) / 2, but does not overflow.
 997     const size_t middle = left + (right - left) / 2;
 998     RegionData* const middle_ptr = sd.region(middle);
 999     HeapWord* const dest = middle_ptr->destination();
1000     HeapWord* const addr = sd.region_to_addr(middle);
1001     assert(dest != nullptr, "sanity");
1002     assert(dest <= addr, "must move left");
1003 
1004     if (middle > left && dest < addr) {
1005       right = middle - 1;
1006     } else if (middle < right && middle_ptr->data_size() == region_size) {
1007       left = middle + 1;
1008     } else {
1009       return middle_ptr;
1010     }
1011   }
1012   return sd.region(left);
1013 }
1014 
1015 // Return the address of the end of the dense prefix, a.k.a. the start of the
1016 // compacted region.  The address is always on a region boundary.
1017 //
1018 // Completely full regions at the left are skipped, since no compaction can
1019 // occur in those regions.  Then the maximum amount of dead wood to allow is
1020 // computed, based on the density (amount live / capacity) of the generation;
1021 // the region with approximately that amount of dead space to the left is
1022 // identified as the limit region.  Regions between the last completely full
1023 // region and the limit region are scanned and the one that has the best
1024 // (maximum) reclaimed_ratio() is selected.
1025 HeapWord*
1026 PSParallelCompact::compute_dense_prefix(const SpaceId id,
1027                                         bool maximum_compaction)
1028 {
1029   const size_t region_size = ParallelCompactData::RegionSize;
1030   const ParallelCompactData& sd = summary_data();
1031 
1032   const MutableSpace* const space = _space_info[id].space();
1033   HeapWord* const top = space->top();
1034   HeapWord* const top_aligned_up = sd.region_align_up(top);
1035   HeapWord* const new_top = _space_info[id].new_top();
1036   HeapWord* const new_top_aligned_up = sd.region_align_up(new_top);
1037   HeapWord* const bottom = space->bottom();
1038   const RegionData* const beg_cp = sd.addr_to_region_ptr(bottom);
1039   const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
1040   const RegionData* const new_top_cp =
1041     sd.addr_to_region_ptr(new_top_aligned_up);
1042 
1043   // Skip full regions at the beginning of the space--they are necessarily part
1044   // of the dense prefix.
1045   const RegionData* const full_cp = first_dead_space_region(beg_cp, new_top_cp);
1046   assert(full_cp->destination() == sd.region_to_addr(full_cp) ||
1047          space->is_empty(), "no dead space allowed to the left");
1048   assert(full_cp->data_size() < region_size || full_cp == new_top_cp - 1,
1049          "region must have dead space");
1050 
1051   // The gc number is saved whenever a maximum compaction is done, and used to
1052   // determine when the maximum compaction interval has expired.  This avoids
1053   // successive max compactions for different reasons.
1054   const uint total_invocations = ParallelScavengeHeap::heap()->total_full_collections();
1055   assert(total_invocations >= _maximum_compaction_gc_num, "sanity");
1056   const size_t gcs_since_max = total_invocations - _maximum_compaction_gc_num;
1057   const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval ||
1058     total_invocations == HeapFirstMaximumCompactionCount;
1059   if (maximum_compaction || full_cp == top_cp || interval_ended) {
1060     _maximum_compaction_gc_num = total_invocations;
1061     return sd.region_to_addr(full_cp);
1062   }
1063 
1064   // Iteration starts with the region *after* the full-region-prefix-end.
1065   const RegionData* const start_region = full_cp;
1066   // If final region is not full, iteration stops before that region,
1067   // because fill_dense_prefix_end assumes that prefix_end <= top.
1068   const RegionData* const end_region = sd.addr_to_region_ptr(space->top());
1069   assert(start_region <= end_region, "inv");
1070 
1071   size_t max_waste = space->capacity_in_words() * (MarkSweepDeadRatio / 100.0);
1072   const RegionData* cur_region = start_region;
1073   for (/* empty */; cur_region < end_region; ++cur_region) {
1074     assert(region_size >= cur_region->data_size(), "inv");
1075     size_t dead_size = region_size - cur_region->data_size();
1076     if (max_waste < dead_size) {
1077       break;
1078     }
1079     max_waste -= dead_size;
1080   }
1081 
1082   HeapWord* const prefix_end = sd.region_to_addr(cur_region);
1083   assert(sd.is_region_aligned(prefix_end), "postcondition");
1084   assert(prefix_end >= sd.region_to_addr(full_cp), "in-range");
1085   assert(prefix_end <= space->top(), "in-range");
1086   return prefix_end;
1087 }
1088 
1089 void PSParallelCompact::summarize_spaces_quick()
1090 {
1091   for (unsigned int i = 0; i < last_space_id; ++i) {
1092     const MutableSpace* space = _space_info[i].space();
1093     HeapWord** nta = _space_info[i].new_top_addr();
1094     bool result = _summary_data.summarize(_space_info[i].split_info(),
1095                                           space->bottom(), space->top(), nullptr,
1096                                           space->bottom(), space->end(), nta);
1097     assert(result, "space must fit into itself");
1098     _space_info[i].set_dense_prefix(space->bottom());
1099   }
1100 }
1101 
1102 void PSParallelCompact::fill_dense_prefix_end(SpaceId id) {
1103   // Comparing two sizes to decide if filling is required:
1104   //
1105   // The size of the filler (min-obj-size) is 2 heap words with the default
1106   // MinObjAlignment, since both markword and klass take 1 heap word.
1107   //
1108   // The size of the gap (if any) right before dense-prefix-end is
1109   // MinObjAlignment.
1110   //
1111   // Need to fill in the gap only if it's smaller than min-obj-size, and the
1112   // filler obj will extend to next region.
1113 
1114   // Note: If min-fill-size decreases to 1, this whole method becomes redundant.
1115   assert(CollectedHeap::min_fill_size() >= 2, "inv");
1116 #ifndef _LP64
1117   // In 32-bit system, each heap word is 4 bytes, so MinObjAlignment == 2.
1118   // The gap is always equal to min-fill-size, so nothing to do.
1119   return;
1120 #endif
1121   if (MinObjAlignment > 1) {
1122     return;
1123   }
1124   assert(CollectedHeap::min_fill_size() == 2, "inv");
1125   HeapWord* const dense_prefix_end = dense_prefix(id);
1126   RegionData* const region_after_dense_prefix = _summary_data.addr_to_region_ptr(dense_prefix_end);
1127   idx_t const dense_prefix_bit = _mark_bitmap.addr_to_bit(dense_prefix_end);
1128 
1129   if (region_after_dense_prefix->partial_obj_size() != 0 ||
1130       _mark_bitmap.is_obj_beg(dense_prefix_bit)) {
1131     // The region after the dense prefix starts with live bytes.
1132     return;
1133   }
1134 
1135   if (_mark_bitmap.is_obj_end(dense_prefix_bit - 2)) {
1136     // There is exactly one heap word gap right before the dense prefix end, so we need a filler object.
1137     // The filler object will extend into the region after the last dense prefix region.
1138     const size_t obj_len = 2; // min-fill-size
1139     HeapWord* const obj_beg = dense_prefix_end - 1;
1140     CollectedHeap::fill_with_object(obj_beg, obj_len);
1141     _mark_bitmap.mark_obj(obj_beg, obj_len);
1142     _summary_data.addr_to_region_ptr(obj_beg)->add_live_obj(1);
1143     region_after_dense_prefix->set_partial_obj_size(1);
1144     region_after_dense_prefix->set_partial_obj_addr(obj_beg);
1145     assert(start_array(id) != nullptr, "sanity");
1146     start_array(id)->update_for_block(obj_beg, obj_beg + obj_len);
1147   }
1148 }
1149 
1150 void
1151 PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction)
1152 {
1153   assert(id < last_space_id, "id out of range");
1154   assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom(),
1155          "should have been reset in summarize_spaces_quick()");
1156 
1157   const MutableSpace* space = _space_info[id].space();
1158   if (_space_info[id].new_top() != space->bottom()) {
1159     HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction);
1160     _space_info[id].set_dense_prefix(dense_prefix_end);
1161 
1162     // Recompute the summary data, taking into account the dense prefix.  If
1163     // every last byte will be reclaimed, then the existing summary data which
1164     // compacts everything can be left in place.
1165     if (!maximum_compaction && dense_prefix_end != space->bottom()) {
1166       // If dead space crosses the dense prefix boundary, it is (at least
1167       // partially) filled with a dummy object, marked live and added to the
1168       // summary data.  This simplifies the copy/update phase and must be done
1169       // before the final locations of objects are determined, to prevent
1170       // leaving a fragment of dead space that is too small to fill.
1171       fill_dense_prefix_end(id);
1172 
1173       // Compute the destination of each Region, and thus each object.
1174       _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end);
1175       _summary_data.summarize(_space_info[id].split_info(),
1176                               dense_prefix_end, space->top(), nullptr,
1177                               dense_prefix_end, space->end(),
1178                               _space_info[id].new_top_addr());
1179     }
1180   }
1181 
1182   if (log_develop_is_enabled(Trace, gc, compaction)) {
1183     const size_t region_size = ParallelCompactData::RegionSize;
1184     HeapWord* const dense_prefix_end = _space_info[id].dense_prefix();
1185     const size_t dp_region = _summary_data.addr_to_region_idx(dense_prefix_end);
1186     const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom());
1187     HeapWord* const new_top = _space_info[id].new_top();
1188     const HeapWord* nt_aligned_up = _summary_data.region_align_up(new_top);
1189     const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end);
1190     log_develop_trace(gc, compaction)(
1191         "id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " "
1192         "dp_region=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " "
1193         "cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT,
1194         id, space->capacity_in_words(), p2i(dense_prefix_end),
1195         dp_region, dp_words / region_size,
1196         cr_words / region_size, p2i(new_top));
1197   }
1198 }
1199 
1200 #ifndef PRODUCT
1201 void PSParallelCompact::summary_phase_msg(SpaceId dst_space_id,
1202                                           HeapWord* dst_beg, HeapWord* dst_end,
1203                                           SpaceId src_space_id,
1204                                           HeapWord* src_beg, HeapWord* src_end)
1205 {
1206   log_develop_trace(gc, compaction)(
1207       "Summarizing %d [%s] into %d [%s]:  "
1208       "src=" PTR_FORMAT "-" PTR_FORMAT " "
1209       SIZE_FORMAT "-" SIZE_FORMAT " "
1210       "dst=" PTR_FORMAT "-" PTR_FORMAT " "
1211       SIZE_FORMAT "-" SIZE_FORMAT,
1212       src_space_id, space_names[src_space_id],
1213       dst_space_id, space_names[dst_space_id],
1214       p2i(src_beg), p2i(src_end),
1215       _summary_data.addr_to_region_idx(src_beg),
1216       _summary_data.addr_to_region_idx(src_end),
1217       p2i(dst_beg), p2i(dst_end),
1218       _summary_data.addr_to_region_idx(dst_beg),
1219       _summary_data.addr_to_region_idx(dst_end));
1220 }
1221 #endif  // #ifndef PRODUCT
1222 
1223 void PSParallelCompact::summary_phase(bool maximum_compaction)
1224 {
1225   GCTraceTime(Info, gc, phases) tm("Summary Phase", &_gc_timer);
1226 
1227   // Quick summarization of each space into itself, to see how much is live.
1228   summarize_spaces_quick();
1229 
1230   log_develop_trace(gc, compaction)("summary phase:  after summarizing each space to self");
1231   NOT_PRODUCT(print_region_ranges());
1232   NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1233 
1234   // The amount of live data that will end up in old space (assuming it fits).
1235   size_t old_space_total_live = 0;
1236   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1237     old_space_total_live += pointer_delta(_space_info[id].new_top(),
1238                                           _space_info[id].space()->bottom());
1239   }
1240 
1241   MutableSpace* const old_space = _space_info[old_space_id].space();
1242   const size_t old_capacity = old_space->capacity_in_words();
1243   if (old_space_total_live > old_capacity) {
1244     // XXX - should also try to expand
1245     maximum_compaction = true;
1246   }
1247 
1248   // Old generations.
1249   summarize_space(old_space_id, maximum_compaction);
1250 
1251   // Summarize the remaining spaces in the young gen.  The initial target space
1252   // is the old gen.  If a space does not fit entirely into the target, then the
1253   // remainder is compacted into the space itself and that space becomes the new
1254   // target.
1255   SpaceId dst_space_id = old_space_id;
1256   HeapWord* dst_space_end = old_space->end();
1257   HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
1258   for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
1259     const MutableSpace* space = _space_info[id].space();
1260     const size_t live = pointer_delta(_space_info[id].new_top(),
1261                                       space->bottom());
1262     const size_t available = pointer_delta(dst_space_end, *new_top_addr);
1263 
1264     NOT_PRODUCT(summary_phase_msg(dst_space_id, *new_top_addr, dst_space_end,
1265                                   SpaceId(id), space->bottom(), space->top());)
1266     if (live > 0 && live <= available) {
1267       // All the live data will fit.
1268       bool done = _summary_data.summarize(_space_info[id].split_info(),
1269                                           space->bottom(), space->top(),
1270                                           nullptr,
1271                                           *new_top_addr, dst_space_end,
1272                                           new_top_addr);
1273       assert(done, "space must fit into old gen");
1274 
1275       // Reset the new_top value for the space.
1276       _space_info[id].set_new_top(space->bottom());
1277     } else if (live > 0) {
1278       // Attempt to fit part of the source space into the target space.
1279       HeapWord* next_src_addr = nullptr;
1280       bool done = _summary_data.summarize(_space_info[id].split_info(),
1281                                           space->bottom(), space->top(),
1282                                           &next_src_addr,
1283                                           *new_top_addr, dst_space_end,
1284                                           new_top_addr);
1285       assert(!done, "space should not fit into old gen");
1286       assert(next_src_addr != nullptr, "sanity");
1287 
1288       // The source space becomes the new target, so the remainder is compacted
1289       // within the space itself.
1290       dst_space_id = SpaceId(id);
1291       dst_space_end = space->end();
1292       new_top_addr = _space_info[id].new_top_addr();
1293       NOT_PRODUCT(summary_phase_msg(dst_space_id,
1294                                     space->bottom(), dst_space_end,
1295                                     SpaceId(id), next_src_addr, space->top());)
1296       done = _summary_data.summarize(_space_info[id].split_info(),
1297                                      next_src_addr, space->top(),
1298                                      nullptr,
1299                                      space->bottom(), dst_space_end,
1300                                      new_top_addr);
1301       assert(done, "space must fit when compacted into itself");
1302       assert(*new_top_addr <= space->top(), "usage should not grow");
1303     }
1304   }
1305 
1306   log_develop_trace(gc, compaction)("Summary_phase:  after final summarization");
1307   NOT_PRODUCT(print_region_ranges());
1308   NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1309 }
1310 
1311 // This method should contain all heap-specific policy for invoking a full
1312 // collection.  invoke_no_policy() will only attempt to compact the heap; it
1313 // will do nothing further.  If we need to bail out for policy reasons, scavenge
1314 // before full gc, or any other specialized behavior, it needs to be added here.
1315 //
1316 // Note that this method should only be called from the vm_thread while at a
1317 // safepoint.
1318 //
1319 // Note that the all_soft_refs_clear flag in the soft ref policy
1320 // may be true because this method can be called without intervening
1321 // activity.  For example when the heap space is tight and full measure
1322 // are being taken to free space.
1323 bool PSParallelCompact::invoke(bool maximum_heap_compaction) {
1324   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
1325   assert(Thread::current() == (Thread*)VMThread::vm_thread(),
1326          "should be in vm thread");
1327 
1328   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1329   assert(!heap->is_gc_active(), "not reentrant");
1330 
1331   IsGCActiveMark mark;
1332 
1333   if (ScavengeBeforeFullGC) {
1334     PSScavenge::invoke_no_policy();
1335   }
1336 
1337   const bool clear_all_soft_refs =
1338     heap->soft_ref_policy()->should_clear_all_soft_refs();
1339 
1340   return PSParallelCompact::invoke_no_policy(clear_all_soft_refs ||
1341                                              maximum_heap_compaction);
1342 }
1343 
1344 // This method contains no policy. You should probably
1345 // be calling invoke() instead.
1346 bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
1347   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
1348   assert(ref_processor() != nullptr, "Sanity");
1349 
1350   if (GCLocker::check_active_before_gc()) {
1351     return false;
1352   }
1353 
1354   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1355 
1356   GCIdMark gc_id_mark;
1357   _gc_timer.register_gc_start();
1358   _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
1359 
1360   GCCause::Cause gc_cause = heap->gc_cause();
1361   PSYoungGen* young_gen = heap->young_gen();
1362   PSOldGen* old_gen = heap->old_gen();
1363   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
1364 
1365   // The scope of casr should end after code that can change
1366   // SoftRefPolicy::_should_clear_all_soft_refs.
1367   ClearedAllSoftRefs casr(maximum_heap_compaction,
1368                           heap->soft_ref_policy());
1369 
1370   if (ZapUnusedHeapArea) {
1371     // Save information needed to minimize mangling
1372     heap->record_gen_tops_before_GC();
1373   }
1374 
1375   // Make sure data structures are sane, make the heap parsable, and do other
1376   // miscellaneous bookkeeping.
1377   pre_compact();
1378 
1379   const PreGenGCValues pre_gc_values = heap->get_pre_gc_values();
1380 
1381   {
1382     const uint active_workers =
1383       WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().max_workers(),
1384                                         ParallelScavengeHeap::heap()->workers().active_workers(),
1385                                         Threads::number_of_non_daemon_threads());
1386     ParallelScavengeHeap::heap()->workers().set_active_workers(active_workers);
1387 
1388     GCTraceCPUTime tcpu(&_gc_tracer);
1389     GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause, true);
1390 
1391     heap->pre_full_gc_dump(&_gc_timer);
1392 
1393     TraceCollectorStats tcs(counters());
1394     TraceMemoryManagerStats tms(heap->old_gc_manager(), gc_cause, "end of major GC");
1395 
1396     if (log_is_enabled(Debug, gc, heap, exit)) {
1397       accumulated_time()->start();
1398     }
1399 
1400     // Let the size policy know we're starting
1401     size_policy->major_collection_begin();
1402 
1403 #if COMPILER2_OR_JVMCI
1404     DerivedPointerTable::clear();
1405 #endif
1406 
1407     ref_processor()->start_discovery(maximum_heap_compaction);
1408 
1409     ClassUnloadingContext ctx(1 /* num_nmethod_unlink_workers */,
1410                               false /* unregister_nmethods_during_purge */,
1411                               false /* lock_nmethod_free_separately */);
1412 
1413     marking_phase(&_gc_tracer);
1414 
1415     bool max_on_system_gc = UseMaximumCompactionOnSystemGC
1416       && GCCause::is_user_requested_gc(gc_cause);
1417     summary_phase(maximum_heap_compaction || max_on_system_gc);
1418 
1419 #if COMPILER2_OR_JVMCI
1420     assert(DerivedPointerTable::is_active(), "Sanity");
1421     DerivedPointerTable::set_active(false);
1422 #endif
1423 
1424     // adjust_roots() updates Universe::_intArrayKlass which is
1425     // needed by the compaction for filling holes in the dense prefix.
1426     adjust_roots();
1427 
1428     compact();
1429 
1430     ParCompactionManager::verify_all_region_stack_empty();
1431 
1432     // Reset the mark bitmap, summary data, and do other bookkeeping.  Must be
1433     // done before resizing.
1434     post_compact();
1435 
1436     // Let the size policy know we're done
1437     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
1438 
1439     if (UseAdaptiveSizePolicy) {
1440       log_debug(gc, ergo)("AdaptiveSizeStart: collection: %d ", heap->total_collections());
1441       log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT,
1442                           old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
1443 
1444       // Don't check if the size_policy is ready here.  Let
1445       // the size_policy check that internally.
1446       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
1447           AdaptiveSizePolicy::should_update_promo_stats(gc_cause)) {
1448         // Swap the survivor spaces if from_space is empty. The
1449         // resize_young_gen() called below is normally used after
1450         // a successful young GC and swapping of survivor spaces;
1451         // otherwise, it will fail to resize the young gen with
1452         // the current implementation.
1453         if (young_gen->from_space()->is_empty()) {
1454           young_gen->from_space()->clear(SpaceDecorator::Mangle);
1455           young_gen->swap_spaces();
1456         }
1457 
1458         // Calculate optimal free space amounts
1459         assert(young_gen->max_gen_size() >
1460           young_gen->from_space()->capacity_in_bytes() +
1461           young_gen->to_space()->capacity_in_bytes(),
1462           "Sizes of space in young gen are out-of-bounds");
1463 
1464         size_t young_live = young_gen->used_in_bytes();
1465         size_t eden_live = young_gen->eden_space()->used_in_bytes();
1466         size_t old_live = old_gen->used_in_bytes();
1467         size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
1468         size_t max_old_gen_size = old_gen->max_gen_size();
1469         size_t max_eden_size = young_gen->max_gen_size() -
1470           young_gen->from_space()->capacity_in_bytes() -
1471           young_gen->to_space()->capacity_in_bytes();
1472 
1473         // Used for diagnostics
1474         size_policy->clear_generation_free_space_flags();
1475 
1476         size_policy->compute_generations_free_space(young_live,
1477                                                     eden_live,
1478                                                     old_live,
1479                                                     cur_eden,
1480                                                     max_old_gen_size,
1481                                                     max_eden_size,
1482                                                     true /* full gc*/);
1483 
1484         size_policy->check_gc_overhead_limit(eden_live,
1485                                              max_old_gen_size,
1486                                              max_eden_size,
1487                                              true /* full gc*/,
1488                                              gc_cause,
1489                                              heap->soft_ref_policy());
1490 
1491         size_policy->decay_supplemental_growth(true /* full gc*/);
1492 
1493         heap->resize_old_gen(
1494           size_policy->calculated_old_free_size_in_bytes());
1495 
1496         heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
1497                                size_policy->calculated_survivor_size_in_bytes());
1498       }
1499 
1500       log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections());
1501     }
1502 
1503     if (UsePerfData) {
1504       PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();
1505       counters->update_counters();
1506       counters->update_old_capacity(old_gen->capacity_in_bytes());
1507       counters->update_young_capacity(young_gen->capacity_in_bytes());
1508     }
1509 
1510     heap->resize_all_tlabs();
1511 
1512     // Resize the metaspace capacity after a collection
1513     MetaspaceGC::compute_new_size();
1514 
1515     if (log_is_enabled(Debug, gc, heap, exit)) {
1516       accumulated_time()->stop();
1517     }
1518 
1519     heap->print_heap_change(pre_gc_values);
1520 
1521     // Track memory usage and detect low memory
1522     MemoryService::track_memory_usage();
1523     heap->update_counters();
1524 
1525     heap->post_full_gc_dump(&_gc_timer);
1526   }
1527 
1528   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
1529     Universe::verify("After GC");
1530   }
1531 
1532   if (ZapUnusedHeapArea) {
1533     old_gen->object_space()->check_mangled_unused_area_complete();
1534   }
1535 
1536   heap->print_heap_after_gc();
1537   heap->trace_heap_after_gc(&_gc_tracer);
1538 
1539   AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections());
1540 
1541   _gc_timer.register_gc_end();
1542 
1543   _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
1544   _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
1545 
1546   return true;
1547 }
1548 
1549 class PCAddThreadRootsMarkingTaskClosure : public ThreadClosure {
1550 private:
1551   uint _worker_id;
1552 
1553 public:
1554   PCAddThreadRootsMarkingTaskClosure(uint worker_id) : _worker_id(worker_id) { }
1555   void do_thread(Thread* thread) {
1556     assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
1557 
1558     ResourceMark rm;
1559 
1560     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(_worker_id);
1561 
1562     PCMarkAndPushClosure mark_and_push_closure(cm);
1563     MarkingNMethodClosure mark_and_push_in_blobs(&mark_and_push_closure, !NMethodToOopClosure::FixRelocations, true /* keepalive nmethods */);
1564 
1565     thread->oops_do(&mark_and_push_closure, &mark_and_push_in_blobs);
1566 
1567     // Do the real work
1568     cm->follow_marking_stacks();
1569   }
1570 };
1571 
1572 void steal_marking_work(TaskTerminator& terminator, uint worker_id) {
1573   assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
1574 
1575   ParCompactionManager* cm =
1576     ParCompactionManager::gc_thread_compaction_manager(worker_id);
1577 
1578   do {
1579     oop obj = nullptr;
1580     ObjArrayTask task;
1581     if (ParCompactionManager::steal_objarray(worker_id,  task)) {
1582       cm->follow_array((objArrayOop)task.obj(), task.index());
1583     } else if (ParCompactionManager::steal(worker_id, obj)) {
1584       cm->follow_contents(obj);
1585     }
1586     cm->follow_marking_stacks();
1587   } while (!terminator.offer_termination());
1588 }
1589 
1590 class MarkFromRootsTask : public WorkerTask {
1591   StrongRootsScope _strong_roots_scope; // needed for Threads::possibly_parallel_threads_do
1592   OopStorageSetStrongParState<false /* concurrent */, false /* is_const */> _oop_storage_set_par_state;
1593   TaskTerminator _terminator;
1594   uint _active_workers;
1595 
1596 public:
1597   MarkFromRootsTask(uint active_workers) :
1598       WorkerTask("MarkFromRootsTask"),
1599       _strong_roots_scope(active_workers),
1600       _terminator(active_workers, ParCompactionManager::oop_task_queues()),
1601       _active_workers(active_workers) {}
1602 
1603   virtual void work(uint worker_id) {
1604     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1605     cm->create_marking_stats_cache();
1606     PCMarkAndPushClosure mark_and_push_closure(cm);
1607 
1608     {
1609       CLDToOopClosure cld_closure(&mark_and_push_closure, ClassLoaderData::_claim_stw_fullgc_mark);
1610       ClassLoaderDataGraph::always_strong_cld_do(&cld_closure);
1611 
1612       // Do the real work
1613       cm->follow_marking_stacks();
1614     }
1615 
1616     PCAddThreadRootsMarkingTaskClosure closure(worker_id);
1617     Threads::possibly_parallel_threads_do(true /* is_par */, &closure);
1618 
1619     // Mark from OopStorages
1620     {
1621       _oop_storage_set_par_state.oops_do(&mark_and_push_closure);
1622       // Do the real work
1623       cm->follow_marking_stacks();
1624     }
1625 
1626     if (_active_workers > 1) {
1627       steal_marking_work(_terminator, worker_id);
1628     }
1629   }
1630 };
1631 
1632 class ParallelCompactRefProcProxyTask : public RefProcProxyTask {
1633   TaskTerminator _terminator;
1634 
1635 public:
1636   ParallelCompactRefProcProxyTask(uint max_workers)
1637     : RefProcProxyTask("ParallelCompactRefProcProxyTask", max_workers),
1638       _terminator(_max_workers, ParCompactionManager::oop_task_queues()) {}
1639 
1640   void work(uint worker_id) override {
1641     assert(worker_id < _max_workers, "sanity");
1642     ParCompactionManager* cm = (_tm == RefProcThreadModel::Single) ? ParCompactionManager::get_vmthread_cm() : ParCompactionManager::gc_thread_compaction_manager(worker_id);
1643     PCMarkAndPushClosure keep_alive(cm);
1644     BarrierEnqueueDiscoveredFieldClosure enqueue;
1645     ParCompactionManager::FollowStackClosure complete_gc(cm, (_tm == RefProcThreadModel::Single) ? nullptr : &_terminator, worker_id);
1646     _rp_task->rp_work(worker_id, PSParallelCompact::is_alive_closure(), &keep_alive, &enqueue, &complete_gc);
1647   }
1648 
1649   void prepare_run_task_hook() override {
1650     _terminator.reset_for_reuse(_queue_count);
1651   }
1652 };
1653 
1654 static void flush_marking_stats_cache(const uint num_workers) {
1655   for (uint i = 0; i < num_workers; ++i) {
1656     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(i);
1657     cm->flush_and_destroy_marking_stats_cache();
1658   }
1659 }
1660 
1661 void PSParallelCompact::marking_phase(ParallelOldTracer *gc_tracer) {
1662   // Recursively traverse all live objects and mark them
1663   GCTraceTime(Info, gc, phases) tm("Marking Phase", &_gc_timer);
1664 
1665   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
1666 
1667   ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_mark);
1668   {
1669     GCTraceTime(Debug, gc, phases) tm("Par Mark", &_gc_timer);
1670 
1671     MarkFromRootsTask task(active_gc_threads);
1672     ParallelScavengeHeap::heap()->workers().run_task(&task);
1673   }
1674 
1675   // Process reference objects found during marking
1676   {
1677     GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
1678 
1679     ReferenceProcessorStats stats;
1680     ReferenceProcessorPhaseTimes pt(&_gc_timer, ref_processor()->max_num_queues());
1681 
1682     ref_processor()->set_active_mt_degree(active_gc_threads);
1683     ParallelCompactRefProcProxyTask task(ref_processor()->max_num_queues());
1684     stats = ref_processor()->process_discovered_references(task, pt);
1685 
1686     gc_tracer->report_gc_reference_stats(stats);
1687     pt.print_all_references();
1688   }
1689 
1690   {
1691     GCTraceTime(Debug, gc, phases) tm("Flush Marking Stats", &_gc_timer);
1692 
1693     flush_marking_stats_cache(active_gc_threads);
1694   }
1695 
1696   // This is the point where the entire marking should have completed.
1697   ParCompactionManager::verify_all_marking_stack_empty();
1698 
1699   {
1700     GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
1701     WeakProcessor::weak_oops_do(&ParallelScavengeHeap::heap()->workers(),
1702                                 is_alive_closure(),
1703                                 &do_nothing_cl,
1704                                 1);
1705   }
1706 
1707   {
1708     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
1709 
1710     ClassUnloadingContext* ctx = ClassUnloadingContext::context();
1711 
1712     bool unloading_occurred;
1713     {
1714       CodeCache::UnlinkingScope scope(is_alive_closure());
1715 
1716       // Follow system dictionary roots and unload classes.
1717       unloading_occurred = SystemDictionary::do_unloading(&_gc_timer);
1718 
1719       // Unload nmethods.
1720       CodeCache::do_unloading(unloading_occurred);
1721     }
1722 
1723     {
1724       GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", gc_timer());
1725       // Release unloaded nmethod's memory.
1726       ctx->purge_nmethods();
1727     }
1728     {
1729       GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", &_gc_timer);
1730       ParallelScavengeHeap::heap()->prune_unlinked_nmethods();
1731     }
1732     {
1733       GCTraceTime(Debug, gc, phases) t("Free Code Blobs", gc_timer());
1734       ctx->free_nmethods();
1735     }
1736 
1737     // Prune dead klasses from subklass/sibling/implementor lists.
1738     Klass::clean_weak_klass_links(unloading_occurred);
1739 
1740     // Clean JVMCI metadata handles.
1741     JVMCI_ONLY(JVMCI::do_unloading(unloading_occurred));
1742   }
1743 
1744   {
1745     GCTraceTime(Debug, gc, phases) tm("Report Object Count", &_gc_timer);
1746     _gc_tracer.report_object_count_after_gc(is_alive_closure(), &ParallelScavengeHeap::heap()->workers());
1747   }
1748 #if TASKQUEUE_STATS
1749   ParCompactionManager::oop_task_queues()->print_and_reset_taskqueue_stats("Oop Queue");
1750   ParCompactionManager::_objarray_task_queues->print_and_reset_taskqueue_stats("ObjArrayOop Queue");
1751 #endif
1752 }
1753 
1754 class PSAdjustTask final : public WorkerTask {
1755   SubTasksDone                               _sub_tasks;
1756   WeakProcessor::Task                        _weak_proc_task;
1757   OopStorageSetStrongParState<false, false>  _oop_storage_iter;
1758   uint                                       _nworkers;
1759 
1760   enum PSAdjustSubTask {
1761     PSAdjustSubTask_code_cache,
1762 
1763     PSAdjustSubTask_num_elements
1764   };
1765 
1766 public:
1767   PSAdjustTask(uint nworkers) :
1768     WorkerTask("PSAdjust task"),
1769     _sub_tasks(PSAdjustSubTask_num_elements),
1770     _weak_proc_task(nworkers),
1771     _nworkers(nworkers) {
1772 
1773     ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_adjust);
1774     if (nworkers > 1) {
1775       Threads::change_thread_claim_token();
1776     }
1777   }
1778 
1779   ~PSAdjustTask() {
1780     Threads::assert_all_threads_claimed();
1781   }
1782 
1783   void work(uint worker_id) {
1784     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1785     PCAdjustPointerClosure adjust(cm);
1786     {
1787       ResourceMark rm;
1788       Threads::possibly_parallel_oops_do(_nworkers > 1, &adjust, nullptr);
1789     }
1790     _oop_storage_iter.oops_do(&adjust);
1791     {
1792       CLDToOopClosure cld_closure(&adjust, ClassLoaderData::_claim_stw_fullgc_adjust);
1793       ClassLoaderDataGraph::cld_do(&cld_closure);
1794     }
1795     {
1796       AlwaysTrueClosure always_alive;
1797       _weak_proc_task.work(worker_id, &always_alive, &adjust);
1798     }
1799     if (_sub_tasks.try_claim_task(PSAdjustSubTask_code_cache)) {
1800       NMethodToOopClosure adjust_code(&adjust, NMethodToOopClosure::FixRelocations);
1801       CodeCache::nmethods_do(&adjust_code);
1802     }
1803     _sub_tasks.all_tasks_claimed();
1804   }
1805 };
1806 
1807 void PSParallelCompact::adjust_roots() {
1808   // Adjust the pointers to reflect the new locations
1809   GCTraceTime(Info, gc, phases) tm("Adjust Roots", &_gc_timer);
1810   uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
1811   PSAdjustTask task(nworkers);
1812   ParallelScavengeHeap::heap()->workers().run_task(&task);
1813 }
1814 
1815 // Helper class to print 8 region numbers per line and then print the total at the end.
1816 class FillableRegionLogger : public StackObj {
1817 private:
1818   Log(gc, compaction) log;
1819   static const int LineLength = 8;
1820   size_t _regions[LineLength];
1821   int _next_index;
1822   bool _enabled;
1823   size_t _total_regions;
1824 public:
1825   FillableRegionLogger() : _next_index(0), _enabled(log_develop_is_enabled(Trace, gc, compaction)), _total_regions(0) { }
1826   ~FillableRegionLogger() {
1827     log.trace(SIZE_FORMAT " initially fillable regions", _total_regions);
1828   }
1829 
1830   void print_line() {
1831     if (!_enabled || _next_index == 0) {
1832       return;
1833     }
1834     FormatBuffer<> line("Fillable: ");
1835     for (int i = 0; i < _next_index; i++) {
1836       line.append(" " SIZE_FORMAT_W(7), _regions[i]);
1837     }
1838     log.trace("%s", line.buffer());
1839     _next_index = 0;
1840   }
1841 
1842   void handle(size_t region) {
1843     if (!_enabled) {
1844       return;
1845     }
1846     _regions[_next_index++] = region;
1847     if (_next_index == LineLength) {
1848       print_line();
1849     }
1850     _total_regions++;
1851   }
1852 };
1853 
1854 void PSParallelCompact::prepare_region_draining_tasks(uint parallel_gc_threads)
1855 {
1856   GCTraceTime(Trace, gc, phases) tm("Drain Task Setup", &_gc_timer);
1857 
1858   // Find the threads that are active
1859   uint worker_id = 0;
1860 
1861   // Find all regions that are available (can be filled immediately) and
1862   // distribute them to the thread stacks.  The iteration is done in reverse
1863   // order (high to low) so the regions will be removed in ascending order.
1864 
1865   const ParallelCompactData& sd = PSParallelCompact::summary_data();
1866 
1867   // id + 1 is used to test termination so unsigned  can
1868   // be used with an old_space_id == 0.
1869   FillableRegionLogger region_logger;
1870   for (unsigned int id = to_space_id; id + 1 > old_space_id; --id) {
1871     SpaceInfo* const space_info = _space_info + id;
1872     HeapWord* const new_top = space_info->new_top();
1873 
1874     const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
1875     const size_t end_region =
1876       sd.addr_to_region_idx(sd.region_align_up(new_top));
1877 
1878     for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
1879       if (sd.region(cur)->claim_unsafe()) {
1880         ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1881         bool result = sd.region(cur)->mark_normal();
1882         assert(result, "Must succeed at this point.");
1883         cm->region_stack()->push(cur);
1884         region_logger.handle(cur);
1885         // Assign regions to tasks in round-robin fashion.
1886         if (++worker_id == parallel_gc_threads) {
1887           worker_id = 0;
1888         }
1889       }
1890     }
1891     region_logger.print_line();
1892   }
1893 }
1894 
1895 class TaskQueue : StackObj {
1896   volatile uint _counter;
1897   uint _size;
1898   uint _insert_index;
1899   PSParallelCompact::UpdateDensePrefixTask* _backing_array;
1900 public:
1901   explicit TaskQueue(uint size) : _counter(0), _size(size), _insert_index(0), _backing_array(nullptr) {
1902     _backing_array = NEW_C_HEAP_ARRAY(PSParallelCompact::UpdateDensePrefixTask, _size, mtGC);
1903   }
1904   ~TaskQueue() {
1905     assert(_counter >= _insert_index, "not all queue elements were claimed");
1906     FREE_C_HEAP_ARRAY(T, _backing_array);
1907   }
1908 
1909   void push(const PSParallelCompact::UpdateDensePrefixTask& value) {
1910     assert(_insert_index < _size, "too small backing array");
1911     _backing_array[_insert_index++] = value;
1912   }
1913 
1914   bool try_claim(PSParallelCompact::UpdateDensePrefixTask& reference) {
1915     uint claimed = Atomic::fetch_then_add(&_counter, 1u);
1916     if (claimed < _insert_index) {
1917       reference = _backing_array[claimed];
1918       return true;
1919     } else {
1920       return false;
1921     }
1922   }
1923 };
1924 
1925 #define PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING 4
1926 
1927 void PSParallelCompact::enqueue_dense_prefix_tasks(TaskQueue& task_queue,
1928                                                    uint parallel_gc_threads) {
1929   GCTraceTime(Trace, gc, phases) tm("Dense Prefix Task Setup", &_gc_timer);
1930 
1931   ParallelCompactData& sd = PSParallelCompact::summary_data();
1932 
1933   // Iterate over all the spaces adding tasks for updating
1934   // regions in the dense prefix.  Assume that 1 gc thread
1935   // will work on opening the gaps and the remaining gc threads
1936   // will work on the dense prefix.
1937   unsigned int space_id;
1938   for (space_id = old_space_id; space_id < last_space_id; ++ space_id) {
1939     HeapWord* const dense_prefix_end = _space_info[space_id].dense_prefix();
1940     const MutableSpace* const space = _space_info[space_id].space();
1941 
1942     if (dense_prefix_end == space->bottom()) {
1943       // There is no dense prefix for this space.
1944       continue;
1945     }
1946 
1947     // The dense prefix is before this region.
1948     size_t region_index_end_dense_prefix =
1949         sd.addr_to_region_idx(dense_prefix_end);
1950     RegionData* const dense_prefix_cp =
1951       sd.region(region_index_end_dense_prefix);
1952     assert(dense_prefix_end == space->end() ||
1953            dense_prefix_cp->available() ||
1954            dense_prefix_cp->claimed(),
1955            "The region after the dense prefix should always be ready to fill");
1956 
1957     size_t region_index_start = sd.addr_to_region_idx(space->bottom());
1958 
1959     // Is there dense prefix work?
1960     size_t total_dense_prefix_regions =
1961       region_index_end_dense_prefix - region_index_start;
1962     // How many regions of the dense prefix should be given to
1963     // each thread?
1964     if (total_dense_prefix_regions > 0) {
1965       uint tasks_for_dense_prefix = 1;
1966       if (total_dense_prefix_regions <=
1967           (parallel_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)) {
1968         // Don't over partition.  This assumes that
1969         // PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING is a small integer value
1970         // so there are not many regions to process.
1971         tasks_for_dense_prefix = parallel_gc_threads;
1972       } else {
1973         // Over partition
1974         tasks_for_dense_prefix = parallel_gc_threads *
1975           PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING;
1976       }
1977       size_t regions_per_thread = total_dense_prefix_regions /
1978         tasks_for_dense_prefix;
1979       // Give each thread at least 1 region.
1980       if (regions_per_thread == 0) {
1981         regions_per_thread = 1;
1982       }
1983 
1984       for (uint k = 0; k < tasks_for_dense_prefix; k++) {
1985         if (region_index_start >= region_index_end_dense_prefix) {
1986           break;
1987         }
1988         // region_index_end is not processed
1989         size_t region_index_end = MIN2(region_index_start + regions_per_thread,
1990                                        region_index_end_dense_prefix);
1991         task_queue.push(UpdateDensePrefixTask(SpaceId(space_id),
1992                                               region_index_start,
1993                                               region_index_end));
1994         region_index_start = region_index_end;
1995       }
1996     }
1997     // This gets any part of the dense prefix that did not
1998     // fit evenly.
1999     if (region_index_start < region_index_end_dense_prefix) {
2000       task_queue.push(UpdateDensePrefixTask(SpaceId(space_id),
2001                                             region_index_start,
2002                                             region_index_end_dense_prefix));
2003     }
2004   }
2005 }
2006 
2007 #ifdef ASSERT
2008 // Write a histogram of the number of times the block table was filled for a
2009 // region.
2010 void PSParallelCompact::write_block_fill_histogram()
2011 {
2012   if (!log_develop_is_enabled(Trace, gc, compaction)) {
2013     return;
2014   }
2015 
2016   Log(gc, compaction) log;
2017   ResourceMark rm;
2018   LogStream ls(log.trace());
2019   outputStream* out = &ls;
2020 
2021   typedef ParallelCompactData::RegionData rd_t;
2022   ParallelCompactData& sd = summary_data();
2023 
2024   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2025     MutableSpace* const spc = _space_info[id].space();
2026     if (spc->bottom() != spc->top()) {
2027       const rd_t* const beg = sd.addr_to_region_ptr(spc->bottom());
2028       HeapWord* const top_aligned_up = sd.region_align_up(spc->top());
2029       const rd_t* const end = sd.addr_to_region_ptr(top_aligned_up);
2030 
2031       size_t histo[5] = { 0, 0, 0, 0, 0 };
2032       const size_t histo_len = sizeof(histo) / sizeof(size_t);
2033       const size_t region_cnt = pointer_delta(end, beg, sizeof(rd_t));
2034 
2035       for (const rd_t* cur = beg; cur < end; ++cur) {
2036         ++histo[MIN2(cur->blocks_filled_count(), histo_len - 1)];
2037       }
2038       out->print("Block fill histogram: %u %-4s" SIZE_FORMAT_W(5), id, space_names[id], region_cnt);
2039       for (size_t i = 0; i < histo_len; ++i) {
2040         out->print(" " SIZE_FORMAT_W(5) " %5.1f%%",
2041                    histo[i], 100.0 * histo[i] / region_cnt);
2042       }
2043       out->cr();
2044     }
2045   }
2046 }
2047 #endif // #ifdef ASSERT
2048 
2049 static void compaction_with_stealing_work(TaskTerminator* terminator, uint worker_id) {
2050   assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
2051 
2052   ParCompactionManager* cm =
2053     ParCompactionManager::gc_thread_compaction_manager(worker_id);
2054 
2055   // Drain the stacks that have been preloaded with regions
2056   // that are ready to fill.
2057 
2058   cm->drain_region_stacks();
2059 
2060   guarantee(cm->region_stack()->is_empty(), "Not empty");
2061 
2062   size_t region_index = 0;
2063 
2064   while (true) {
2065     if (ParCompactionManager::steal(worker_id, region_index)) {
2066       PSParallelCompact::fill_and_update_region(cm, region_index);
2067       cm->drain_region_stacks();
2068     } else if (PSParallelCompact::steal_unavailable_region(cm, region_index)) {
2069       // Fill and update an unavailable region with the help of a shadow region
2070       PSParallelCompact::fill_and_update_shadow_region(cm, region_index);
2071       cm->drain_region_stacks();
2072     } else {
2073       if (terminator->offer_termination()) {
2074         break;
2075       }
2076       // Go around again.
2077     }
2078   }
2079 }
2080 
2081 class UpdateDensePrefixAndCompactionTask: public WorkerTask {
2082   TaskQueue& _tq;
2083   TaskTerminator _terminator;
2084 
2085 public:
2086   UpdateDensePrefixAndCompactionTask(TaskQueue& tq, uint active_workers) :
2087       WorkerTask("UpdateDensePrefixAndCompactionTask"),
2088       _tq(tq),
2089       _terminator(active_workers, ParCompactionManager::region_task_queues()) {
2090   }
2091   virtual void work(uint worker_id) {
2092     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
2093 
2094     for (PSParallelCompact::UpdateDensePrefixTask task; _tq.try_claim(task); /* empty */) {
2095       PSParallelCompact::update_and_deadwood_in_dense_prefix(cm,
2096                                                              task._space_id,
2097                                                              task._region_index_start,
2098                                                              task._region_index_end);
2099     }
2100 
2101     // Once a thread has drained it's stack, it should try to steal regions from
2102     // other threads.
2103     compaction_with_stealing_work(&_terminator, worker_id);
2104 
2105     // At this point all regions have been compacted, so it's now safe
2106     // to update the deferred objects that cross region boundaries.
2107     cm->drain_deferred_objects();
2108   }
2109 };
2110 
2111 void PSParallelCompact::compact() {
2112   GCTraceTime(Info, gc, phases) tm("Compaction Phase", &_gc_timer);
2113 
2114   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
2115   PSOldGen* old_gen = heap->old_gen();
2116   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2117 
2118   // for [0..last_space_id)
2119   //     for [0..active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)
2120   //         push
2121   //     push
2122   //
2123   // max push count is thus: last_space_id * (active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING + 1)
2124   TaskQueue task_queue(last_space_id * (active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING + 1));
2125   initialize_shadow_regions(active_gc_threads);
2126   prepare_region_draining_tasks(active_gc_threads);
2127   enqueue_dense_prefix_tasks(task_queue, active_gc_threads);
2128 
2129   {
2130     GCTraceTime(Trace, gc, phases) tm("Par Compact", &_gc_timer);
2131 
2132     UpdateDensePrefixAndCompactionTask task(task_queue, active_gc_threads);
2133     ParallelScavengeHeap::heap()->workers().run_task(&task);
2134 
2135 #ifdef  ASSERT
2136     // Verify that all regions have been processed.
2137     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2138       verify_complete(SpaceId(id));
2139     }
2140 #endif
2141   }
2142 
2143   DEBUG_ONLY(write_block_fill_histogram());
2144 }
2145 
2146 #ifdef  ASSERT
2147 void PSParallelCompact::verify_complete(SpaceId space_id) {
2148   // All Regions between space bottom() to new_top() should be marked as filled
2149   // and all Regions between new_top() and top() should be available (i.e.,
2150   // should have been emptied).
2151   ParallelCompactData& sd = summary_data();
2152   SpaceInfo si = _space_info[space_id];
2153   HeapWord* new_top_addr = sd.region_align_up(si.new_top());
2154   HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
2155   const size_t beg_region = sd.addr_to_region_idx(si.space()->bottom());
2156   const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
2157   const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
2158 
2159   bool issued_a_warning = false;
2160 
2161   size_t cur_region;
2162   for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
2163     const RegionData* const c = sd.region(cur_region);
2164     if (!c->completed()) {
2165       log_warning(gc)("region " SIZE_FORMAT " not filled: destination_count=%u",
2166                       cur_region, c->destination_count());
2167       issued_a_warning = true;
2168     }
2169   }
2170 
2171   for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
2172     const RegionData* const c = sd.region(cur_region);
2173     if (!c->available()) {
2174       log_warning(gc)("region " SIZE_FORMAT " not empty: destination_count=%u",
2175                       cur_region, c->destination_count());
2176       issued_a_warning = true;
2177     }
2178   }
2179 
2180   if (issued_a_warning) {
2181     print_region_ranges();
2182   }
2183 }
2184 #endif  // #ifdef ASSERT
2185 
2186 inline void UpdateOnlyClosure::do_addr(HeapWord* addr) {
2187   compaction_manager()->update_contents(cast_to_oop(addr));
2188 }
2189 
2190 // Update interior oops in the ranges of regions [beg_region, end_region).
2191 void
2192 PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,
2193                                                        SpaceId space_id,
2194                                                        size_t beg_region,
2195                                                        size_t end_region) {
2196   ParallelCompactData& sd = summary_data();
2197   ParMarkBitMap* const mbm = mark_bitmap();
2198 
2199   HeapWord* beg_addr = sd.region_to_addr(beg_region);
2200   HeapWord* const end_addr = sd.region_to_addr(end_region);
2201   assert(beg_region <= end_region, "bad region range");
2202   assert(end_addr <= dense_prefix(space_id), "not in the dense prefix");
2203 
2204 #ifdef  ASSERT
2205   // Claim the regions to avoid triggering an assert when they are marked as
2206   // filled.
2207   for (size_t claim_region = beg_region; claim_region < end_region; ++claim_region) {
2208     assert(sd.region(claim_region)->claim_unsafe(), "claim() failed");
2209   }
2210 #endif  // #ifdef ASSERT
2211   HeapWord* const space_bottom = space(space_id)->bottom();
2212 
2213   // Check if it's the first region in this space.
2214   if (beg_addr != space_bottom) {
2215     // Find the first live object or block of dead space that *starts* in this
2216     // range of regions.  If a partial object crosses onto the region, skip it;
2217     // it will be marked for 'deferred update' when the object head is
2218     // processed.  If dead space crosses onto the region, it is also skipped; it
2219     // will be filled when the prior region is processed.  If neither of those
2220     // apply, the first word in the region is the start of a live object or dead
2221     // space.
2222     assert(beg_addr > space(space_id)->bottom(), "sanity");
2223     const RegionData* const cp = sd.region(beg_region);
2224     if (cp->partial_obj_size() != 0) {
2225       beg_addr = sd.partial_obj_end(beg_region);
2226     } else {
2227       idx_t beg_bit = mbm->addr_to_bit(beg_addr);
2228       if (!mbm->is_obj_beg(beg_bit) && !mbm->is_obj_end(beg_bit - 1)) {
2229         beg_addr = mbm->find_obj_beg(beg_addr, end_addr);
2230       }
2231     }
2232   }
2233 
2234   if (beg_addr < end_addr) {
2235     // A live object or block of dead space starts in this range of Regions.
2236      HeapWord* const dense_prefix_end = dense_prefix(space_id);
2237 
2238     // Create closures and iterate.
2239     UpdateOnlyClosure update_closure(mbm, cm, space_id);
2240     FillClosure fill_closure(cm, space_id);
2241     mbm->iterate(&update_closure, &fill_closure, beg_addr, end_addr, dense_prefix_end);
2242   }
2243 
2244   // Mark the regions as filled.
2245   RegionData* const beg_cp = sd.region(beg_region);
2246   RegionData* const end_cp = sd.region(end_region);
2247   for (RegionData* cp = beg_cp; cp < end_cp; ++cp) {
2248     cp->set_completed();
2249   }
2250 }
2251 
2252 // Return the SpaceId for the space containing addr.  If addr is not in the
2253 // heap, last_space_id is returned.  In debug mode it expects the address to be
2254 // in the heap and asserts such.
2255 PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
2256   assert(ParallelScavengeHeap::heap()->is_in_reserved(addr), "addr not in the heap");
2257 
2258   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2259     if (_space_info[id].space()->contains(addr)) {
2260       return SpaceId(id);
2261     }
2262   }
2263 
2264   assert(false, "no space contains the addr");
2265   return last_space_id;
2266 }
2267 
2268 void PSParallelCompact::update_deferred_object(ParCompactionManager* cm, HeapWord *addr) {
2269 #ifdef ASSERT
2270   ParallelCompactData& sd = summary_data();
2271   size_t region_idx = sd.addr_to_region_idx(addr);
2272   assert(sd.region(region_idx)->completed(), "first region must be completed before deferred updates");
2273   assert(sd.region(region_idx + 1)->completed(), "second region must be completed before deferred updates");
2274 #endif
2275 
2276   const SpaceInfo* const space_info = _space_info + space_id(addr);
2277   ObjectStartArray* const start_array = space_info->start_array();
2278   if (start_array != nullptr) {
2279     start_array->update_for_block(addr, addr + cast_to_oop(addr)->size());
2280   }
2281 
2282   cm->update_contents(cast_to_oop(addr));
2283   assert(oopDesc::is_oop(cast_to_oop(addr)), "Expected an oop at " PTR_FORMAT, p2i(cast_to_oop(addr)));
2284 }
2285 
2286 // Skip over count live words starting from beg, and return the address of the
2287 // next live word.  Unless marked, the word corresponding to beg is assumed to
2288 // be dead.  Callers must either ensure beg does not correspond to the middle of
2289 // an object, or account for those live words in some other way.  Callers must
2290 // also ensure that there are enough live words in the range [beg, end) to skip.
2291 HeapWord*
2292 PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
2293 {
2294   assert(count > 0, "sanity");
2295 
2296   ParMarkBitMap* m = mark_bitmap();
2297   idx_t bits_to_skip = m->words_to_bits(count);
2298   idx_t cur_beg = m->addr_to_bit(beg);
2299   const idx_t search_end = m->align_range_end(m->addr_to_bit(end));
2300 
2301   do {
2302     cur_beg = m->find_obj_beg(cur_beg, search_end);
2303     idx_t cur_end = m->find_obj_end(cur_beg, search_end);
2304     const size_t obj_bits = cur_end - cur_beg + 1;
2305     if (obj_bits > bits_to_skip) {
2306       return m->bit_to_addr(cur_beg + bits_to_skip);
2307     }
2308     bits_to_skip -= obj_bits;
2309     cur_beg = cur_end + 1;
2310   } while (bits_to_skip > 0);
2311 
2312   // Skipping the desired number of words landed just past the end of an object.
2313   // Find the start of the next object.
2314   cur_beg = m->find_obj_beg(cur_beg, search_end);
2315   assert(cur_beg < m->addr_to_bit(end), "not enough live words to skip");
2316   return m->bit_to_addr(cur_beg);
2317 }
2318 
2319 HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
2320                                             SpaceId src_space_id,
2321                                             size_t src_region_idx)
2322 {
2323   assert(summary_data().is_region_aligned(dest_addr), "not aligned");
2324 
2325   const SplitInfo& split_info = _space_info[src_space_id].split_info();
2326   if (split_info.dest_region_addr() == dest_addr) {
2327     // The partial object ending at the split point contains the first word to
2328     // be copied to dest_addr.
2329     return split_info.first_src_addr();
2330   }
2331 
2332   const ParallelCompactData& sd = summary_data();
2333   ParMarkBitMap* const bitmap = mark_bitmap();
2334   const size_t RegionSize = ParallelCompactData::RegionSize;
2335 
2336   assert(sd.is_region_aligned(dest_addr), "not aligned");
2337   const RegionData* const src_region_ptr = sd.region(src_region_idx);
2338   const size_t partial_obj_size = src_region_ptr->partial_obj_size();
2339   HeapWord* const src_region_destination = src_region_ptr->destination();
2340 
2341   assert(dest_addr >= src_region_destination, "wrong src region");
2342   assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
2343 
2344   HeapWord* const src_region_beg = sd.region_to_addr(src_region_idx);
2345   HeapWord* const src_region_end = src_region_beg + RegionSize;
2346 
2347   HeapWord* addr = src_region_beg;
2348   if (dest_addr == src_region_destination) {
2349     // Return the first live word in the source region.
2350     if (partial_obj_size == 0) {
2351       addr = bitmap->find_obj_beg(addr, src_region_end);
2352       assert(addr < src_region_end, "no objects start in src region");
2353     }
2354     return addr;
2355   }
2356 
2357   // Must skip some live data.
2358   size_t words_to_skip = dest_addr - src_region_destination;
2359   assert(src_region_ptr->data_size() > words_to_skip, "wrong src region");
2360 
2361   if (partial_obj_size >= words_to_skip) {
2362     // All the live words to skip are part of the partial object.
2363     addr += words_to_skip;
2364     if (partial_obj_size == words_to_skip) {
2365       // Find the first live word past the partial object.
2366       addr = bitmap->find_obj_beg(addr, src_region_end);
2367       assert(addr < src_region_end, "wrong src region");
2368     }
2369     return addr;
2370   }
2371 
2372   // Skip over the partial object (if any).
2373   if (partial_obj_size != 0) {
2374     words_to_skip -= partial_obj_size;
2375     addr += partial_obj_size;
2376   }
2377 
2378   // Skip over live words due to objects that start in the region.
2379   addr = skip_live_words(addr, src_region_end, words_to_skip);
2380   assert(addr < src_region_end, "wrong src region");
2381   return addr;
2382 }
2383 
2384 void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
2385                                                      SpaceId src_space_id,
2386                                                      size_t beg_region,
2387                                                      HeapWord* end_addr)
2388 {
2389   ParallelCompactData& sd = summary_data();
2390 
2391 #ifdef ASSERT
2392   MutableSpace* const src_space = _space_info[src_space_id].space();
2393   HeapWord* const beg_addr = sd.region_to_addr(beg_region);
2394   assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
2395          "src_space_id does not match beg_addr");
2396   assert(src_space->contains(end_addr) || end_addr == src_space->end(),
2397          "src_space_id does not match end_addr");
2398 #endif // #ifdef ASSERT
2399 
2400   RegionData* const beg = sd.region(beg_region);
2401   RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));
2402 
2403   // Regions up to new_top() are enqueued if they become available.
2404   HeapWord* const new_top = _space_info[src_space_id].new_top();
2405   RegionData* const enqueue_end =
2406     sd.addr_to_region_ptr(sd.region_align_up(new_top));
2407 
2408   for (RegionData* cur = beg; cur < end; ++cur) {
2409     assert(cur->data_size() > 0, "region must have live data");
2410     cur->decrement_destination_count();
2411     if (cur < enqueue_end && cur->available() && cur->claim()) {
2412       if (cur->mark_normal()) {
2413         cm->push_region(sd.region(cur));
2414       } else if (cur->mark_copied()) {
2415         // Try to copy the content of the shadow region back to its corresponding
2416         // heap region if the shadow region is filled. Otherwise, the GC thread
2417         // fills the shadow region will copy the data back (see
2418         // MoveAndUpdateShadowClosure::complete_region).
2419         copy_back(sd.region_to_addr(cur->shadow_region()), sd.region_to_addr(cur));
2420         ParCompactionManager::push_shadow_region_mt_safe(cur->shadow_region());
2421         cur->set_completed();
2422       }
2423     }
2424   }
2425 }
2426 
2427 size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
2428                                           SpaceId& src_space_id,
2429                                           HeapWord*& src_space_top,
2430                                           HeapWord* end_addr)
2431 {
2432   typedef ParallelCompactData::RegionData RegionData;
2433 
2434   ParallelCompactData& sd = PSParallelCompact::summary_data();
2435   const size_t region_size = ParallelCompactData::RegionSize;
2436 
2437   size_t src_region_idx = 0;
2438 
2439   // Skip empty regions (if any) up to the top of the space.
2440   HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
2441   RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
2442   HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
2443   const RegionData* const top_region_ptr =
2444     sd.addr_to_region_ptr(top_aligned_up);
2445   while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
2446     ++src_region_ptr;
2447   }
2448 
2449   if (src_region_ptr < top_region_ptr) {
2450     // The next source region is in the current space.  Update src_region_idx
2451     // and the source address to match src_region_ptr.
2452     src_region_idx = sd.region(src_region_ptr);
2453     HeapWord* const src_region_addr = sd.region_to_addr(src_region_idx);
2454     if (src_region_addr > closure.source()) {
2455       closure.set_source(src_region_addr);
2456     }
2457     return src_region_idx;
2458   }
2459 
2460   // Switch to a new source space and find the first non-empty region.
2461   unsigned int space_id = src_space_id + 1;
2462   assert(space_id < last_space_id, "not enough spaces");
2463 
2464   HeapWord* const destination = closure.destination();
2465 
2466   do {
2467     MutableSpace* space = _space_info[space_id].space();
2468     HeapWord* const bottom = space->bottom();
2469     const RegionData* const bottom_cp = sd.addr_to_region_ptr(bottom);
2470 
2471     // Iterate over the spaces that do not compact into themselves.
2472     if (bottom_cp->destination() != bottom) {
2473       HeapWord* const top_aligned_up = sd.region_align_up(space->top());
2474       const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
2475 
2476       for (const RegionData* src_cp = bottom_cp; src_cp < top_cp; ++src_cp) {
2477         if (src_cp->live_obj_size() > 0) {
2478           // Found it.
2479           assert(src_cp->destination() == destination,
2480                  "first live obj in the space must match the destination");
2481           assert(src_cp->partial_obj_size() == 0,
2482                  "a space cannot begin with a partial obj");
2483 
2484           src_space_id = SpaceId(space_id);
2485           src_space_top = space->top();
2486           const size_t src_region_idx = sd.region(src_cp);
2487           closure.set_source(sd.region_to_addr(src_region_idx));
2488           return src_region_idx;
2489         } else {
2490           assert(src_cp->data_size() == 0, "sanity");
2491         }
2492       }
2493     }
2494   } while (++space_id < last_space_id);
2495 
2496   assert(false, "no source region was found");
2497   return 0;
2498 }
2499 
2500 void PSParallelCompact::fill_region(ParCompactionManager* cm, MoveAndUpdateClosure& closure, size_t region_idx)
2501 {
2502   typedef ParMarkBitMap::IterationStatus IterationStatus;
2503   ParMarkBitMap* const bitmap = mark_bitmap();
2504   ParallelCompactData& sd = summary_data();
2505   RegionData* const region_ptr = sd.region(region_idx);
2506 
2507   // Get the source region and related info.
2508   size_t src_region_idx = region_ptr->source_region();
2509   SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
2510   HeapWord* src_space_top = _space_info[src_space_id].space()->top();
2511   HeapWord* dest_addr = sd.region_to_addr(region_idx);
2512 
2513   closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
2514 
2515   // Adjust src_region_idx to prepare for decrementing destination counts (the
2516   // destination count is not decremented when a region is copied to itself).
2517   if (src_region_idx == region_idx) {
2518     src_region_idx += 1;
2519   }
2520 
2521   if (bitmap->is_unmarked(closure.source())) {
2522     // The first source word is in the middle of an object; copy the remainder
2523     // of the object or as much as will fit.  The fact that pointer updates were
2524     // deferred will be noted when the object header is processed.
2525     HeapWord* const old_src_addr = closure.source();
2526     closure.copy_partial_obj();
2527     if (closure.is_full()) {
2528       decrement_destination_counts(cm, src_space_id, src_region_idx,
2529                                    closure.source());
2530       closure.complete_region(cm, dest_addr, region_ptr);
2531       return;
2532     }
2533 
2534     HeapWord* const end_addr = sd.region_align_down(closure.source());
2535     if (sd.region_align_down(old_src_addr) != end_addr) {
2536       // The partial object was copied from more than one source region.
2537       decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2538 
2539       // Move to the next source region, possibly switching spaces as well.  All
2540       // args except end_addr may be modified.
2541       src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2542                                        end_addr);
2543     }
2544   }
2545 
2546   do {
2547     HeapWord* const cur_addr = closure.source();
2548     HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
2549                                     src_space_top);
2550     IterationStatus status = bitmap->iterate(&closure, cur_addr, end_addr);
2551 
2552     if (status == ParMarkBitMap::would_overflow) {
2553       // The last object did not fit.  Note that interior oop updates were
2554       // deferred, then copy enough of the object to fill the region.
2555       cm->push_deferred_object(closure.destination());
2556       status = closure.copy_until_full(); // copies from closure.source()
2557 
2558       decrement_destination_counts(cm, src_space_id, src_region_idx,
2559                                    closure.source());
2560       closure.complete_region(cm, dest_addr, region_ptr);
2561       return;
2562     }
2563 
2564     if (status == ParMarkBitMap::full) {
2565       decrement_destination_counts(cm, src_space_id, src_region_idx,
2566                                    closure.source());
2567       closure.complete_region(cm, dest_addr, region_ptr);
2568       return;
2569     }
2570 
2571     decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2572 
2573     // Move to the next source region, possibly switching spaces as well.  All
2574     // args except end_addr may be modified.
2575     src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2576                                      end_addr);
2577   } while (true);
2578 }
2579 
2580 void PSParallelCompact::fill_and_update_region(ParCompactionManager* cm, size_t region_idx)
2581 {
2582   MoveAndUpdateClosure cl(mark_bitmap(), cm, region_idx);
2583   fill_region(cm, cl, region_idx);
2584 }
2585 
2586 void PSParallelCompact::fill_and_update_shadow_region(ParCompactionManager* cm, size_t region_idx)
2587 {
2588   // Get a shadow region first
2589   ParallelCompactData& sd = summary_data();
2590   RegionData* const region_ptr = sd.region(region_idx);
2591   size_t shadow_region = ParCompactionManager::pop_shadow_region_mt_safe(region_ptr);
2592   // The InvalidShadow return value indicates the corresponding heap region is available,
2593   // so use MoveAndUpdateClosure to fill the normal region. Otherwise, use
2594   // MoveAndUpdateShadowClosure to fill the acquired shadow region.
2595   if (shadow_region == ParCompactionManager::InvalidShadow) {
2596     MoveAndUpdateClosure cl(mark_bitmap(), cm, region_idx);
2597     region_ptr->shadow_to_normal();
2598     return fill_region(cm, cl, region_idx);
2599   } else {
2600     MoveAndUpdateShadowClosure cl(mark_bitmap(), cm, region_idx, shadow_region);
2601     return fill_region(cm, cl, region_idx);
2602   }
2603 }
2604 
2605 void PSParallelCompact::copy_back(HeapWord *shadow_addr, HeapWord *region_addr)
2606 {
2607   Copy::aligned_conjoint_words(shadow_addr, region_addr, _summary_data.RegionSize);
2608 }
2609 
2610 bool PSParallelCompact::steal_unavailable_region(ParCompactionManager* cm, size_t &region_idx)
2611 {
2612   size_t next = cm->next_shadow_region();
2613   ParallelCompactData& sd = summary_data();
2614   size_t old_new_top = sd.addr_to_region_idx(_space_info[old_space_id].new_top());
2615   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2616 
2617   while (next < old_new_top) {
2618     if (sd.region(next)->mark_shadow()) {
2619       region_idx = next;
2620       return true;
2621     }
2622     next = cm->move_next_shadow_region_by(active_gc_threads);
2623   }
2624 
2625   return false;
2626 }
2627 
2628 // The shadow region is an optimization to address region dependencies in full GC. The basic
2629 // idea is making more regions available by temporally storing their live objects in empty
2630 // shadow regions to resolve dependencies between them and the destination regions. Therefore,
2631 // GC threads need not wait destination regions to be available before processing sources.
2632 //
2633 // A typical workflow would be:
2634 // After draining its own stack and failing to steal from others, a GC worker would pick an
2635 // unavailable region (destination count > 0) and get a shadow region. Then the worker fills
2636 // the shadow region by copying live objects from source regions of the unavailable one. Once
2637 // the unavailable region becomes available, the data in the shadow region will be copied back.
2638 // Shadow regions are empty regions in the to-space and regions between top and end of other spaces.
2639 void PSParallelCompact::initialize_shadow_regions(uint parallel_gc_threads)
2640 {
2641   const ParallelCompactData& sd = PSParallelCompact::summary_data();
2642 
2643   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2644     SpaceInfo* const space_info = _space_info + id;
2645     MutableSpace* const space = space_info->space();
2646 
2647     const size_t beg_region =
2648       sd.addr_to_region_idx(sd.region_align_up(MAX2(space_info->new_top(), space->top())));
2649     const size_t end_region =
2650       sd.addr_to_region_idx(sd.region_align_down(space->end()));
2651 
2652     for (size_t cur = beg_region; cur < end_region; ++cur) {
2653       ParCompactionManager::push_shadow_region(cur);
2654     }
2655   }
2656 
2657   size_t beg_region = sd.addr_to_region_idx(_space_info[old_space_id].dense_prefix());
2658   for (uint i = 0; i < parallel_gc_threads; i++) {
2659     ParCompactionManager *cm = ParCompactionManager::gc_thread_compaction_manager(i);
2660     cm->set_next_shadow_region(beg_region + i);
2661   }
2662 }
2663 
2664 void PSParallelCompact::fill_blocks(size_t region_idx)
2665 {
2666   // Fill in the block table elements for the specified region.  Each block
2667   // table element holds the number of live words in the region that are to the
2668   // left of the first object that starts in the block.  Thus only blocks in
2669   // which an object starts need to be filled.
2670   //
2671   // The algorithm scans the section of the bitmap that corresponds to the
2672   // region, keeping a running total of the live words.  When an object start is
2673   // found, if it's the first to start in the block that contains it, the
2674   // current total is written to the block table element.
2675   const size_t Log2BlockSize = ParallelCompactData::Log2BlockSize;
2676   const size_t Log2RegionSize = ParallelCompactData::Log2RegionSize;
2677   const size_t RegionSize = ParallelCompactData::RegionSize;
2678 
2679   ParallelCompactData& sd = summary_data();
2680   const size_t partial_obj_size = sd.region(region_idx)->partial_obj_size();
2681   if (partial_obj_size >= RegionSize) {
2682     return; // No objects start in this region.
2683   }
2684 
2685   // Ensure the first loop iteration decides that the block has changed.
2686   size_t cur_block = sd.block_count();
2687 
2688   const ParMarkBitMap* const bitmap = mark_bitmap();
2689 
2690   const size_t Log2BitsPerBlock = Log2BlockSize - LogMinObjAlignment;
2691   assert((size_t)1 << Log2BitsPerBlock ==
2692          bitmap->words_to_bits(ParallelCompactData::BlockSize), "sanity");
2693 
2694   size_t beg_bit = bitmap->words_to_bits(region_idx << Log2RegionSize);
2695   const size_t range_end = beg_bit + bitmap->words_to_bits(RegionSize);
2696   size_t live_bits = bitmap->words_to_bits(partial_obj_size);
2697   beg_bit = bitmap->find_obj_beg(beg_bit + live_bits, range_end);
2698   while (beg_bit < range_end) {
2699     const size_t new_block = beg_bit >> Log2BitsPerBlock;
2700     if (new_block != cur_block) {
2701       cur_block = new_block;
2702       sd.block(cur_block)->set_offset(bitmap->bits_to_words(live_bits));
2703     }
2704 
2705     const size_t end_bit = bitmap->find_obj_end(beg_bit, range_end);
2706     if (end_bit < range_end - 1) {
2707       live_bits += end_bit - beg_bit + 1;
2708       beg_bit = bitmap->find_obj_beg(end_bit + 1, range_end);
2709     } else {
2710       return;
2711     }
2712   }
2713 }
2714 
2715 ParMarkBitMap::IterationStatus MoveAndUpdateClosure::copy_until_full()
2716 {
2717   if (source() != copy_destination()) {
2718     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2719     Copy::aligned_conjoint_words(source(), copy_destination(), words_remaining());
2720   }
2721   update_state(words_remaining());
2722   assert(is_full(), "sanity");
2723   return ParMarkBitMap::full;
2724 }
2725 
2726 void MoveAndUpdateClosure::copy_partial_obj()
2727 {
2728   size_t words = words_remaining();
2729 
2730   HeapWord* const range_end = MIN2(source() + words, bitmap()->region_end());
2731   HeapWord* const end_addr = bitmap()->find_obj_end(source(), range_end);
2732   if (end_addr < range_end) {
2733     words = bitmap()->obj_size(source(), end_addr);
2734   }
2735 
2736   // This test is necessary; if omitted, the pointer updates to a partial object
2737   // that crosses the dense prefix boundary could be overwritten.
2738   if (source() != copy_destination()) {
2739     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2740     Copy::aligned_conjoint_words(source(), copy_destination(), words);
2741   }
2742   update_state(words);
2743 }
2744 
2745 void MoveAndUpdateClosure::complete_region(ParCompactionManager *cm, HeapWord *dest_addr,
2746                                            PSParallelCompact::RegionData *region_ptr) {
2747   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::NormalRegion, "Region should be finished");
2748   region_ptr->set_completed();
2749 }
2750 
2751 ParMarkBitMapClosure::IterationStatus
2752 MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
2753   assert(destination() != nullptr, "sanity");
2754   assert(bitmap()->obj_size(addr) == words, "bad size");
2755 
2756   _source = addr;
2757   assert(PSParallelCompact::summary_data().calc_new_pointer(source(), compaction_manager()) ==
2758          destination(), "wrong destination");
2759 
2760   if (words > words_remaining()) {
2761     return ParMarkBitMap::would_overflow;
2762   }
2763 
2764   // The start_array must be updated even if the object is not moving.
2765   if (_start_array != nullptr) {
2766     _start_array->update_for_block(destination(), destination() + words);
2767   }
2768 
2769   if (copy_destination() != source()) {
2770     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2771     Copy::aligned_conjoint_words(source(), copy_destination(), words);
2772   }
2773 
2774   oop moved_oop = cast_to_oop(copy_destination());
2775   compaction_manager()->update_contents(moved_oop);
2776   assert(oopDesc::is_oop_or_null(moved_oop), "Expected an oop or null at " PTR_FORMAT, p2i(moved_oop));
2777 
2778   update_state(words);
2779   assert(copy_destination() == cast_from_oop<HeapWord*>(moved_oop) + moved_oop->size(), "sanity");
2780   return is_full() ? ParMarkBitMap::full : ParMarkBitMap::incomplete;
2781 }
2782 
2783 void MoveAndUpdateShadowClosure::complete_region(ParCompactionManager *cm, HeapWord *dest_addr,
2784                                                  PSParallelCompact::RegionData *region_ptr) {
2785   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::ShadowRegion, "Region should be shadow");
2786   // Record the shadow region index
2787   region_ptr->set_shadow_region(_shadow);
2788   // Mark the shadow region as filled to indicate the data is ready to be
2789   // copied back
2790   region_ptr->mark_filled();
2791   // Try to copy the content of the shadow region back to its corresponding
2792   // heap region if available; the GC thread that decreases the destination
2793   // count to zero will do the copying otherwise (see
2794   // PSParallelCompact::decrement_destination_counts).
2795   if (((region_ptr->available() && region_ptr->claim()) || region_ptr->claimed()) && region_ptr->mark_copied()) {
2796     region_ptr->set_completed();
2797     PSParallelCompact::copy_back(PSParallelCompact::summary_data().region_to_addr(_shadow), dest_addr);
2798     ParCompactionManager::push_shadow_region_mt_safe(_shadow);
2799   }
2800 }
2801 
2802 UpdateOnlyClosure::UpdateOnlyClosure(ParMarkBitMap* mbm,
2803                                      ParCompactionManager* cm,
2804                                      PSParallelCompact::SpaceId space_id) :
2805   ParMarkBitMapClosure(mbm, cm),
2806   _start_array(PSParallelCompact::start_array(space_id))
2807 {
2808 }
2809 
2810 // Updates the references in the object to their new values.
2811 ParMarkBitMapClosure::IterationStatus
2812 UpdateOnlyClosure::do_addr(HeapWord* addr, size_t words) {
2813   do_addr(addr);
2814   return ParMarkBitMap::incomplete;
2815 }
2816 
2817 FillClosure::FillClosure(ParCompactionManager* cm, PSParallelCompact::SpaceId space_id) :
2818   ParMarkBitMapClosure(PSParallelCompact::mark_bitmap(), cm),
2819   _start_array(PSParallelCompact::start_array(space_id))
2820 {
2821   assert(space_id == PSParallelCompact::old_space_id,
2822          "cannot use FillClosure in the young gen");
2823 }
2824 
2825 ParMarkBitMapClosure::IterationStatus
2826 FillClosure::do_addr(HeapWord* addr, size_t size) {
2827   CollectedHeap::fill_with_objects(addr, size);
2828   HeapWord* const end = addr + size;
2829   do {
2830     size_t size = cast_to_oop(addr)->size();
2831     _start_array->update_for_block(addr, addr + size);
2832     addr += size;
2833   } while (addr < end);
2834   return ParMarkBitMap::incomplete;
2835 }