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