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