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