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