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