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