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