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