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