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