psParallelCompact.cpp 133.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include "precompiled.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "code/codeCache.hpp"
#include "gc_implementation/parallelScavenge/gcTaskManager.hpp"
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
#include "gc_implementation/parallelScavenge/pcTasks.hpp"
#include "gc_implementation/parallelScavenge/psAdaptiveSizePolicy.hpp"
#include "gc_implementation/parallelScavenge/psCompactionManager.inline.hpp"
#include "gc_implementation/parallelScavenge/psMarkSweep.hpp"
#include "gc_implementation/parallelScavenge/psMarkSweepDecorator.hpp"
#include "gc_implementation/parallelScavenge/psOldGen.hpp"
#include "gc_implementation/parallelScavenge/psParallelCompact.hpp"
#include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
#include "gc_implementation/parallelScavenge/psScavenge.hpp"
#include "gc_implementation/parallelScavenge/psYoungGen.hpp"
S
sla 已提交
41 42 43 44
#include "gc_implementation/shared/gcHeapSummary.hpp"
#include "gc_implementation/shared/gcTimer.hpp"
#include "gc_implementation/shared/gcTrace.hpp"
#include "gc_implementation/shared/gcTraceTime.hpp"
45 46 47 48 49
#include "gc_implementation/shared/isGCActiveMark.hpp"
#include "gc_interface/gcCause.hpp"
#include "memory/gcLocker.inline.hpp"
#include "memory/referencePolicy.hpp"
#include "memory/referenceProcessor.hpp"
50
#include "oops/methodData.hpp"
51 52 53 54 55 56 57
#include "oops/oop.inline.hpp"
#include "oops/oop.pcgc.inline.hpp"
#include "runtime/fprofiler.hpp"
#include "runtime/safepoint.hpp"
#include "runtime/vmThread.hpp"
#include "services/management.hpp"
#include "services/memoryService.hpp"
Z
zgu 已提交
58
#include "services/memTracker.hpp"
59 60
#include "utilities/events.hpp"
#include "utilities/stack.inline.hpp"
D
duke 已提交
61 62 63 64

#include <math.h>

// All sizes are in HeapWords.
65
const size_t ParallelCompactData::Log2RegionSize  = 16; // 64K words
66 67 68 69 70
const size_t ParallelCompactData::RegionSize      = (size_t)1 << Log2RegionSize;
const size_t ParallelCompactData::RegionSizeBytes =
  RegionSize << LogHeapWordSize;
const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
71 72 73 74 75 76 77 78 79 80 81 82 83
const size_t ParallelCompactData::RegionAddrMask       = ~RegionAddrOffsetMask;

const size_t ParallelCompactData::Log2BlockSize   = 7; // 128 words
const size_t ParallelCompactData::BlockSize       = (size_t)1 << Log2BlockSize;
const size_t ParallelCompactData::BlockSizeBytes  =
  BlockSize << LogHeapWordSize;
const size_t ParallelCompactData::BlockSizeOffsetMask = BlockSize - 1;
const size_t ParallelCompactData::BlockAddrOffsetMask = BlockSizeBytes - 1;
const size_t ParallelCompactData::BlockAddrMask       = ~BlockAddrOffsetMask;

const size_t ParallelCompactData::BlocksPerRegion = RegionSize / BlockSize;
const size_t ParallelCompactData::Log2BlocksPerRegion =
  Log2RegionSize - Log2BlockSize;
D
duke 已提交
84

85 86
const ParallelCompactData::RegionData::region_sz_t
ParallelCompactData::RegionData::dc_shift = 27;
D
duke 已提交
87

88 89
const ParallelCompactData::RegionData::region_sz_t
ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
D
duke 已提交
90

91 92
const ParallelCompactData::RegionData::region_sz_t
ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
D
duke 已提交
93

94 95
const ParallelCompactData::RegionData::region_sz_t
ParallelCompactData::RegionData::los_mask = ~dc_mask;
D
duke 已提交
96

97 98
const ParallelCompactData::RegionData::region_sz_t
ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
D
duke 已提交
99

100 101
const ParallelCompactData::RegionData::region_sz_t
ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
D
duke 已提交
102 103 104 105 106

SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
bool      PSParallelCompact::_print_phases = false;

ReferenceProcessor* PSParallelCompact::_ref_processor = NULL;
107
Klass*              PSParallelCompact::_updated_int_array_klass_obj = NULL;
D
duke 已提交
108 109 110 111 112 113 114 115 116

double PSParallelCompact::_dwl_mean;
double PSParallelCompact::_dwl_std_dev;
double PSParallelCompact::_dwl_first_term;
double PSParallelCompact::_dwl_adjustment;
#ifdef  ASSERT
bool   PSParallelCompact::_dwl_initialized = false;
#endif  // #ifdef ASSERT

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
void SplitInfo::record(size_t src_region_idx, size_t partial_obj_size,
                       HeapWord* destination)
{
  assert(src_region_idx != 0, "invalid src_region_idx");
  assert(partial_obj_size != 0, "invalid partial_obj_size argument");
  assert(destination != NULL, "invalid destination argument");

  _src_region_idx = src_region_idx;
  _partial_obj_size = partial_obj_size;
  _destination = destination;

  // These fields may not be updated below, so make sure they're clear.
  assert(_dest_region_addr == NULL, "should have been cleared");
  assert(_first_src_addr == NULL, "should have been cleared");

  // Determine the number of destination regions for the partial object.
  HeapWord* const last_word = destination + partial_obj_size - 1;
  const ParallelCompactData& sd = PSParallelCompact::summary_data();
  HeapWord* const beg_region_addr = sd.region_align_down(destination);
  HeapWord* const end_region_addr = sd.region_align_down(last_word);

  if (beg_region_addr == end_region_addr) {
    // One destination region.
    _destination_count = 1;
    if (end_region_addr == destination) {
      // The destination falls on a region boundary, thus the first word of the
      // partial object will be the first word copied to the destination region.
      _dest_region_addr = end_region_addr;
      _first_src_addr = sd.region_to_addr(src_region_idx);
    }
  } else {
    // Two destination regions.  When copied, the partial object will cross a
    // destination region boundary, so a word somewhere within the partial
    // object will be the first word copied to the second destination region.
    _destination_count = 2;
    _dest_region_addr = end_region_addr;
    const size_t ofs = pointer_delta(end_region_addr, destination);
    assert(ofs < _partial_obj_size, "sanity");
    _first_src_addr = sd.region_to_addr(src_region_idx) + ofs;
  }
}

void SplitInfo::clear()
{
  _src_region_idx = 0;
  _partial_obj_size = 0;
  _destination = NULL;
  _destination_count = 0;
  _dest_region_addr = NULL;
  _first_src_addr = NULL;
  assert(!is_valid(), "sanity");
}

#ifdef  ASSERT
void SplitInfo::verify_clear()
{
  assert(_src_region_idx == 0, "not clear");
  assert(_partial_obj_size == 0, "not clear");
  assert(_destination == NULL, "not clear");
  assert(_destination_count == 0, "not clear");
  assert(_dest_region_addr == NULL, "not clear");
  assert(_first_src_addr == NULL, "not clear");
}
#endif  // #ifdef ASSERT


183 184 185 186
void PSParallelCompact::print_on_error(outputStream* st) {
  _mark_bitmap.print_on_error(st);
}

D
duke 已提交
187 188
#ifndef PRODUCT
const char* PSParallelCompact::space_names[] = {
189
  "old ", "eden", "from", "to  "
D
duke 已提交
190 191
};

192
void PSParallelCompact::print_region_ranges()
D
duke 已提交
193 194 195 196 197 198 199
{
  tty->print_cr("space  bottom     top        end        new_top");
  tty->print_cr("------ ---------- ---------- ---------- ----------");

  for (unsigned int id = 0; id < last_space_id; ++id) {
    const MutableSpace* space = _space_info[id].space();
    tty->print_cr("%u %s "
200 201
                  SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " "
                  SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ",
D
duke 已提交
202
                  id, space_names[id],
203 204 205 206
                  summary_data().addr_to_region_idx(space->bottom()),
                  summary_data().addr_to_region_idx(space->top()),
                  summary_data().addr_to_region_idx(space->end()),
                  summary_data().addr_to_region_idx(_space_info[id].new_top()));
D
duke 已提交
207 208 209 210
  }
}

void
211
print_generic_summary_region(size_t i, const ParallelCompactData::RegionData* c)
D
duke 已提交
212
{
213 214
#define REGION_IDX_FORMAT        SIZE_FORMAT_W(7)
#define REGION_DATA_FORMAT       SIZE_FORMAT_W(5)
D
duke 已提交
215 216

  ParallelCompactData& sd = PSParallelCompact::summary_data();
217 218 219 220 221
  size_t dci = c->destination() ? sd.addr_to_region_idx(c->destination()) : 0;
  tty->print_cr(REGION_IDX_FORMAT " " PTR_FORMAT " "
                REGION_IDX_FORMAT " " PTR_FORMAT " "
                REGION_DATA_FORMAT " " REGION_DATA_FORMAT " "
                REGION_DATA_FORMAT " " REGION_IDX_FORMAT " %d",
D
duke 已提交
222 223
                i, c->data_location(), dci, c->destination(),
                c->partial_obj_size(), c->live_obj_size(),
224
                c->data_size(), c->source_region(), c->destination_count());
D
duke 已提交
225

226 227
#undef  REGION_IDX_FORMAT
#undef  REGION_DATA_FORMAT
D
duke 已提交
228 229 230 231 232 233 234 235
}

void
print_generic_summary_data(ParallelCompactData& summary_data,
                           HeapWord* const beg_addr,
                           HeapWord* const end_addr)
{
  size_t total_words = 0;
236 237
  size_t i = summary_data.addr_to_region_idx(beg_addr);
  const size_t last = summary_data.addr_to_region_idx(end_addr);
D
duke 已提交
238 239 240
  HeapWord* pdest = 0;

  while (i <= last) {
241
    ParallelCompactData::RegionData* c = summary_data.region(i);
D
duke 已提交
242
    if (c->data_size() != 0 || c->destination() != pdest) {
243
      print_generic_summary_region(i, c);
D
duke 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
      total_words += c->data_size();
      pdest = c->destination();
    }
    ++i;
  }

  tty->print_cr("summary_data_bytes=" SIZE_FORMAT, total_words * HeapWordSize);
}

void
print_generic_summary_data(ParallelCompactData& summary_data,
                           SpaceInfo* space_info)
{
  for (unsigned int id = 0; id < PSParallelCompact::last_space_id; ++id) {
    const MutableSpace* space = space_info[id].space();
    print_generic_summary_data(summary_data, space->bottom(),
                               MAX2(space->top(), space_info[id].new_top()));
  }
}

void
265 266 267
print_initial_summary_region(size_t i,
                             const ParallelCompactData::RegionData* c,
                             bool newline = true)
D
duke 已提交
268
{
269 270 271
  tty->print(SIZE_FORMAT_W(5) " " PTR_FORMAT " "
             SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " "
             SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
D
duke 已提交
272 273
             i, c->destination(),
             c->partial_obj_size(), c->live_obj_size(),
274
             c->data_size(), c->source_region(), c->destination_count());
D
duke 已提交
275 276 277 278 279 280 281 282 283 284
  if (newline) tty->cr();
}

void
print_initial_summary_data(ParallelCompactData& summary_data,
                           const MutableSpace* space) {
  if (space->top() == space->bottom()) {
    return;
  }

285 286 287 288 289
  const size_t region_size = ParallelCompactData::RegionSize;
  typedef ParallelCompactData::RegionData RegionData;
  HeapWord* const top_aligned_up = summary_data.region_align_up(space->top());
  const size_t end_region = summary_data.addr_to_region_idx(top_aligned_up);
  const RegionData* c = summary_data.region(end_region - 1);
D
duke 已提交
290 291 292
  HeapWord* end_addr = c->destination() + c->data_size();
  const size_t live_in_space = pointer_delta(end_addr, space->bottom());

293 294 295 296 297 298
  // Print (and count) the full regions at the beginning of the space.
  size_t full_region_count = 0;
  size_t i = summary_data.addr_to_region_idx(space->bottom());
  while (i < end_region && summary_data.region(i)->data_size() == region_size) {
    print_initial_summary_region(i, summary_data.region(i));
    ++full_region_count;
D
duke 已提交
299 300 301
    ++i;
  }

302
  size_t live_to_right = live_in_space - full_region_count * region_size;
D
duke 已提交
303 304

  double max_reclaimed_ratio = 0.0;
305
  size_t max_reclaimed_ratio_region = 0;
D
duke 已提交
306 307 308
  size_t max_dead_to_right = 0;
  size_t max_live_to_right = 0;

309 310
  // Print the 'reclaimed ratio' for regions while there is something live in
  // the region or to the right of it.  The remaining regions are empty (and
D
duke 已提交
311
  // uninteresting), and computing the ratio will result in division by 0.
312 313 314 315
  while (i < end_region && live_to_right > 0) {
    c = summary_data.region(i);
    HeapWord* const region_addr = summary_data.region_to_addr(i);
    const size_t used_to_right = pointer_delta(space->top(), region_addr);
D
duke 已提交
316 317 318 319 320
    const size_t dead_to_right = used_to_right - live_to_right;
    const double reclaimed_ratio = double(dead_to_right) / live_to_right;

    if (reclaimed_ratio > max_reclaimed_ratio) {
            max_reclaimed_ratio = reclaimed_ratio;
321
            max_reclaimed_ratio_region = i;
D
duke 已提交
322 323 324 325
            max_dead_to_right = dead_to_right;
            max_live_to_right = live_to_right;
    }

326
    print_initial_summary_region(i, c, false);
327
    tty->print_cr(" %12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10),
D
duke 已提交
328 329 330 331 332 333
                  reclaimed_ratio, dead_to_right, live_to_right);

    live_to_right -= c->data_size();
    ++i;
  }

334 335 336
  // Any remaining regions are empty.  Print one more if there is one.
  if (i < end_region) {
    print_initial_summary_region(i, summary_data.region(i));
D
duke 已提交
337 338
  }

339 340
  tty->print_cr("max:  " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " "
                "l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f",
341
                max_reclaimed_ratio_region, max_dead_to_right,
D
duke 已提交
342 343 344 345 346 347
                max_live_to_right, max_reclaimed_ratio);
}

void
print_initial_summary_data(ParallelCompactData& summary_data,
                           SpaceInfo* space_info) {
348
  unsigned int id = PSParallelCompact::old_space_id;
D
duke 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  const MutableSpace* space;
  do {
    space = space_info[id].space();
    print_initial_summary_data(summary_data, space);
  } while (++id < PSParallelCompact::eden_space_id);

  do {
    space = space_info[id].space();
    print_generic_summary_data(summary_data, space->bottom(), space->top());
  } while (++id < PSParallelCompact::last_space_id);
}
#endif  // #ifndef PRODUCT

#ifdef  ASSERT
size_t add_obj_count;
size_t add_obj_size;
size_t mark_bitmap_count;
size_t mark_bitmap_size;
#endif  // #ifdef ASSERT

ParallelCompactData::ParallelCompactData()
{
  _region_start = 0;

373
  _region_vspace = 0;
374
  _reserved_byte_size = 0;
375 376
  _region_data = 0;
  _region_count = 0;
377 378 379 380

  _block_vspace = 0;
  _block_data = 0;
  _block_count = 0;
D
duke 已提交
381 382 383 384 385 386 387 388
}

bool ParallelCompactData::initialize(MemRegion covered_region)
{
  _region_start = covered_region.start();
  const size_t region_size = covered_region.word_size();
  DEBUG_ONLY(_region_end = _region_start + region_size;)

389
  assert(region_align_down(_region_start) == _region_start,
D
duke 已提交
390
         "region start not aligned");
391 392
  assert((region_size & RegionSizeOffsetMask) == 0,
         "region size not a multiple of RegionSize");
D
duke 已提交
393

394
  bool result = initialize_region_data(region_size) && initialize_block_data();
D
duke 已提交
395 396 397 398 399 400 401 402 403
  return result;
}

PSVirtualSpace*
ParallelCompactData::create_vspace(size_t count, size_t element_size)
{
  const size_t raw_bytes = count * element_size;
  const size_t page_sz = os::page_size_for_region(raw_bytes, raw_bytes, 10);
  const size_t granularity = os::vm_allocation_granularity();
404
  _reserved_byte_size = align_size_up(raw_bytes, MAX2(page_sz, granularity));
D
duke 已提交
405 406 407

  const size_t rs_align = page_sz == (size_t) os::vm_page_size() ? 0 :
    MAX2(page_sz, granularity);
408
  ReservedSpace rs(_reserved_byte_size, rs_align, rs_align > 0);
D
duke 已提交
409 410
  os::trace_page_sizes("par compact", raw_bytes, raw_bytes, page_sz, rs.base(),
                       rs.size());
Z
zgu 已提交
411 412 413

  MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);

D
duke 已提交
414 415
  PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
  if (vspace != 0) {
416
    if (vspace->expand_by(_reserved_byte_size)) {
D
duke 已提交
417 418 419
      return vspace;
    }
    delete vspace;
420 421
    // Release memory reserved in the space.
    rs.release();
D
duke 已提交
422 423 424 425 426
  }

  return 0;
}

427
bool ParallelCompactData::initialize_region_data(size_t region_size)
D
duke 已提交
428
{
429 430 431 432 433
  const size_t count = (region_size + RegionSizeOffsetMask) >> Log2RegionSize;
  _region_vspace = create_vspace(count, sizeof(RegionData));
  if (_region_vspace != 0) {
    _region_data = (RegionData*)_region_vspace->reserved_low_addr();
    _region_count = count;
D
duke 已提交
434 435 436 437 438
    return true;
  }
  return false;
}

439 440 441 442 443 444 445 446 447 448 449 450 451
bool ParallelCompactData::initialize_block_data()
{
  assert(_region_count != 0, "region data must be initialized first");
  const size_t count = _region_count << Log2BlocksPerRegion;
  _block_vspace = create_vspace(count, sizeof(BlockData));
  if (_block_vspace != 0) {
    _block_data = (BlockData*)_block_vspace->reserved_low_addr();
    _block_count = count;
    return true;
  }
  return false;
}

D
duke 已提交
452 453
void ParallelCompactData::clear()
{
454
  memset(_region_data, 0, _region_vspace->committed_size());
455
  memset(_block_data, 0, _block_vspace->committed_size());
D
duke 已提交
456 457
}

458 459 460
void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
  assert(beg_region <= _region_count, "beg_region out of range");
  assert(end_region <= _region_count, "end_region out of range");
461
  assert(RegionSize % BlockSize == 0, "RegionSize not a multiple of BlockSize");
D
duke 已提交
462

463 464
  const size_t region_cnt = end_region - beg_region;
  memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));
465 466 467 468

  const size_t beg_block = beg_region * BlocksPerRegion;
  const size_t block_cnt = region_cnt * BlocksPerRegion;
  memset(_block_data + beg_block, 0, block_cnt * sizeof(BlockData));
D
duke 已提交
469 470
}

471
HeapWord* ParallelCompactData::partial_obj_end(size_t region_idx) const
D
duke 已提交
472
{
473 474
  const RegionData* cur_cp = region(region_idx);
  const RegionData* const end_cp = region(region_count() - 1);
D
duke 已提交
475

476
  HeapWord* result = region_to_addr(region_idx);
D
duke 已提交
477 478 479
  if (cur_cp < end_cp) {
    do {
      result += cur_cp->partial_obj_size();
480
    } while (cur_cp->partial_obj_size() == RegionSize && ++cur_cp < end_cp);
D
duke 已提交
481 482 483 484 485 486 487
  }
  return result;
}

void ParallelCompactData::add_obj(HeapWord* addr, size_t len)
{
  const size_t obj_ofs = pointer_delta(addr, _region_start);
488 489
  const size_t beg_region = obj_ofs >> Log2RegionSize;
  const size_t end_region = (obj_ofs + len - 1) >> Log2RegionSize;
D
duke 已提交
490 491 492 493

  DEBUG_ONLY(Atomic::inc_ptr(&add_obj_count);)
  DEBUG_ONLY(Atomic::add_ptr(len, &add_obj_size);)

494 495 496
  if (beg_region == end_region) {
    // All in one region.
    _region_data[beg_region].add_live_obj(len);
D
duke 已提交
497 498 499
    return;
  }

500 501 502
  // First region.
  const size_t beg_ofs = region_offset(addr);
  _region_data[beg_region].add_live_obj(RegionSize - beg_ofs);
D
duke 已提交
503

504
  Klass* klass = ((oop)addr)->klass();
505 506 507 508
  // Middle regions--completely spanned by this object.
  for (size_t region = beg_region + 1; region < end_region; ++region) {
    _region_data[region].set_partial_obj_size(RegionSize);
    _region_data[region].set_partial_obj_addr(addr);
D
duke 已提交
509 510
  }

511 512 513 514
  // Last region.
  const size_t end_ofs = region_offset(addr + len - 1);
  _region_data[end_region].set_partial_obj_size(end_ofs + 1);
  _region_data[end_region].set_partial_obj_addr(addr);
D
duke 已提交
515 516 517 518 519
}

void
ParallelCompactData::summarize_dense_prefix(HeapWord* beg, HeapWord* end)
{
520 521
  assert(region_offset(beg) == 0, "not RegionSize aligned");
  assert(region_offset(end) == 0, "not RegionSize aligned");
D
duke 已提交
522

523 524
  size_t cur_region = addr_to_region_idx(beg);
  const size_t end_region = addr_to_region_idx(end);
D
duke 已提交
525
  HeapWord* addr = beg;
526 527 528 529 530
  while (cur_region < end_region) {
    _region_data[cur_region].set_destination(addr);
    _region_data[cur_region].set_destination_count(0);
    _region_data[cur_region].set_source_region(cur_region);
    _region_data[cur_region].set_data_location(addr);
D
duke 已提交
531

532 533 534
    // Update live_obj_size so the region appears completely full.
    size_t live_size = RegionSize - _region_data[cur_region].partial_obj_size();
    _region_data[cur_region].set_live_obj_size(live_size);
D
duke 已提交
535

536 537
    ++cur_region;
    addr += RegionSize;
D
duke 已提交
538 539 540
  }
}

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
// Find the point at which a space can be split and, if necessary, record the
// split point.
//
// If the current src region (which overflowed the destination space) doesn't
// have a partial object, the split point is at the beginning of the current src
// region (an "easy" split, no extra bookkeeping required).
//
// If the current src region has a partial object, the split point is in the
// region where that partial object starts (call it the split_region).  If
// split_region has a partial object, then the split point is just after that
// partial object (a "hard" split where we have to record the split data and
// zero the partial_obj_size field).  With a "hard" split, we know that the
// partial_obj ends within split_region because the partial object that caused
// the overflow starts in split_region.  If split_region doesn't have a partial
// obj, then the split is at the beginning of split_region (another "easy"
// split).
HeapWord*
ParallelCompactData::summarize_split_space(size_t src_region,
                                           SplitInfo& split_info,
                                           HeapWord* destination,
                                           HeapWord* target_end,
                                           HeapWord** target_next)
{
  assert(destination <= target_end, "sanity");
  assert(destination + _region_data[src_region].data_size() > target_end,
    "region should not fit into target space");
567
  assert(is_region_aligned(target_end), "sanity");
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597

  size_t split_region = src_region;
  HeapWord* split_destination = destination;
  size_t partial_obj_size = _region_data[src_region].partial_obj_size();

  if (destination + partial_obj_size > target_end) {
    // The split point is just after the partial object (if any) in the
    // src_region that contains the start of the object that overflowed the
    // destination space.
    //
    // Find the start of the "overflow" object and set split_region to the
    // region containing it.
    HeapWord* const overflow_obj = _region_data[src_region].partial_obj_addr();
    split_region = addr_to_region_idx(overflow_obj);

    // Clear the source_region field of all destination regions whose first word
    // came from data after the split point (a non-null source_region field
    // implies a region must be filled).
    //
    // An alternative to the simple loop below:  clear during post_compact(),
    // which uses memcpy instead of individual stores, and is easy to
    // parallelize.  (The downside is that it clears the entire RegionData
    // object as opposed to just one field.)
    //
    // post_compact() would have to clear the summary data up to the highest
    // address that was written during the summary phase, which would be
    //
    //         max(top, max(new_top, clear_top))
    //
    // where clear_top is a new field in SpaceInfo.  Would have to set clear_top
598
    // to target_end.
599 600 601 602
    const RegionData* const sr = region(split_region);
    const size_t beg_idx =
      addr_to_region_idx(region_align_up(sr->destination() +
                                         sr->partial_obj_size()));
603
    const size_t end_idx = addr_to_region_idx(target_end);
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

    if (TraceParallelOldGCSummaryPhase) {
        gclog_or_tty->print_cr("split:  clearing source_region field in ["
                               SIZE_FORMAT ", " SIZE_FORMAT ")",
                               beg_idx, end_idx);
    }
    for (size_t idx = beg_idx; idx < end_idx; ++idx) {
      _region_data[idx].set_source_region(0);
    }

    // Set split_destination and partial_obj_size to reflect the split region.
    split_destination = sr->destination();
    partial_obj_size = sr->partial_obj_size();
  }

  // The split is recorded only if a partial object extends onto the region.
  if (partial_obj_size != 0) {
    _region_data[split_region].set_partial_obj_size(0);
    split_info.record(split_region, partial_obj_size, split_destination);
  }

  // Setup the continuation addresses.
  *target_next = split_destination + partial_obj_size;
  HeapWord* const source_next = region_to_addr(split_region) + partial_obj_size;
D
duke 已提交
628 629

  if (TraceParallelOldGCSummaryPhase) {
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    const char * split_type = partial_obj_size == 0 ? "easy" : "hard";
    gclog_or_tty->print_cr("%s split:  src=" PTR_FORMAT " src_c=" SIZE_FORMAT
                           " pos=" SIZE_FORMAT,
                           split_type, source_next, split_region,
                           partial_obj_size);
    gclog_or_tty->print_cr("%s split:  dst=" PTR_FORMAT " dst_c=" SIZE_FORMAT
                           " tn=" PTR_FORMAT,
                           split_type, split_destination,
                           addr_to_region_idx(split_destination),
                           *target_next);

    if (partial_obj_size != 0) {
      HeapWord* const po_beg = split_info.destination();
      HeapWord* const po_end = po_beg + split_info.partial_obj_size();
      gclog_or_tty->print_cr("%s split:  "
                             "po_beg=" PTR_FORMAT " " SIZE_FORMAT " "
                             "po_end=" PTR_FORMAT " " SIZE_FORMAT,
                             split_type,
                             po_beg, addr_to_region_idx(po_beg),
                             po_end, addr_to_region_idx(po_end));
    }
  }

  return source_next;
}

bool ParallelCompactData::summarize(SplitInfo& split_info,
                                    HeapWord* source_beg, HeapWord* source_end,
                                    HeapWord** source_next,
                                    HeapWord* target_beg, HeapWord* target_end,
                                    HeapWord** target_next)
{
  if (TraceParallelOldGCSummaryPhase) {
    HeapWord* const source_next_val = source_next == NULL ? NULL : *source_next;
    tty->print_cr("sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
                  "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
                  source_beg, source_end, source_next_val,
                  target_beg, target_end, *target_next);
D
duke 已提交
668 669
  }

670 671
  size_t cur_region = addr_to_region_idx(source_beg);
  const size_t end_region = addr_to_region_idx(region_align_up(source_end));
D
duke 已提交
672 673

  HeapWord *dest_addr = target_beg;
674
  while (cur_region < end_region) {
675
    // The destination must be set even if the region has no data.
676
    _region_data[cur_region].set_destination(dest_addr);
D
duke 已提交
677

678
    size_t words = _region_data[cur_region].data_size();
D
duke 已提交
679
    if (words > 0) {
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
      // If cur_region does not fit entirely into the target space, find a point
      // at which the source space can be 'split' so that part is copied to the
      // target space and the rest is copied elsewhere.
      if (dest_addr + words > target_end) {
        assert(source_next != NULL, "source_next is NULL when splitting");
        *source_next = summarize_split_space(cur_region, split_info, dest_addr,
                                             target_end, target_next);
        return false;
      }

      // Compute the destination_count for cur_region, and if necessary, update
      // source_region for a destination region.  The source_region field is
      // updated if cur_region is the first (left-most) region to be copied to a
      // destination region.
      //
      // The destination_count calculation is a bit subtle.  A region that has
      // data that compacts into itself does not count itself as a destination.
      // This maintains the invariant that a zero count means the region is
      // available and can be claimed and then filled.
      uint destination_count = 0;
      if (split_info.is_split(cur_region)) {
        // The current region has been split:  the partial object will be copied
        // to one destination space and the remaining data will be copied to
        // another destination space.  Adjust the initial destination_count and,
        // if necessary, set the source_region field if the partial object will
        // cross a destination region boundary.
        destination_count = split_info.destination_count();
        if (destination_count == 2) {
          size_t dest_idx = addr_to_region_idx(split_info.dest_region_addr());
          _region_data[dest_idx].set_source_region(cur_region);
        }
      }

D
duke 已提交
713
      HeapWord* const last_addr = dest_addr + words - 1;
714 715
      const size_t dest_region_1 = addr_to_region_idx(dest_addr);
      const size_t dest_region_2 = addr_to_region_idx(last_addr);
716

717
      // Initially assume that the destination regions will be the same and
D
duke 已提交
718
      // adjust the value below if necessary.  Under this assumption, if
719 720
      // cur_region == dest_region_2, then cur_region will be compacted
      // completely into itself.
721
      destination_count += cur_region == dest_region_2 ? 0 : 1;
722 723
      if (dest_region_1 != dest_region_2) {
        // Destination regions differ; adjust destination_count.
D
duke 已提交
724
        destination_count += 1;
725 726 727 728 729 730
        // Data from cur_region will be copied to the start of dest_region_2.
        _region_data[dest_region_2].set_source_region(cur_region);
      } else if (region_offset(dest_addr) == 0) {
        // Data from cur_region will be copied to the start of the destination
        // region.
        _region_data[dest_region_1].set_source_region(cur_region);
D
duke 已提交
731 732
      }

733 734
      _region_data[cur_region].set_destination_count(destination_count);
      _region_data[cur_region].set_data_location(region_to_addr(cur_region));
D
duke 已提交
735 736 737
      dest_addr += words;
    }

738
    ++cur_region;
D
duke 已提交
739 740 741 742 743 744 745 746
  }

  *target_next = dest_addr;
  return true;
}

HeapWord* ParallelCompactData::calc_new_pointer(HeapWord* addr) {
  assert(addr != NULL, "Should detect NULL oop earlier");
747 748
  assert(PSParallelCompact::gc_heap()->is_in(addr), "not in heap");
  assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "not marked");
D
duke 已提交
749

750
  // Region covering the object.
751
  RegionData* const region_ptr = addr_to_region_ptr(addr);
752
  HeapWord* result = region_ptr->destination();
D
duke 已提交
753

754 755 756 757 758 759 760
  // If the entire Region is live, the new location is region->destination + the
  // offset of the object within in the Region.

  // Run some performance tests to determine if this special case pays off.  It
  // is worth it for pointers into the dense prefix.  If the optimization to
  // avoid pointer updates in regions that only point to the dense prefix is
  // ever implemented, this should be revisited.
761
  if (region_ptr->data_size() == RegionSize) {
762
    result += region_offset(addr);
D
duke 已提交
763 764 765
    return result;
  }

766 767 768
  // Otherwise, the new location is region->destination + block offset + the
  // number of live words in the Block that are (a) to the left of addr and (b)
  // due to objects that start in the Block.
D
duke 已提交
769

770 771 772 773 774 775 776 777 778 779
  // Fill in the block table if necessary.  This is unsynchronized, so multiple
  // threads may fill the block table for a region (harmless, since it is
  // idempotent).
  if (!region_ptr->blocks_filled()) {
    PSParallelCompact::fill_blocks(addr_to_region_idx(addr));
    region_ptr->set_blocks_filled();
  }

  HeapWord* const search_start = block_align_down(addr);
  const size_t block_offset = addr_to_block_ptr(addr)->offset();
D
duke 已提交
780

781 782 783 784
  const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();
  const size_t live = bitmap->live_words_in_range(search_start, oop(addr));
  result += block_offset + live;
  DEBUG_ONLY(PSParallelCompact::check_new_location(addr, result));
D
duke 已提交
785 786 787
  return result;
}

788
#ifdef ASSERT
D
duke 已提交
789 790 791 792 793 794 795 796 797 798 799
void ParallelCompactData::verify_clear(const PSVirtualSpace* vspace)
{
  const size_t* const beg = (const size_t*)vspace->committed_low_addr();
  const size_t* const end = (const size_t*)vspace->committed_high_addr();
  for (const size_t* p = beg; p < end; ++p) {
    assert(*p == 0, "not zero");
  }
}

void ParallelCompactData::verify_clear()
{
800
  verify_clear(_region_vspace);
801
  verify_clear(_block_vspace);
D
duke 已提交
802 803 804
}
#endif  // #ifdef ASSERT

S
sla 已提交
805 806
STWGCTimer          PSParallelCompact::_gc_timer;
ParallelOldTracer   PSParallelCompact::_gc_tracer;
D
duke 已提交
807 808 809 810 811 812 813 814 815
elapsedTimer        PSParallelCompact::_accumulated_time;
unsigned int        PSParallelCompact::_total_invocations = 0;
unsigned int        PSParallelCompact::_maximum_compaction_gc_num = 0;
jlong               PSParallelCompact::_time_of_last_gc = 0;
CollectorCounters*  PSParallelCompact::_counters = NULL;
ParMarkBitMap       PSParallelCompact::_mark_bitmap;
ParallelCompactData PSParallelCompact::_summary_data;

PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
816 817 818 819 820 821

bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }

void PSParallelCompact::KeepAliveClosure::do_oop(oop* p)       { PSParallelCompact::KeepAliveClosure::do_oop_work(p); }
void PSParallelCompact::KeepAliveClosure::do_oop(narrowOop* p) { PSParallelCompact::KeepAliveClosure::do_oop_work(p); }

822
PSParallelCompact::AdjustPointerClosure PSParallelCompact::_adjust_pointer_closure;
823
PSParallelCompact::AdjustKlassClosure PSParallelCompact::_adjust_klass_closure;
D
duke 已提交
824

825 826
void PSParallelCompact::AdjustPointerClosure::do_oop(oop* p)       { adjust_pointer(p); }
void PSParallelCompact::AdjustPointerClosure::do_oop(narrowOop* p) { adjust_pointer(p); }
D
duke 已提交
827

828
void PSParallelCompact::FollowStackClosure::do_void() { _compaction_manager->follow_marking_stacks(); }
D
duke 已提交
829

830 831 832
void PSParallelCompact::MarkAndPushClosure::do_oop(oop* p)       {
  mark_and_push(_compaction_manager, p);
}
833
void PSParallelCompact::MarkAndPushClosure::do_oop(narrowOop* p) { mark_and_push(_compaction_manager, p); }
D
duke 已提交
834

835 836 837 838
void PSParallelCompact::FollowKlassClosure::do_klass(Klass* klass) {
  klass->oops_do(_mark_and_push_closure);
}
void PSParallelCompact::AdjustKlassClosure::do_klass(Klass* klass) {
839
  klass->oops_do(&PSParallelCompact::_adjust_pointer_closure);
840 841
}

D
duke 已提交
842 843 844 845 846
void PSParallelCompact::post_initialize() {
  ParallelScavengeHeap* heap = gc_heap();
  assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");

  MemRegion mr = heap->reserved_region();
847 848 849 850 851 852 853 854 855
  _ref_processor =
    new ReferenceProcessor(mr,            // span
                           ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing
                           (int) ParallelGCThreads, // mt processing degree
                           true,          // mt discovery
                           (int) ParallelGCThreads, // mt discovery degree
                           true,          // atomic_discovery
                           &_is_alive_closure, // non-header is alive closure
                           false);        // write barrier for next field updates
D
duke 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
  _counters = new CollectorCounters("PSParallelCompact", 1);

  // Initialize static fields in ParCompactionManager.
  ParCompactionManager::initialize(mark_bitmap());
}

bool PSParallelCompact::initialize() {
  ParallelScavengeHeap* heap = gc_heap();
  assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
  MemRegion mr = heap->reserved_region();

  // Was the old gen get allocated successfully?
  if (!heap->old_gen()->is_allocated()) {
    return false;
  }

  initialize_space_info();
  initialize_dead_wood_limiter();

  if (!_mark_bitmap.initialize(mr)) {
876 877 878 879
    vm_shutdown_during_initialization(
      err_msg("Unable to allocate " SIZE_FORMAT "KB bitmaps for parallel "
      "garbage collection for the requested " SIZE_FORMAT "KB heap.",
      _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
D
duke 已提交
880 881 882 883
    return false;
  }

  if (!_summary_data.initialize(mr)) {
884 885 886 887
    vm_shutdown_during_initialization(
      err_msg("Unable to allocate " SIZE_FORMAT "KB card tables for parallel "
      "garbage collection for the requested " SIZE_FORMAT "KB heap.",
      _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
D
duke 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
    return false;
  }

  return true;
}

void PSParallelCompact::initialize_space_info()
{
  memset(&_space_info, 0, sizeof(_space_info));

  ParallelScavengeHeap* heap = gc_heap();
  PSYoungGen* young_gen = heap->young_gen();

  _space_info[old_space_id].set_space(heap->old_gen()->object_space());
  _space_info[eden_space_id].set_space(young_gen->eden_space());
  _space_info[from_space_id].set_space(young_gen->from_space());
  _space_info[to_space_id].set_space(young_gen->to_space());

  _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
}

void PSParallelCompact::initialize_dead_wood_limiter()
{
  const size_t max = 100;
  _dwl_mean = double(MIN2(ParallelOldDeadWoodLimiterMean, max)) / 100.0;
  _dwl_std_dev = double(MIN2(ParallelOldDeadWoodLimiterStdDev, max)) / 100.0;
  _dwl_first_term = 1.0 / (sqrt(2.0 * M_PI) * _dwl_std_dev);
  DEBUG_ONLY(_dwl_initialized = true;)
  _dwl_adjustment = normal_distribution(1.0);
}

// Simple class for storing info about the heap at the start of GC, to be used
// after GC for comparison/printing.
class PreGCValues {
public:
  PreGCValues() { }
  PreGCValues(ParallelScavengeHeap* heap) { fill(heap); }

  void fill(ParallelScavengeHeap* heap) {
    _heap_used      = heap->used();
    _young_gen_used = heap->young_gen()->used_in_bytes();
    _old_gen_used   = heap->old_gen()->used_in_bytes();
930
    _metadata_used  = MetaspaceAux::allocated_used_bytes();
D
duke 已提交
931 932 933 934 935
  };

  size_t heap_used() const      { return _heap_used; }
  size_t young_gen_used() const { return _young_gen_used; }
  size_t old_gen_used() const   { return _old_gen_used; }
936
  size_t metadata_used() const  { return _metadata_used; }
D
duke 已提交
937 938 939 940 941

private:
  size_t _heap_used;
  size_t _young_gen_used;
  size_t _old_gen_used;
942
  size_t _metadata_used;
D
duke 已提交
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
};

void
PSParallelCompact::clear_data_covering_space(SpaceId id)
{
  // At this point, top is the value before GC, new_top() is the value that will
  // be set at the end of GC.  The marking bitmap is cleared to top; nothing
  // should be marked above top.  The summary data is cleared to the larger of
  // top & new_top.
  MutableSpace* const space = _space_info[id].space();
  HeapWord* const bot = space->bottom();
  HeapWord* const top = space->top();
  HeapWord* const max_top = MAX2(top, _space_info[id].new_top());

  const idx_t beg_bit = _mark_bitmap.addr_to_bit(bot);
  const idx_t end_bit = BitMap::word_align_up(_mark_bitmap.addr_to_bit(top));
  _mark_bitmap.clear_range(beg_bit, end_bit);

961 962 963 964
  const size_t beg_region = _summary_data.addr_to_region_idx(bot);
  const size_t end_region =
    _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
  _summary_data.clear_range(beg_region, end_region);
965 966 967 968 969 970 971

  // Clear the data used to 'split' regions.
  SplitInfo& split_info = _space_info[id].split_info();
  if (split_info.is_valid()) {
    split_info.clear();
  }
  DEBUG_ONLY(split_info.verify_clear();)
D
duke 已提交
972 973 974 975 976 977 978 979
}

void PSParallelCompact::pre_compact(PreGCValues* pre_gc_values)
{
  // Update the from & to space pointers in space_info, since they are swapped
  // at each young gen gc.  Do the update unconditionally (even though a
  // promotion failure does not swap spaces) because an unknown number of minor
  // collections will have swapped the spaces an unknown number of times.
S
sla 已提交
980
  GCTraceTime tm("pre compact", print_phases(), true, &_gc_timer);
D
duke 已提交
981 982 983 984 985 986 987 988 989 990
  ParallelScavengeHeap* heap = gc_heap();
  _space_info[from_space_id].set_space(heap->young_gen()->from_space());
  _space_info[to_space_id].set_space(heap->young_gen()->to_space());

  pre_gc_values->fill(heap);

  DEBUG_ONLY(add_obj_count = add_obj_size = 0;)
  DEBUG_ONLY(mark_bitmap_count = mark_bitmap_size = 0;)

  // Increment the invocation count
991
  heap->increment_total_collections(true);
D
duke 已提交
992 993 994 995

  // We need to track unique mark sweep invocations as well.
  _total_invocations++;

996
  heap->print_heap_before_gc();
S
sla 已提交
997
  heap->trace_heap_before_gc(&_gc_tracer);
D
duke 已提交
998 999 1000 1001 1002 1003 1004

  // Fill in TLABs
  heap->accumulate_statistics_all_tlabs();
  heap->ensure_parsability(true);  // retire TLABs

  if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
    HandleMark hm;  // Discard invalid handles created during verification
1005
    Universe::verify(" VerifyBeforeGC:");
D
duke 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  }

  // Verify object start arrays
  if (VerifyObjectStartArray &&
      VerifyBeforeGC) {
    heap->old_gen()->verify_object_start_array();
  }

  DEBUG_ONLY(mark_bitmap()->verify_clear();)
  DEBUG_ONLY(summary_data().verify_clear();)
J
jcoomes 已提交
1016 1017 1018

  // Have worker threads release resources the next time they run a task.
  gc_task_manager()->release_all_resources();
D
duke 已提交
1019 1020 1021 1022
}

void PSParallelCompact::post_compact()
{
S
sla 已提交
1023
  GCTraceTime tm("post compact", print_phases(), true, &_gc_timer);
D
duke 已提交
1024

1025
  for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1026
    // Clear the marking bitmap, summary data and split info.
D
duke 已提交
1027
    clear_data_covering_space(SpaceId(id));
1028 1029
    // Update top().  Must be done after clearing the bitmap and summary data.
    _space_info[id].publish_new_top();
D
duke 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  }

  MutableSpace* const eden_space = _space_info[eden_space_id].space();
  MutableSpace* const from_space = _space_info[from_space_id].space();
  MutableSpace* const to_space   = _space_info[to_space_id].space();

  ParallelScavengeHeap* heap = gc_heap();
  bool eden_empty = eden_space->is_empty();
  if (!eden_empty) {
    eden_empty = absorb_live_data_from_eden(heap->size_policy(),
                                            heap->young_gen(), heap->old_gen());
  }

  // Update heap occupancy information which is used as input to the soft ref
  // clearing policy at the next gc.
  Universe::update_heap_info_at_gc();

  bool young_gen_empty = eden_empty && from_space->is_empty() &&
    to_space->is_empty();

  BarrierSet* bs = heap->barrier_set();
  if (bs->is_a(BarrierSet::ModRef)) {
    ModRefBarrierSet* modBS = (ModRefBarrierSet*)bs;
    MemRegion old_mr = heap->old_gen()->reserved();

    if (young_gen_empty) {
1056
      modBS->clear(MemRegion(old_mr.start(), old_mr.end()));
D
duke 已提交
1057
    } else {
1058
      modBS->invalidate(MemRegion(old_mr.start(), old_mr.end()));
D
duke 已提交
1059 1060 1061
    }
  }

1062 1063
  // Delete metaspaces for unloaded class loaders and clean up loader_data graph
  ClassLoaderDataGraph::purge();
1064
  MetaspaceAux::verify_metrics();
1065

D
duke 已提交
1066 1067
  Threads::gc_epilogue();
  CodeCache::gc_epilogue();
1068
  JvmtiExport::gc_epilogue();
D
duke 已提交
1069 1070 1071 1072 1073

  COMPILER2_PRESENT(DerivedPointerTable::update_pointers());

  ref_processor()->enqueue_discovered_references(NULL);

1074 1075 1076 1077
  if (ZapUnusedHeapArea) {
    heap->gen_mangle_unused_area();
  }

D
duke 已提交
1078 1079 1080 1081 1082 1083 1084 1085
  // Update time of last GC
  reset_millis_since_last_gc();
}

HeapWord*
PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id,
                                                    bool maximum_compaction)
{
1086
  const size_t region_size = ParallelCompactData::RegionSize;
D
duke 已提交
1087 1088 1089
  const ParallelCompactData& sd = summary_data();

  const MutableSpace* const space = _space_info[id].space();
1090 1091 1092
  HeapWord* const top_aligned_up = sd.region_align_up(space->top());
  const RegionData* const beg_cp = sd.addr_to_region_ptr(space->bottom());
  const RegionData* const end_cp = sd.addr_to_region_ptr(top_aligned_up);
D
duke 已提交
1093

1094
  // Skip full regions at the beginning of the space--they are necessarily part
D
duke 已提交
1095 1096
  // of the dense prefix.
  size_t full_count = 0;
1097 1098
  const RegionData* cp;
  for (cp = beg_cp; cp < end_cp && cp->data_size() == region_size; ++cp) {
D
duke 已提交
1099 1100 1101 1102 1103 1104 1105 1106
    ++full_count;
  }

  assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");
  const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;
  const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval;
  if (maximum_compaction || cp == end_cp || interval_ended) {
    _maximum_compaction_gc_num = total_invocations();
1107
    return sd.region_to_addr(cp);
D
duke 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
  }

  HeapWord* const new_top = _space_info[id].new_top();
  const size_t space_live = pointer_delta(new_top, space->bottom());
  const size_t space_used = space->used_in_words();
  const size_t space_capacity = space->capacity_in_words();

  const double cur_density = double(space_live) / space_capacity;
  const double deadwood_density =
    (1.0 - cur_density) * (1.0 - cur_density) * cur_density * cur_density;
  const size_t deadwood_goal = size_t(space_capacity * deadwood_density);

  if (TraceParallelOldGCDensePrefix) {
    tty->print_cr("cur_dens=%5.3f dw_dens=%5.3f dw_goal=" SIZE_FORMAT,
                  cur_density, deadwood_density, deadwood_goal);
    tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "
                  "space_cap=" SIZE_FORMAT,
                  space_live, space_used,
                  space_capacity);
  }

  // XXX - Use binary search?
1130 1131 1132
  HeapWord* dense_prefix = sd.region_to_addr(cp);
  const RegionData* full_cp = cp;
  const RegionData* const top_cp = sd.addr_to_region_ptr(space->top() - 1);
D
duke 已提交
1133
  while (cp < end_cp) {
1134 1135
    HeapWord* region_destination = cp->destination();
    const size_t cur_deadwood = pointer_delta(dense_prefix, region_destination);
D
duke 已提交
1136
    if (TraceParallelOldGCDensePrefix && Verbose) {
1137 1138
      tty->print_cr("c#=" SIZE_FORMAT_W(4) " dst=" PTR_FORMAT " "
                    "dp=" SIZE_FORMAT_W(8) " " "cdw=" SIZE_FORMAT_W(8),
1139
                    sd.region(cp), region_destination,
D
duke 已提交
1140 1141 1142 1143
                    dense_prefix, cur_deadwood);
    }

    if (cur_deadwood >= deadwood_goal) {
1144 1145 1146 1147 1148
      // Found the region that has the correct amount of deadwood to the left.
      // This typically occurs after crossing a fairly sparse set of regions, so
      // iterate backwards over those sparse regions, looking for the region
      // that has the lowest density of live objects 'to the right.'
      size_t space_to_left = sd.region(cp) * region_size;
D
duke 已提交
1149 1150 1151 1152 1153 1154
      size_t live_to_left = space_to_left - cur_deadwood;
      size_t space_to_right = space_capacity - space_to_left;
      size_t live_to_right = space_live - live_to_left;
      double density_to_right = double(live_to_right) / space_to_right;
      while (cp > full_cp) {
        --cp;
1155 1156 1157 1158 1159 1160
        const size_t prev_region_live_to_right = live_to_right -
          cp->data_size();
        const size_t prev_region_space_to_right = space_to_right + region_size;
        double prev_region_density_to_right =
          double(prev_region_live_to_right) / prev_region_space_to_right;
        if (density_to_right <= prev_region_density_to_right) {
D
duke 已提交
1161 1162 1163
          return dense_prefix;
        }
        if (TraceParallelOldGCDensePrefix && Verbose) {
1164
          tty->print_cr("backing up from c=" SIZE_FORMAT_W(4) " d2r=%10.8f "
1165 1166
                        "pc_d2r=%10.8f", sd.region(cp), density_to_right,
                        prev_region_density_to_right);
D
duke 已提交
1167
        }
1168 1169 1170 1171
        dense_prefix -= region_size;
        live_to_right = prev_region_live_to_right;
        space_to_right = prev_region_space_to_right;
        density_to_right = prev_region_density_to_right;
D
duke 已提交
1172 1173 1174 1175
      }
      return dense_prefix;
    }

1176
    dense_prefix += region_size;
D
duke 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    ++cp;
  }

  return dense_prefix;
}

#ifndef PRODUCT
void PSParallelCompact::print_dense_prefix_stats(const char* const algorithm,
                                                 const SpaceId id,
                                                 const bool maximum_compaction,
                                                 HeapWord* const addr)
{
1189 1190
  const size_t region_idx = summary_data().addr_to_region_idx(addr);
  RegionData* const cp = summary_data().region(region_idx);
D
duke 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
  const MutableSpace* const space = _space_info[id].space();
  HeapWord* const new_top = _space_info[id].new_top();

  const size_t space_live = pointer_delta(new_top, space->bottom());
  const size_t dead_to_left = pointer_delta(addr, cp->destination());
  const size_t space_cap = space->capacity_in_words();
  const double dead_to_left_pct = double(dead_to_left) / space_cap;
  const size_t live_to_right = new_top - cp->destination();
  const size_t dead_to_right = space->top() - addr - live_to_right;

1201
  tty->print_cr("%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W(5) " "
D
duke 已提交
1202 1203 1204 1205
                "spl=" SIZE_FORMAT " "
                "d2l=" SIZE_FORMAT " d2l%%=%6.4f "
                "d2r=" SIZE_FORMAT " l2r=" SIZE_FORMAT
                " ratio=%10.8f",
1206
                algorithm, addr, region_idx,
D
duke 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
                space_live,
                dead_to_left, dead_to_left_pct,
                dead_to_right, live_to_right,
                double(dead_to_right) / live_to_right);
}
#endif  // #ifndef PRODUCT

// Return a fraction indicating how much of the generation can be treated as
// "dead wood" (i.e., not reclaimed).  The function uses a normal distribution
// based on the density of live objects in the generation to determine a limit,
// which is then adjusted so the return value is min_percent when the density is
// 1.
//
// The following table shows some return values for a different values of the
// standard deviation (ParallelOldDeadWoodLimiterStdDev); the mean is 0.5 and
// min_percent is 1.
//
//                          fraction allowed as dead wood
//         -----------------------------------------------------------------
// density std_dev=70 std_dev=75 std_dev=80 std_dev=85 std_dev=90 std_dev=95
// ------- ---------- ---------- ---------- ---------- ---------- ----------
// 0.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
// 0.05000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
// 0.10000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
// 0.15000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
// 0.20000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
// 0.25000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
// 0.30000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
// 0.35000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
// 0.40000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
// 0.45000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
// 0.50000 0.13832410 0.11599237 0.09847664 0.08456518 0.07338887 0.06431510
// 0.55000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
// 0.60000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
// 0.65000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
// 0.70000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
// 0.75000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
// 0.80000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
// 0.85000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
// 0.90000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
// 0.95000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
// 1.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000

double PSParallelCompact::dead_wood_limiter(double density, size_t min_percent)
{
  assert(_dwl_initialized, "uninitialized");

  // The raw limit is the value of the normal distribution at x = density.
  const double raw_limit = normal_distribution(density);

  // Adjust the raw limit so it becomes the minimum when the density is 1.
  //
  // First subtract the adjustment value (which is simply the precomputed value
  // normal_distribution(1.0)); this yields a value of 0 when the density is 1.
  // Then add the minimum value, so the minimum is returned when the density is
  // 1.  Finally, prevent negative values, which occur when the mean is not 0.5.
  const double min = double(min_percent) / 100.0;
  const double limit = raw_limit - _dwl_adjustment + min;
  return MAX2(limit, 0.0);
}

1268 1269 1270
ParallelCompactData::RegionData*
PSParallelCompact::first_dead_space_region(const RegionData* beg,
                                           const RegionData* end)
D
duke 已提交
1271
{
1272
  const size_t region_size = ParallelCompactData::RegionSize;
D
duke 已提交
1273
  ParallelCompactData& sd = summary_data();
1274 1275
  size_t left = sd.region(beg);
  size_t right = end > beg ? sd.region(end) - 1 : left;
D
duke 已提交
1276 1277 1278 1279 1280

  // Binary search.
  while (left < right) {
    // Equivalent to (left + right) / 2, but does not overflow.
    const size_t middle = left + (right - left) / 2;
1281
    RegionData* const middle_ptr = sd.region(middle);
D
duke 已提交
1282
    HeapWord* const dest = middle_ptr->destination();
1283
    HeapWord* const addr = sd.region_to_addr(middle);
D
duke 已提交
1284 1285 1286 1287 1288
    assert(dest != NULL, "sanity");
    assert(dest <= addr, "must move left");

    if (middle > left && dest < addr) {
      right = middle - 1;
1289
    } else if (middle < right && middle_ptr->data_size() == region_size) {
D
duke 已提交
1290 1291 1292 1293 1294
      left = middle + 1;
    } else {
      return middle_ptr;
    }
  }
1295
  return sd.region(left);
D
duke 已提交
1296 1297
}

1298 1299 1300 1301
ParallelCompactData::RegionData*
PSParallelCompact::dead_wood_limit_region(const RegionData* beg,
                                          const RegionData* end,
                                          size_t dead_words)
D
duke 已提交
1302 1303
{
  ParallelCompactData& sd = summary_data();
1304 1305
  size_t left = sd.region(beg);
  size_t right = end > beg ? sd.region(end) - 1 : left;
D
duke 已提交
1306 1307 1308 1309 1310

  // Binary search.
  while (left < right) {
    // Equivalent to (left + right) / 2, but does not overflow.
    const size_t middle = left + (right - left) / 2;
1311
    RegionData* const middle_ptr = sd.region(middle);
D
duke 已提交
1312
    HeapWord* const dest = middle_ptr->destination();
1313
    HeapWord* const addr = sd.region_to_addr(middle);
D
duke 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    assert(dest != NULL, "sanity");
    assert(dest <= addr, "must move left");

    const size_t dead_to_left = pointer_delta(addr, dest);
    if (middle > left && dead_to_left > dead_words) {
      right = middle - 1;
    } else if (middle < right && dead_to_left < dead_words) {
      left = middle + 1;
    } else {
      return middle_ptr;
    }
  }
1326
  return sd.region(left);
D
duke 已提交
1327 1328 1329 1330 1331
}

// The result is valid during the summary phase, after the initial summarization
// of each space into itself, and before final summarization.
inline double
1332
PSParallelCompact::reclaimed_ratio(const RegionData* const cp,
D
duke 已提交
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
                                   HeapWord* const bottom,
                                   HeapWord* const top,
                                   HeapWord* const new_top)
{
  ParallelCompactData& sd = summary_data();

  assert(cp != NULL, "sanity");
  assert(bottom != NULL, "sanity");
  assert(top != NULL, "sanity");
  assert(new_top != NULL, "sanity");
  assert(top >= new_top, "summary data problem?");
  assert(new_top > bottom, "space is empty; should not be here");
  assert(new_top >= cp->destination(), "sanity");
1346
  assert(top >= sd.region_to_addr(cp), "sanity");
D
duke 已提交
1347 1348 1349 1350

  HeapWord* const destination = cp->destination();
  const size_t dense_prefix_live  = pointer_delta(destination, bottom);
  const size_t compacted_region_live = pointer_delta(new_top, destination);
1351 1352
  const size_t compacted_region_used = pointer_delta(top,
                                                     sd.region_to_addr(cp));
D
duke 已提交
1353 1354 1355 1356 1357 1358 1359
  const size_t reclaimable = compacted_region_used - compacted_region_live;

  const double divisor = dense_prefix_live + 1.25 * compacted_region_live;
  return double(reclaimable) / divisor;
}

// Return the address of the end of the dense prefix, a.k.a. the start of the
1360
// compacted region.  The address is always on a region boundary.
D
duke 已提交
1361
//
1362 1363 1364 1365 1366 1367 1368
// Completely full regions at the left are skipped, since no compaction can
// occur in those regions.  Then the maximum amount of dead wood to allow is
// computed, based on the density (amount live / capacity) of the generation;
// the region with approximately that amount of dead space to the left is
// identified as the limit region.  Regions between the last completely full
// region and the limit region are scanned and the one that has the best
// (maximum) reclaimed_ratio() is selected.
D
duke 已提交
1369 1370 1371 1372
HeapWord*
PSParallelCompact::compute_dense_prefix(const SpaceId id,
                                        bool maximum_compaction)
{
1373 1374 1375 1376 1377 1378 1379
  if (ParallelOldGCSplitALot) {
    if (_space_info[id].dense_prefix() != _space_info[id].space()->bottom()) {
      // The value was chosen to provoke splitting a young gen space; use it.
      return _space_info[id].dense_prefix();
    }
  }

1380
  const size_t region_size = ParallelCompactData::RegionSize;
D
duke 已提交
1381 1382 1383 1384
  const ParallelCompactData& sd = summary_data();

  const MutableSpace* const space = _space_info[id].space();
  HeapWord* const top = space->top();
1385
  HeapWord* const top_aligned_up = sd.region_align_up(top);
D
duke 已提交
1386
  HeapWord* const new_top = _space_info[id].new_top();
1387
  HeapWord* const new_top_aligned_up = sd.region_align_up(new_top);
D
duke 已提交
1388
  HeapWord* const bottom = space->bottom();
1389 1390 1391 1392
  const RegionData* const beg_cp = sd.addr_to_region_ptr(bottom);
  const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
  const RegionData* const new_top_cp =
    sd.addr_to_region_ptr(new_top_aligned_up);
D
duke 已提交
1393

1394
  // Skip full regions at the beginning of the space--they are necessarily part
D
duke 已提交
1395
  // of the dense prefix.
1396 1397
  const RegionData* const full_cp = first_dead_space_region(beg_cp, new_top_cp);
  assert(full_cp->destination() == sd.region_to_addr(full_cp) ||
D
duke 已提交
1398
         space->is_empty(), "no dead space allowed to the left");
1399 1400
  assert(full_cp->data_size() < region_size || full_cp == new_top_cp - 1,
         "region must have dead space");
D
duke 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410

  // The gc number is saved whenever a maximum compaction is done, and used to
  // determine when the maximum compaction interval has expired.  This avoids
  // successive max compactions for different reasons.
  assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");
  const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;
  const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval ||
    total_invocations() == HeapFirstMaximumCompactionCount;
  if (maximum_compaction || full_cp == top_cp || interval_ended) {
    _maximum_compaction_gc_num = total_invocations();
1411
    return sd.region_to_addr(full_cp);
D
duke 已提交
1412 1413 1414 1415 1416 1417 1418
  }

  const size_t space_live = pointer_delta(new_top, bottom);
  const size_t space_used = space->used_in_words();
  const size_t space_capacity = space->capacity_in_words();

  const double density = double(space_live) / double(space_capacity);
1419
  const size_t min_percent_free = MarkSweepDeadRatio;
D
duke 已提交
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
  const double limiter = dead_wood_limiter(density, min_percent_free);
  const size_t dead_wood_max = space_used - space_live;
  const size_t dead_wood_limit = MIN2(size_t(space_capacity * limiter),
                                      dead_wood_max);

  if (TraceParallelOldGCDensePrefix) {
    tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "
                  "space_cap=" SIZE_FORMAT,
                  space_live, space_used,
                  space_capacity);
    tty->print_cr("dead_wood_limiter(%6.4f, %d)=%6.4f "
                  "dead_wood_max=" SIZE_FORMAT " dead_wood_limit=" SIZE_FORMAT,
                  density, min_percent_free, limiter,
                  dead_wood_max, dead_wood_limit);
  }

1436 1437 1438
  // Locate the region with the desired amount of dead space to the left.
  const RegionData* const limit_cp =
    dead_wood_limit_region(full_cp, top_cp, dead_wood_limit);
D
duke 已提交
1439

1440
  // Scan from the first region with dead space to the limit region and find the
D
duke 已提交
1441 1442
  // one with the best (largest) reclaimed ratio.
  double best_ratio = 0.0;
1443 1444
  const RegionData* best_cp = full_cp;
  for (const RegionData* cp = full_cp; cp < limit_cp; ++cp) {
D
duke 已提交
1445 1446 1447 1448 1449 1450 1451 1452
    double tmp_ratio = reclaimed_ratio(cp, bottom, top, new_top);
    if (tmp_ratio > best_ratio) {
      best_cp = cp;
      best_ratio = tmp_ratio;
    }
  }

#if     0
1453 1454 1455
  // Something to consider:  if the region with the best ratio is 'close to' the
  // first region w/free space, choose the first region with free space
  // ("first-free").  The first-free region is usually near the start of the
D
duke 已提交
1456 1457
  // heap, which means we are copying most of the heap already, so copy a bit
  // more to get complete compaction.
1458
  if (pointer_delta(best_cp, full_cp, sizeof(RegionData)) < 4) {
D
duke 已提交
1459 1460 1461 1462 1463
    _maximum_compaction_gc_num = total_invocations();
    best_cp = full_cp;
  }
#endif  // #if 0

1464
  return sd.region_to_addr(best_cp);
D
duke 已提交
1465 1466
}

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
#ifndef PRODUCT
void
PSParallelCompact::fill_with_live_objects(SpaceId id, HeapWord* const start,
                                          size_t words)
{
  if (TraceParallelOldGCSummaryPhase) {
    tty->print_cr("fill_with_live_objects [" PTR_FORMAT " " PTR_FORMAT ") "
                  SIZE_FORMAT, start, start + words, words);
  }

  ObjectStartArray* const start_array = _space_info[id].start_array();
  CollectedHeap::fill_with_objects(start, words);
  for (HeapWord* p = start; p < start + words; p += oop(p)->size()) {
    _mark_bitmap.mark_obj(p, words);
    _summary_data.add_obj(p, words);
    start_array->allocate_block(p);
  }
}

void
PSParallelCompact::summarize_new_objects(SpaceId id, HeapWord* start)
{
  ParallelCompactData& sd = summary_data();
  MutableSpace* space = _space_info[id].space();

  // Find the source and destination start addresses.
  HeapWord* const src_addr = sd.region_align_down(start);
  HeapWord* dst_addr;
  if (src_addr < start) {
    dst_addr = sd.addr_to_region_ptr(src_addr)->destination();
  } else if (src_addr > space->bottom()) {
    // The start (the original top() value) is aligned to a region boundary so
    // the associated region does not have a destination.  Compute the
    // destination from the previous region.
    RegionData* const cp = sd.addr_to_region_ptr(src_addr) - 1;
    dst_addr = cp->destination() + cp->data_size();
  } else {
    // Filling the entire space.
    dst_addr = space->bottom();
  }
  assert(dst_addr != NULL, "sanity");

  // Update the summary data.
  bool result = _summary_data.summarize(_space_info[id].split_info(),
                                        src_addr, space->top(), NULL,
                                        dst_addr, space->end(),
                                        _space_info[id].new_top_addr());
  assert(result, "should not fail:  bad filler object size");
}

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
void
PSParallelCompact::provoke_split_fill_survivor(SpaceId id)
{
  if (total_invocations() % (ParallelOldGCSplitInterval * 3) != 0) {
    return;
  }

  MutableSpace* const space = _space_info[id].space();
  if (space->is_empty()) {
    HeapWord* b = space->bottom();
    HeapWord* t = b + space->capacity_in_words() / 2;
    space->set_top(t);
    if (ZapUnusedHeapArea) {
      space->set_top_for_allocations();
    }

1533 1534
    size_t min_size = CollectedHeap::min_fill_size();
    size_t obj_len = min_size;
1535 1536 1537 1538 1539
    while (b + obj_len <= t) {
      CollectedHeap::fill_with_object(b, obj_len);
      mark_bitmap()->mark_obj(b, obj_len);
      summary_data().add_obj(b, obj_len);
      b += obj_len;
1540
      obj_len = (obj_len & (min_size*3)) + min_size; // 8 16 24 32 8 16 24 32 ...
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
    }
    if (b < t) {
      // The loop didn't completely fill to t (top); adjust top downward.
      space->set_top(b);
      if (ZapUnusedHeapArea) {
        space->set_top_for_allocations();
      }
    }

    HeapWord** nta = _space_info[id].new_top_addr();
    bool result = summary_data().summarize(_space_info[id].split_info(),
                                           space->bottom(), space->top(), NULL,
                                           space->bottom(), space->end(), nta);
    assert(result, "space must fit into itself");
  }
}

1558 1559 1560
void
PSParallelCompact::provoke_split(bool & max_compaction)
{
1561 1562 1563 1564
  if (total_invocations() % ParallelOldGCSplitInterval != 0) {
    return;
  }

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
  const size_t region_size = ParallelCompactData::RegionSize;
  ParallelCompactData& sd = summary_data();

  MutableSpace* const eden_space = _space_info[eden_space_id].space();
  MutableSpace* const from_space = _space_info[from_space_id].space();
  const size_t eden_live = pointer_delta(eden_space->top(),
                                         _space_info[eden_space_id].new_top());
  const size_t from_live = pointer_delta(from_space->top(),
                                         _space_info[from_space_id].new_top());

  const size_t min_fill_size = CollectedHeap::min_fill_size();
  const size_t eden_free = pointer_delta(eden_space->end(), eden_space->top());
  const size_t eden_fillable = eden_free >= min_fill_size ? eden_free : 0;
  const size_t from_free = pointer_delta(from_space->end(), from_space->top());
  const size_t from_fillable = from_free >= min_fill_size ? from_free : 0;

  // Choose the space to split; need at least 2 regions live (or fillable).
  SpaceId id;
  MutableSpace* space;
  size_t live_words;
  size_t fill_words;
  if (eden_live + eden_fillable >= region_size * 2) {
    id = eden_space_id;
    space = eden_space;
    live_words = eden_live;
    fill_words = eden_fillable;
  } else if (from_live + from_fillable >= region_size * 2) {
    id = from_space_id;
    space = from_space;
    live_words = from_live;
    fill_words = from_fillable;
  } else {
    return; // Give up.
  }
  assert(fill_words == 0 || fill_words >= min_fill_size, "sanity");

  if (live_words < region_size * 2) {
    // Fill from top() to end() w/live objects of mixed sizes.
    HeapWord* const fill_start = space->top();
    live_words += fill_words;

    space->set_top(fill_start + fill_words);
    if (ZapUnusedHeapArea) {
      space->set_top_for_allocations();
    }

    HeapWord* cur_addr = fill_start;
    while (fill_words > 0) {
      const size_t r = (size_t)os::random() % (region_size / 2) + min_fill_size;
      size_t cur_size = MIN2(align_object_size_(r), fill_words);
      if (fill_words - cur_size < min_fill_size) {
        cur_size = fill_words; // Avoid leaving a fragment too small to fill.
      }

      CollectedHeap::fill_with_object(cur_addr, cur_size);
      mark_bitmap()->mark_obj(cur_addr, cur_size);
      sd.add_obj(cur_addr, cur_size);

      cur_addr += cur_size;
      fill_words -= cur_size;
    }

    summarize_new_objects(id, fill_start);
  }

  max_compaction = false;

  // Manipulate the old gen so that it has room for about half of the live data
  // in the target young gen space (live_words / 2).
  id = old_space_id;
  space = _space_info[id].space();
  const size_t free_at_end = space->free_in_words();
  const size_t free_target = align_object_size(live_words / 2);
  const size_t dead = pointer_delta(space->top(), _space_info[id].new_top());

  if (free_at_end >= free_target + min_fill_size) {
    // Fill space above top() and set the dense prefix so everything survives.
    HeapWord* const fill_start = space->top();
    const size_t fill_size = free_at_end - free_target;
    space->set_top(space->top() + fill_size);
    if (ZapUnusedHeapArea) {
      space->set_top_for_allocations();
    }
    fill_with_live_objects(id, fill_start, fill_size);
    summarize_new_objects(id, fill_start);
    _space_info[id].set_dense_prefix(sd.region_align_down(space->top()));
  } else if (dead + free_at_end > free_target) {
    // Find a dense prefix that makes the right amount of space available.
    HeapWord* cur = sd.region_align_down(space->top());
    HeapWord* cur_destination = sd.addr_to_region_ptr(cur)->destination();
    size_t dead_to_right = pointer_delta(space->end(), cur_destination);
    while (dead_to_right < free_target) {
      cur -= region_size;
      cur_destination = sd.addr_to_region_ptr(cur)->destination();
      dead_to_right = pointer_delta(space->end(), cur_destination);
    }
    _space_info[id].set_dense_prefix(cur);
  }
}
#endif // #ifndef PRODUCT

D
duke 已提交
1666 1667 1668 1669
void PSParallelCompact::summarize_spaces_quick()
{
  for (unsigned int i = 0; i < last_space_id; ++i) {
    const MutableSpace* space = _space_info[i].space();
1670 1671 1672 1673 1674
    HeapWord** nta = _space_info[i].new_top_addr();
    bool result = _summary_data.summarize(_space_info[i].split_info(),
                                          space->bottom(), space->top(), NULL,
                                          space->bottom(), space->end(), nta);
    assert(result, "space must fit into itself");
D
duke 已提交
1675 1676
    _space_info[i].set_dense_prefix(space->bottom());
  }
1677 1678 1679 1680 1681 1682

#ifndef PRODUCT
  if (ParallelOldGCSplitALot) {
    provoke_split_fill_survivor(to_space_id);
  }
#endif // #ifndef PRODUCT
D
duke 已提交
1683 1684 1685 1686 1687
}

void PSParallelCompact::fill_dense_prefix_end(SpaceId id)
{
  HeapWord* const dense_prefix_end = dense_prefix(id);
1688
  const RegionData* region = _summary_data.addr_to_region_ptr(dense_prefix_end);
D
duke 已提交
1689
  const idx_t dense_prefix_bit = _mark_bitmap.addr_to_bit(dense_prefix_end);
1690
  if (dead_space_crosses_boundary(region, dense_prefix_bit)) {
D
duke 已提交
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
    // Only enough dead space is filled so that any remaining dead space to the
    // left is larger than the minimum filler object.  (The remainder is filled
    // during the copy/update phase.)
    //
    // The size of the dead space to the right of the boundary is not a
    // concern, since compaction will be able to use whatever space is
    // available.
    //
    // Here '||' is the boundary, 'x' represents a don't care bit and a box
    // surrounds the space to be filled with an object.
    //
    // In the 32-bit VM, each bit represents two 32-bit words:
    //                              +---+
    // a) beg_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
    //    end_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
    //                              +---+
    //
    // In the 64-bit VM, each bit represents one 64-bit word:
    //                              +------------+
    // b) beg_bits:  ...  x   x   x | 0   ||   0 | x  x  ...
    //    end_bits:  ...  x   x   1 | 0   ||   0 | x  x  ...
    //                              +------------+
    //                          +-------+
    // c) beg_bits:  ...  x   x | 0   0 | ||   0   x  x  ...
    //    end_bits:  ...  x   1 | 0   0 | ||   0   x  x  ...
    //                          +-------+
    //                      +-----------+
    // d) beg_bits:  ...  x | 0   0   0 | ||   0   x  x  ...
    //    end_bits:  ...  1 | 0   0   0 | ||   0   x  x  ...
    //                      +-----------+
    //                          +-------+
    // e) beg_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
    //    end_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
    //                          +-------+

    // Initially assume case a, c or e will apply.
1727
    size_t obj_len = CollectedHeap::min_fill_size();
D
duke 已提交
1728 1729 1730
    HeapWord* obj_beg = dense_prefix_end - obj_len;

#ifdef  _LP64
1731 1732 1733
    if (MinObjAlignment > 1) { // object alignment > heap word size
      // Cases a, c or e.
    } else if (_mark_bitmap.is_obj_end(dense_prefix_bit - 2)) {
D
duke 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
      // Case b above.
      obj_beg = dense_prefix_end - 1;
    } else if (!_mark_bitmap.is_obj_end(dense_prefix_bit - 3) &&
               _mark_bitmap.is_obj_end(dense_prefix_bit - 4)) {
      // Case d above.
      obj_beg = dense_prefix_end - 3;
      obj_len = 3;
    }
#endif  // #ifdef _LP64

1744
    CollectedHeap::fill_with_object(obj_beg, obj_len);
D
duke 已提交
1745 1746 1747 1748 1749 1750 1751
    _mark_bitmap.mark_obj(obj_beg, obj_len);
    _summary_data.add_obj(obj_beg, obj_len);
    assert(start_array(id) != NULL, "sanity");
    start_array(id)->allocate_block(obj_beg);
  }
}

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
void
PSParallelCompact::clear_source_region(HeapWord* beg_addr, HeapWord* end_addr)
{
  RegionData* const beg_ptr = _summary_data.addr_to_region_ptr(beg_addr);
  HeapWord* const end_aligned_up = _summary_data.region_align_up(end_addr);
  RegionData* const end_ptr = _summary_data.addr_to_region_ptr(end_aligned_up);
  for (RegionData* cur = beg_ptr; cur < end_ptr; ++cur) {
    cur->set_source_region(0);
  }
}

D
duke 已提交
1763 1764 1765 1766
void
PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction)
{
  assert(id < last_space_id, "id out of range");
1767 1768 1769
  assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom() ||
         ParallelOldGCSplitALot && id == old_space_id,
         "should have been reset in summarize_spaces_quick()");
D
duke 已提交
1770 1771

  const MutableSpace* space = _space_info[id].space();
1772 1773 1774
  if (_space_info[id].new_top() != space->bottom()) {
    HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction);
    _space_info[id].set_dense_prefix(dense_prefix_end);
D
duke 已提交
1775 1776

#ifndef PRODUCT
1777 1778 1779 1780 1781 1782
    if (TraceParallelOldGCDensePrefix) {
      print_dense_prefix_stats("ratio", id, maximum_compaction,
                               dense_prefix_end);
      HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction);
      print_dense_prefix_stats("density", id, maximum_compaction, addr);
    }
D
duke 已提交
1783 1784
#endif  // #ifndef PRODUCT

1785 1786 1787
    // Recompute the summary data, taking into account the dense prefix.  If
    // every last byte will be reclaimed, then the existing summary data which
    // compacts everything can be left in place.
1788
    if (!maximum_compaction && dense_prefix_end != space->bottom()) {
1789 1790 1791
      // If dead space crosses the dense prefix boundary, it is (at least
      // partially) filled with a dummy object, marked live and added to the
      // summary data.  This simplifies the copy/update phase and must be done
1792 1793
      // before the final locations of objects are determined, to prevent
      // leaving a fragment of dead space that is too small to fill.
1794
      fill_dense_prefix_end(id);
D
duke 已提交
1795

1796 1797 1798 1799 1800 1801 1802
      // Compute the destination of each Region, and thus each object.
      _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end);
      _summary_data.summarize(_space_info[id].split_info(),
                              dense_prefix_end, space->top(), NULL,
                              dense_prefix_end, space->end(),
                              _space_info[id].new_top_addr());
    }
1803
  }
D
duke 已提交
1804 1805

  if (TraceParallelOldGCSummaryPhase) {
1806
    const size_t region_size = ParallelCompactData::RegionSize;
1807
    HeapWord* const dense_prefix_end = _space_info[id].dense_prefix();
1808
    const size_t dp_region = _summary_data.addr_to_region_idx(dense_prefix_end);
D
duke 已提交
1809
    const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom());
1810
    HeapWord* const new_top = _space_info[id].new_top();
1811
    const HeapWord* nt_aligned_up = _summary_data.region_align_up(new_top);
D
duke 已提交
1812 1813
    const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end);
    tty->print_cr("id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " "
1814
                  "dp_region=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " "
D
duke 已提交
1815 1816
                  "cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT,
                  id, space->capacity_in_words(), dense_prefix_end,
1817 1818
                  dp_region, dp_words / region_size,
                  cr_words / region_size, new_top);
D
duke 已提交
1819 1820 1821
  }
}

1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
#ifndef PRODUCT
void PSParallelCompact::summary_phase_msg(SpaceId dst_space_id,
                                          HeapWord* dst_beg, HeapWord* dst_end,
                                          SpaceId src_space_id,
                                          HeapWord* src_beg, HeapWord* src_end)
{
  if (TraceParallelOldGCSummaryPhase) {
    tty->print_cr("summarizing %d [%s] into %d [%s]:  "
                  "src=" PTR_FORMAT "-" PTR_FORMAT " "
                  SIZE_FORMAT "-" SIZE_FORMAT " "
                  "dst=" PTR_FORMAT "-" PTR_FORMAT " "
                  SIZE_FORMAT "-" SIZE_FORMAT,
                  src_space_id, space_names[src_space_id],
                  dst_space_id, space_names[dst_space_id],
                  src_beg, src_end,
                  _summary_data.addr_to_region_idx(src_beg),
                  _summary_data.addr_to_region_idx(src_end),
                  dst_beg, dst_end,
                  _summary_data.addr_to_region_idx(dst_beg),
                  _summary_data.addr_to_region_idx(dst_end));
  }
}
#endif  // #ifndef PRODUCT

D
duke 已提交
1846 1847 1848
void PSParallelCompact::summary_phase(ParCompactionManager* cm,
                                      bool maximum_compaction)
{
S
sla 已提交
1849
  GCTraceTime tm("summary phase", print_phases(), true, &_gc_timer);
D
duke 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
  // trace("2");

#ifdef  ASSERT
  if (TraceParallelOldGCMarkingPhase) {
    tty->print_cr("add_obj_count=" SIZE_FORMAT " "
                  "add_obj_bytes=" SIZE_FORMAT,
                  add_obj_count, add_obj_size * HeapWordSize);
    tty->print_cr("mark_bitmap_count=" SIZE_FORMAT " "
                  "mark_bitmap_bytes=" SIZE_FORMAT,
                  mark_bitmap_count, mark_bitmap_size * HeapWordSize);
  }
#endif  // #ifdef ASSERT

  // Quick summarization of each space into itself, to see how much is live.
  summarize_spaces_quick();

  if (TraceParallelOldGCSummaryPhase) {
    tty->print_cr("summary_phase:  after summarizing each space to self");
    Universe::print();
1869
    NOT_PRODUCT(print_region_ranges());
D
duke 已提交
1870 1871 1872 1873 1874 1875 1876
    if (Verbose) {
      NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
    }
  }

  // The amount of live data that will end up in old space (assuming it fits).
  size_t old_space_total_live = 0;
1877
  for (unsigned int id = old_space_id; id < last_space_id; ++id) {
D
duke 已提交
1878 1879 1880 1881
    old_space_total_live += pointer_delta(_space_info[id].new_top(),
                                          _space_info[id].space()->bottom());
  }

1882
  MutableSpace* const old_space = _space_info[old_space_id].space();
1883 1884
  const size_t old_capacity = old_space->capacity_in_words();
  if (old_space_total_live > old_capacity) {
D
duke 已提交
1885 1886 1887
    // XXX - should also try to expand
    maximum_compaction = true;
  }
1888 1889
#ifndef PRODUCT
  if (ParallelOldGCSplitALot && old_space_total_live < old_capacity) {
1890
    provoke_split(maximum_compaction);
1891 1892
  }
#endif // #ifndef PRODUCT
D
duke 已提交
1893

1894
  // Old generations.
D
duke 已提交
1895 1896
  summarize_space(old_space_id, maximum_compaction);

1897 1898 1899 1900 1901 1902 1903 1904
  // Summarize the remaining spaces in the young gen.  The initial target space
  // is the old gen.  If a space does not fit entirely into the target, then the
  // remainder is compacted into the space itself and that space becomes the new
  // target.
  SpaceId dst_space_id = old_space_id;
  HeapWord* dst_space_end = old_space->end();
  HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
  for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
D
duke 已提交
1905 1906 1907
    const MutableSpace* space = _space_info[id].space();
    const size_t live = pointer_delta(_space_info[id].new_top(),
                                      space->bottom());
1908 1909 1910 1911
    const size_t available = pointer_delta(dst_space_end, *new_top_addr);

    NOT_PRODUCT(summary_phase_msg(dst_space_id, *new_top_addr, dst_space_end,
                                  SpaceId(id), space->bottom(), space->top());)
1912
    if (live > 0 && live <= available) {
D
duke 已提交
1913
      // All the live data will fit.
1914 1915 1916 1917 1918 1919 1920
      bool done = _summary_data.summarize(_space_info[id].split_info(),
                                          space->bottom(), space->top(),
                                          NULL,
                                          *new_top_addr, dst_space_end,
                                          new_top_addr);
      assert(done, "space must fit into old gen");

1921 1922
      // Reset the new_top value for the space.
      _space_info[id].set_new_top(space->bottom());
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
    } else if (live > 0) {
      // Attempt to fit part of the source space into the target space.
      HeapWord* next_src_addr = NULL;
      bool done = _summary_data.summarize(_space_info[id].split_info(),
                                          space->bottom(), space->top(),
                                          &next_src_addr,
                                          *new_top_addr, dst_space_end,
                                          new_top_addr);
      assert(!done, "space should not fit into old gen");
      assert(next_src_addr != NULL, "sanity");

      // The source space becomes the new target, so the remainder is compacted
      // within the space itself.
      dst_space_id = SpaceId(id);
      dst_space_end = space->end();
      new_top_addr = _space_info[id].new_top_addr();
      NOT_PRODUCT(summary_phase_msg(dst_space_id,
                                    space->bottom(), dst_space_end,
                                    SpaceId(id), next_src_addr, space->top());)
      done = _summary_data.summarize(_space_info[id].split_info(),
                                     next_src_addr, space->top(),
                                     NULL,
                                     space->bottom(), dst_space_end,
                                     new_top_addr);
      assert(done, "space must fit when compacted into itself");
      assert(*new_top_addr <= space->top(), "usage should not grow");
D
duke 已提交
1949 1950 1951 1952 1953 1954
    }
  }

  if (TraceParallelOldGCSummaryPhase) {
    tty->print_cr("summary_phase:  after final summarization");
    Universe::print();
1955
    NOT_PRODUCT(print_region_ranges());
D
duke 已提交
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
    if (Verbose) {
      NOT_PRODUCT(print_generic_summary_data(_summary_data, _space_info));
    }
  }
}

// This method should contain all heap-specific policy for invoking a full
// collection.  invoke_no_policy() will only attempt to compact the heap; it
// will do nothing further.  If we need to bail out for policy reasons, scavenge
// before full gc, or any other specialized behavior, it needs to be added here.
//
// Note that this method should only be called from the vm_thread while at a
// safepoint.
1969 1970 1971 1972 1973
//
// Note that the all_soft_refs_clear flag in the collector policy
// may be true because this method can be called without intervening
// activity.  For example when the heap space is tight and full measure
// are being taken to free space.
D
duke 已提交
1974 1975 1976 1977
void PSParallelCompact::invoke(bool maximum_heap_compaction) {
  assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
  assert(Thread::current() == (Thread*)VMThread::vm_thread(),
         "should be in vm thread");
1978

D
duke 已提交
1979 1980 1981 1982 1983
  ParallelScavengeHeap* heap = gc_heap();
  GCCause::Cause gc_cause = heap->gc_cause();
  assert(!heap->is_gc_active(), "not reentrant");

  PSAdaptiveSizePolicy* policy = heap->size_policy();
1984
  IsGCActiveMark mark;
D
duke 已提交
1985

1986 1987
  if (ScavengeBeforeFullGC) {
    PSScavenge::invoke_no_policy();
D
duke 已提交
1988
  }
1989 1990 1991 1992 1993 1994

  const bool clear_all_soft_refs =
    heap->collector_policy()->should_clear_all_soft_refs();

  PSParallelCompact::invoke_no_policy(clear_all_soft_refs ||
                                      maximum_heap_compaction);
D
duke 已提交
1995 1996 1997 1998
}

// This method contains no policy. You should probably
// be calling invoke() instead.
1999
bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
D
duke 已提交
2000 2001 2002
  assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
  assert(ref_processor() != NULL, "Sanity");

2003
  if (GC_locker::check_active_before_gc()) {
2004
    return false;
D
duke 已提交
2005 2006
  }

S
sla 已提交
2007 2008 2009 2010 2011
  ParallelScavengeHeap* heap = gc_heap();

  _gc_timer.register_gc_start(os::elapsed_counter());
  _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());

D
duke 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020
  TimeStamp marking_start;
  TimeStamp compaction_start;
  TimeStamp collection_exit;

  GCCause::Cause gc_cause = heap->gc_cause();
  PSYoungGen* young_gen = heap->young_gen();
  PSOldGen* old_gen = heap->old_gen();
  PSAdaptiveSizePolicy* size_policy = heap->size_policy();

2021 2022 2023 2024 2025
  // The scope of casr should end after code that can change
  // CollectorPolicy::_should_clear_all_soft_refs.
  ClearedAllSoftRefs casr(maximum_heap_compaction,
                          heap->collector_policy());

2026 2027 2028 2029 2030
  if (ZapUnusedHeapArea) {
    // Save information needed to minimize mangling
    heap->record_gen_tops_before_GC();
  }

S
sla 已提交
2031
  heap->pre_full_gc_dump(&_gc_timer);
2032

D
duke 已提交
2033 2034 2035 2036 2037 2038 2039
  _print_phases = PrintGCDetails && PrintParallelOldGCPhaseTimes;

  // Make sure data structures are sane, make the heap parsable, and do other
  // miscellaneous bookkeeping.
  PreGCValues pre_gc_values;
  pre_compact(&pre_gc_values);

J
jcoomes 已提交
2040 2041 2042 2043
  // Get the compaction manager reserved for the VM thread.
  ParCompactionManager* const vmthread_cm =
    ParCompactionManager::manager_array(gc_task_manager()->workers());

D
duke 已提交
2044 2045 2046 2047 2048 2049 2050
  // Place after pre_compact() where the number of invocations is incremented.
  AdaptiveSizePolicyOutput(size_policy, heap->total_collections());

  {
    ResourceMark rm;
    HandleMark hm;

2051 2052 2053 2054 2055
    // Set the number of GC threads to be used in this collection
    gc_task_manager()->set_active_gang();
    gc_task_manager()->task_idle_workers();
    heap->set_par_threads(gc_task_manager()->active_workers());

D
duke 已提交
2056 2057
    gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
    TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
S
sla 已提交
2058
    GCTraceTime t1(GCCauseString("Full GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
D
duke 已提交
2059
    TraceCollectorStats tcs(counters());
2060
    TraceMemoryManagerStats tms(true /* Full GC */,gc_cause);
D
duke 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071

    if (TraceGen1Time) accumulated_time()->start();

    // Let the size policy know we're starting
    size_policy->major_collection_begin();

    CodeCache::gc_prologue();
    Threads::gc_prologue();

    COMPILER2_PRESENT(DerivedPointerTable::clear());

2072
    ref_processor()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
2073
    ref_processor()->setup_policy(maximum_heap_compaction);
D
duke 已提交
2074 2075 2076 2077

    bool marked_for_unloading = false;

    marking_start.update();
S
sla 已提交
2078
    marking_phase(vmthread_cm, maximum_heap_compaction, &_gc_tracer);
D
duke 已提交
2079

2080 2081
    bool max_on_system_gc = UseMaximumCompactionOnSystemGC
      && gc_cause == GCCause::_java_lang_system_gc;
J
jcoomes 已提交
2082
    summary_phase(vmthread_cm, maximum_heap_compaction || max_on_system_gc);
D
duke 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091

    COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity"));
    COMPILER2_PRESENT(DerivedPointerTable::set_active(false));

    // adjust_roots() updates Universe::_intArrayKlassObj which is
    // needed by the compaction for filling holes in the dense prefix.
    adjust_roots();

    compaction_start.update();
2092
    compact();
D
duke 已提交
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107

    // Reset the mark bitmap, summary data, and do other bookkeeping.  Must be
    // done before resizing.
    post_compact();

    // Let the size policy know we're done
    size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);

    if (UseAdaptiveSizePolicy) {
      if (PrintAdaptiveSizePolicy) {
        gclog_or_tty->print("AdaptiveSizeStart: ");
        gclog_or_tty->stamp();
        gclog_or_tty->print_cr(" collection: %d ",
                       heap->total_collections());
        if (Verbose) {
2108 2109
          gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d",
            old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
D
duke 已提交
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
        }
      }

      // Don't check if the size_policy is ready here.  Let
      // the size_policy check that internally.
      if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
          ((gc_cause != GCCause::_java_lang_system_gc) ||
            UseAdaptiveSizePolicyWithSystemGC)) {
        // Calculate optimal free space amounts
        assert(young_gen->max_size() >
          young_gen->from_space()->capacity_in_bytes() +
          young_gen->to_space()->capacity_in_bytes(),
          "Sizes of space in young gen are out-of-bounds");
2123 2124 2125 2126 2127 2128

        size_t young_live = young_gen->used_in_bytes();
        size_t eden_live = young_gen->eden_space()->used_in_bytes();
        size_t old_live = old_gen->used_in_bytes();
        size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
        size_t max_old_gen_size = old_gen->max_gen_size();
D
duke 已提交
2129 2130 2131
        size_t max_eden_size = young_gen->max_size() -
          young_gen->from_space()->capacity_in_bytes() -
          young_gen->to_space()->capacity_in_bytes();
2132 2133 2134 2135

        // Used for diagnostics
        size_policy->clear_generation_free_space_flags();

2136 2137 2138 2139 2140 2141 2142
        size_policy->compute_generations_free_space(young_live,
                                                    eden_live,
                                                    old_live,
                                                    cur_eden,
                                                    max_old_gen_size,
                                                    max_eden_size,
                                                    true /* full gc*/);
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152

        size_policy->check_gc_overhead_limit(young_live,
                                             eden_live,
                                             max_old_gen_size,
                                             max_eden_size,
                                             true /* full gc*/,
                                             gc_cause,
                                             heap->collector_policy());

        size_policy->decay_supplemental_growth(true /* full gc*/);
2153 2154 2155

        heap->resize_old_gen(
          size_policy->calculated_old_free_size_in_bytes());
D
duke 已提交
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178

        // Don't resize the young generation at an major collection.  A
        // desired young generation size may have been calculated but
        // resizing the young generation complicates the code because the
        // resizing of the old generation may have moved the boundary
        // between the young generation and the old generation.  Let the
        // young generation resizing happen at the minor collections.
      }
      if (PrintAdaptiveSizePolicy) {
        gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",
                       heap->total_collections());
      }
    }

    if (UsePerfData) {
      PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();
      counters->update_counters();
      counters->update_old_capacity(old_gen->capacity_in_bytes());
      counters->update_young_capacity(young_gen->capacity_in_bytes());
    }

    heap->resize_all_tlabs();

2179 2180
    // Resize the metaspace capactiy after a collection
    MetaspaceGC::compute_new_size();
D
duke 已提交
2181 2182 2183 2184 2185 2186 2187 2188 2189

    if (TraceGen1Time) accumulated_time()->stop();

    if (PrintGC) {
      if (PrintGCDetails) {
        // No GC timestamp here.  This is after GC so it would be confusing.
        young_gen->print_used_change(pre_gc_values.young_gen_used());
        old_gen->print_used_change(pre_gc_values.old_gen_used());
        heap->print_heap_change(pre_gc_values.heap_used());
2190
        MetaspaceAux::print_metaspace_change(pre_gc_values.metadata_used());
D
duke 已提交
2191 2192 2193 2194 2195 2196 2197 2198
      } else {
        heap->print_heap_change(pre_gc_values.heap_used());
      }
    }

    // Track memory usage and detect low memory
    MemoryService::track_memory_usage();
    heap->update_counters();
2199
    gc_task_manager()->release_idle_workers();
D
duke 已提交
2200 2201
  }

2202 2203 2204 2205 2206
#ifdef ASSERT
  for (size_t i = 0; i < ParallelGCThreads + 1; ++i) {
    ParCompactionManager* const cm =
      ParCompactionManager::manager_array(int(i));
    assert(cm->marking_stack()->is_empty(),       "should be empty");
2207
    assert(ParCompactionManager::region_list(int(i))->is_empty(), "should be empty");
2208 2209 2210
  }
#endif // ASSERT

D
duke 已提交
2211 2212
  if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
    HandleMark hm;  // Discard invalid handles created during verification
2213
    Universe::verify(" VerifyAfterGC:");
D
duke 已提交
2214 2215 2216 2217 2218 2219 2220 2221
  }

  // Re-verify object start arrays
  if (VerifyObjectStartArray &&
      VerifyAfterGC) {
    old_gen->verify_object_start_array();
  }

2222 2223 2224 2225
  if (ZapUnusedHeapArea) {
    old_gen->object_space()->check_mangled_unused_area_complete();
  }

D
duke 已提交
2226 2227 2228 2229
  NOT_PRODUCT(ref_processor()->verify_no_references_recorded());

  collection_exit.update();

2230
  heap->print_heap_after_gc();
S
sla 已提交
2231 2232
  heap->trace_heap_after_gc(&_gc_tracer);

D
duke 已提交
2233 2234 2235 2236 2237 2238 2239
  if (PrintGCTaskTimeStamps) {
    gclog_or_tty->print_cr("VM-Thread " INT64_FORMAT " " INT64_FORMAT " "
                           INT64_FORMAT,
                           marking_start.ticks(), compaction_start.ticks(),
                           collection_exit.ticks());
    gc_task_manager()->print_task_time_stamps();
  }
2240

S
sla 已提交
2241
  heap->post_full_gc_dump(&_gc_timer);
2242

2243 2244 2245
#ifdef TRACESPINNING
  ParallelTaskTerminator::print_termination_counts();
#endif
2246

S
sla 已提交
2247 2248 2249 2250 2251
  _gc_timer.register_gc_end(os::elapsed_counter());

  _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
  _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());

2252
  return true;
D
duke 已提交
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
}

bool PSParallelCompact::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,
                                             PSYoungGen* young_gen,
                                             PSOldGen* old_gen) {
  MutableSpace* const eden_space = young_gen->eden_space();
  assert(!eden_space->is_empty(), "eden must be non-empty");
  assert(young_gen->virtual_space()->alignment() ==
         old_gen->virtual_space()->alignment(), "alignments do not match");

  if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary)) {
    return false;
  }

  // Both generations must be completely committed.
  if (young_gen->virtual_space()->uncommitted_size() != 0) {
    return false;
  }
  if (old_gen->virtual_space()->uncommitted_size() != 0) {
    return false;
  }

  // Figure out how much to take from eden.  Include the average amount promoted
  // in the total; otherwise the next young gen GC will simply bail out to a
  // full GC.
  const size_t alignment = old_gen->virtual_space()->alignment();
  const size_t eden_used = eden_space->used_in_bytes();
  const size_t promoted = (size_t)size_policy->avg_promoted()->padded_average();
  const size_t absorb_size = align_size_up(eden_used + promoted, alignment);
  const size_t eden_capacity = eden_space->capacity_in_bytes();

  if (absorb_size >= eden_capacity) {
    return false; // Must leave some space in eden.
  }

  const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;
  if (new_young_size < young_gen->min_gen_size()) {
    return false; // Respect young gen minimum size.
  }

  if (TraceAdaptiveGCBoundary && Verbose) {
    gclog_or_tty->print(" absorbing " SIZE_FORMAT "K:  "
                        "eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "
                        "from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "
                        "young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",
                        absorb_size / K,
                        eden_capacity / K, (eden_capacity - absorb_size) / K,
                        young_gen->from_space()->used_in_bytes() / K,
                        young_gen->to_space()->used_in_bytes() / K,
                        young_gen->capacity_in_bytes() / K, new_young_size / K);
  }

  // Fill the unused part of the old gen.
  MutableSpace* const old_space = old_gen->object_space();
2307 2308 2309 2310 2311 2312 2313 2314
  HeapWord* const unused_start = old_space->top();
  size_t const unused_words = pointer_delta(old_space->end(), unused_start);

  if (unused_words > 0) {
    if (unused_words < CollectedHeap::min_fill_size()) {
      return false;  // If the old gen cannot be filled, must give up.
    }
    CollectedHeap::fill_with_objects(unused_start, unused_words);
D
duke 已提交
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
  }

  // Take the live data from eden and set both top and end in the old gen to
  // eden top.  (Need to set end because reset_after_change() mangles the region
  // from end to virtual_space->high() in debug builds).
  HeapWord* const new_top = eden_space->top();
  old_gen->virtual_space()->expand_into(young_gen->virtual_space(),
                                        absorb_size);
  young_gen->reset_after_change();
  old_space->set_top(new_top);
  old_space->set_end(new_top);
  old_gen->reset_after_change();

  // Update the object start array for the filler object and the data from eden.
  ObjectStartArray* const start_array = old_gen->start_array();
2330 2331
  for (HeapWord* p = unused_start; p < new_top; p += oop(p)->size()) {
    start_array->allocate_block(p);
D
duke 已提交
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
  }

  // Could update the promoted average here, but it is not typically updated at
  // full GCs and the value to use is unclear.  Something like
  //
  // cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.

  size_policy->set_bytes_absorbed_from_eden(absorb_size);
  return true;
}

GCTaskManager* const PSParallelCompact::gc_task_manager() {
  assert(ParallelScavengeHeap::gc_task_manager() != NULL,
    "shouldn't return NULL");
  return ParallelScavengeHeap::gc_task_manager();
}

void PSParallelCompact::marking_phase(ParCompactionManager* cm,
S
sla 已提交
2350 2351
                                      bool maximum_heap_compaction,
                                      ParallelOldTracer *gc_tracer) {
D
duke 已提交
2352
  // Recursively traverse all live objects and mark them
S
sla 已提交
2353
  GCTraceTime tm("marking phase", print_phases(), true, &_gc_timer);
D
duke 已提交
2354 2355 2356

  ParallelScavengeHeap* heap = gc_heap();
  uint parallel_gc_threads = heap->gc_task_manager()->workers();
2357
  uint active_gc_threads = heap->gc_task_manager()->active_workers();
2358
  TaskQueueSetSuper* qset = ParCompactionManager::region_array();
2359
  ParallelTaskTerminator terminator(active_gc_threads, qset);
D
duke 已提交
2360 2361 2362 2363

  PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
  PSParallelCompact::FollowStackClosure follow_stack_closure(cm);

2364 2365 2366
  // Need new claim bits before marking starts.
  ClassLoaderDataGraph::clear_claimed_marks();

D
duke 已提交
2367
  {
S
sla 已提交
2368 2369
    GCTraceTime tm_m("par mark", print_phases(), true, &_gc_timer);

2370
    ParallelScavengeHeap::ParStrongRootsScope psrs;
D
duke 已提交
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381

    GCTaskQueue* q = GCTaskQueue::create();

    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::universe));
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jni_handles));
    // We scan the thread roots in parallel
    Threads::create_thread_roots_marking_tasks(q);
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::object_synchronizer));
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::flat_profiler));
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::management));
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::system_dictionary));
2382
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::class_loader_data));
D
duke 已提交
2383
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jvmti));
2384
    q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::code_cache));
D
duke 已提交
2385

2386 2387
    if (active_gc_threads > 1) {
      for (uint j = 0; j < active_gc_threads; j++) {
D
duke 已提交
2388 2389 2390 2391
        q->enqueue(new StealMarkingTask(&terminator));
      }
    }

2392
    gc_task_manager()->execute_and_wait(q);
D
duke 已提交
2393 2394 2395 2396
  }

  // Process reference objects found during marking
  {
S
sla 已提交
2397 2398 2399
    GCTraceTime tm_r("reference processing", print_phases(), true, &_gc_timer);

    ReferenceProcessorStats stats;
D
duke 已提交
2400 2401
    if (ref_processor()->processing_is_mt()) {
      RefProcTaskExecutor task_executor;
S
sla 已提交
2402
      stats = ref_processor()->process_discovered_references(
2403
        is_alive_closure(), &mark_and_push_closure, &follow_stack_closure,
S
sla 已提交
2404
        &task_executor, &_gc_timer);
D
duke 已提交
2405
    } else {
S
sla 已提交
2406 2407 2408
      stats = ref_processor()->process_discovered_references(
        is_alive_closure(), &mark_and_push_closure, &follow_stack_closure, NULL,
        &_gc_timer);
D
duke 已提交
2409
    }
S
sla 已提交
2410 2411

    gc_tracer->report_gc_reference_stats(stats);
D
duke 已提交
2412 2413
  }

S
sla 已提交
2414
  GCTraceTime tm_c("class unloading", print_phases(), true, &_gc_timer);
2415 2416 2417 2418

  // This is the point where the entire marking should have completed.
  assert(cm->marking_stacks_empty(), "Marking should have completed");

D
duke 已提交
2419 2420 2421
  // Follow system dictionary roots and unload classes.
  bool purged_class = SystemDictionary::do_unloading(is_alive_closure());

2422
  // Unload nmethods.
2423
  CodeCache::do_unloading(is_alive_closure(), purged_class);
D
duke 已提交
2424

2425
  // Prune dead klasses from subklass/sibling/implementor lists.
2426
  Klass::clean_weak_klass_links(is_alive_closure());
D
duke 已提交
2427

2428
  // Delete entries for dead interned strings.
D
duke 已提交
2429
  StringTable::unlink(is_alive_closure());
2430

2431 2432
  // Clean up unreferenced symbols in symbol table.
  SymbolTable::unlink();
S
sla 已提交
2433
  _gc_tracer.report_object_count_after_gc(is_alive_closure());
D
duke 已提交
2434 2435
}

2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
void PSParallelCompact::follow_klass(ParCompactionManager* cm, Klass* klass) {
  ClassLoaderData* cld = klass->class_loader_data();
  // The actual processing of the klass is done when we
  // traverse the list of Klasses in the class loader data.
  PSParallelCompact::follow_class_loader(cm, cld);
}

void PSParallelCompact::adjust_klass(ParCompactionManager* cm, Klass* klass) {
  ClassLoaderData* cld = klass->class_loader_data();
  // The actual processing of the klass is done when we
  // traverse the list of Klasses in the class loader data.
  PSParallelCompact::adjust_class_loader(cm, cld);
}

void PSParallelCompact::follow_class_loader(ParCompactionManager* cm,
                                            ClassLoaderData* cld) {
  PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
  PSParallelCompact::FollowKlassClosure follow_klass_closure(&mark_and_push_closure);

  cld->oops_do(&mark_and_push_closure, &follow_klass_closure, true);
}

void PSParallelCompact::adjust_class_loader(ParCompactionManager* cm,
                                            ClassLoaderData* cld) {
2460
  cld->oops_do(PSParallelCompact::adjust_pointer_closure(),
2461 2462 2463 2464
               PSParallelCompact::adjust_klass_closure(),
               true);
}

D
duke 已提交
2465 2466 2467 2468 2469 2470 2471 2472 2473
// This should be moved to the shared markSweep code!
class PSAlwaysTrueClosure: public BoolObjectClosure {
public:
  bool do_object_b(oop p) { return true; }
};
static PSAlwaysTrueClosure always_true;

void PSParallelCompact::adjust_roots() {
  // Adjust the pointers to reflect the new locations
S
sla 已提交
2474
  GCTraceTime tm("adjust roots", print_phases(), true, &_gc_timer);
D
duke 已提交
2475

2476 2477 2478
  // Need new claim bits when tracing through and adjusting pointers.
  ClassLoaderDataGraph::clear_claimed_marks();

D
duke 已提交
2479
  // General strong roots.
2480 2481 2482 2483 2484 2485 2486 2487
  Universe::oops_do(adjust_pointer_closure());
  JNIHandles::oops_do(adjust_pointer_closure());   // Global (strong) JNI handles
  CLDToOopClosure adjust_from_cld(adjust_pointer_closure());
  Threads::oops_do(adjust_pointer_closure(), &adjust_from_cld, NULL);
  ObjectSynchronizer::oops_do(adjust_pointer_closure());
  FlatProfiler::oops_do(adjust_pointer_closure());
  Management::oops_do(adjust_pointer_closure());
  JvmtiExport::oops_do(adjust_pointer_closure());
D
duke 已提交
2488
  // SO_AllClasses
2489 2490
  SystemDictionary::oops_do(adjust_pointer_closure());
  ClassLoaderDataGraph::oops_do(adjust_pointer_closure(), adjust_klass_closure(), true);
D
duke 已提交
2491 2492 2493 2494

  // Now adjust pointers in remaining weak roots.  (All of which should
  // have been cleared if they pointed to non-surviving objects.)
  // Global (weak) JNI handles
2495
  JNIHandles::weak_oops_do(&always_true, adjust_pointer_closure());
D
duke 已提交
2496 2497

  CodeCache::oops_do(adjust_pointer_closure());
2498 2499
  StringTable::oops_do(adjust_pointer_closure());
  ref_processor()->weak_oops_do(adjust_pointer_closure());
D
duke 已提交
2500 2501 2502 2503
  // Roots were visited so references into the young gen in roots
  // may have been scanned.  Process them also.
  // Should the reference processor have a span that excludes
  // young gen objects?
2504
  PSScavenge::reference_processor()->weak_oops_do(adjust_pointer_closure());
D
duke 已提交
2505 2506
}

2507 2508 2509
void PSParallelCompact::enqueue_region_draining_tasks(GCTaskQueue* q,
                                                      uint parallel_gc_threads)
{
S
sla 已提交
2510
  GCTraceTime tm("drain task setup", print_phases(), true, &_gc_timer);
D
duke 已提交
2511

2512 2513 2514 2515 2516
  // Find the threads that are active
  unsigned int which = 0;

  const uint task_count = MAX2(parallel_gc_threads, 1U);
  for (uint j = 0; j < task_count; j++) {
2517
    q->enqueue(new DrainStacksCompactionTask(j));
2518 2519 2520 2521 2522 2523 2524 2525
    ParCompactionManager::verify_region_list_empty(j);
    // Set the region stacks variables to "no" region stack values
    // so that they will be recognized and needing a region stack
    // in the stealing tasks if they do not get one by executing
    // a draining stack.
    ParCompactionManager* cm = ParCompactionManager::manager_array(j);
    cm->set_region_stack(NULL);
    cm->set_region_stack_index((uint)max_uintx);
D
duke 已提交
2526
  }
2527
  ParCompactionManager::reset_recycled_stack_index();
D
duke 已提交
2528

2529
  // Find all regions that are available (can be filled immediately) and
D
duke 已提交
2530
  // distribute them to the thread stacks.  The iteration is done in reverse
2531
  // order (high to low) so the regions will be removed in ascending order.
D
duke 已提交
2532 2533 2534

  const ParallelCompactData& sd = PSParallelCompact::summary_data();

2535
  size_t fillable_regions = 0;   // A count for diagnostic purposes.
2536 2537
  // A region index which corresponds to the tasks created above.
  // "which" must be 0 <= which < task_count
D
duke 已提交
2538

2539
  which = 0;
2540 2541 2542
  // id + 1 is used to test termination so unsigned  can
  // be used with an old_space_id == 0.
  for (unsigned int id = to_space_id; id + 1 > old_space_id; --id) {
D
duke 已提交
2543 2544 2545 2546
    SpaceInfo* const space_info = _space_info + id;
    MutableSpace* const space = space_info->space();
    HeapWord* const new_top = space_info->new_top();

2547 2548 2549
    const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
    const size_t end_region =
      sd.addr_to_region_idx(sd.region_align_up(new_top));
D
duke 已提交
2550

2551
    for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
2552
      if (sd.region(cur)->claim_unsafe()) {
2553
        ParCompactionManager::region_list_push(which, cur);
D
duke 已提交
2554 2555

        if (TraceParallelOldGCCompactionPhase && Verbose) {
2556
          const size_t count_mod_8 = fillable_regions & 7;
D
duke 已提交
2557
          if (count_mod_8 == 0) gclog_or_tty->print("fillable: ");
2558
          gclog_or_tty->print(" " SIZE_FORMAT_W(7), cur);
D
duke 已提交
2559 2560 2561
          if (count_mod_8 == 7) gclog_or_tty->cr();
        }

2562
        NOT_PRODUCT(++fillable_regions;)
D
duke 已提交
2563

2564
        // Assign regions to tasks in round-robin fashion.
D
duke 已提交
2565
        if (++which == task_count) {
2566 2567
          assert(which <= parallel_gc_threads,
            "Inconsistent number of workers");
D
duke 已提交
2568 2569 2570 2571 2572 2573 2574
          which = 0;
        }
      }
    }
  }

  if (TraceParallelOldGCCompactionPhase) {
2575 2576
    if (Verbose && (fillable_regions & 7) != 0) gclog_or_tty->cr();
    gclog_or_tty->print_cr("%u initially fillable regions", fillable_regions);
D
duke 已提交
2577 2578 2579 2580 2581 2582 2583
  }
}

#define PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING 4

void PSParallelCompact::enqueue_dense_prefix_tasks(GCTaskQueue* q,
                                                    uint parallel_gc_threads) {
S
sla 已提交
2584
  GCTraceTime tm("dense prefix task setup", print_phases(), true, &_gc_timer);
D
duke 已提交
2585 2586 2587 2588

  ParallelCompactData& sd = PSParallelCompact::summary_data();

  // Iterate over all the spaces adding tasks for updating
2589
  // regions in the dense prefix.  Assume that 1 gc thread
D
duke 已提交
2590 2591
  // will work on opening the gaps and the remaining gc threads
  // will work on the dense prefix.
2592 2593
  unsigned int space_id;
  for (space_id = old_space_id; space_id < last_space_id; ++ space_id) {
D
duke 已提交
2594 2595 2596 2597 2598 2599 2600 2601
    HeapWord* const dense_prefix_end = _space_info[space_id].dense_prefix();
    const MutableSpace* const space = _space_info[space_id].space();

    if (dense_prefix_end == space->bottom()) {
      // There is no dense prefix for this space.
      continue;
    }

2602 2603 2604 2605 2606
    // The dense prefix is before this region.
    size_t region_index_end_dense_prefix =
        sd.addr_to_region_idx(dense_prefix_end);
    RegionData* const dense_prefix_cp =
      sd.region(region_index_end_dense_prefix);
D
duke 已提交
2607 2608 2609
    assert(dense_prefix_end == space->end() ||
           dense_prefix_cp->available() ||
           dense_prefix_cp->claimed(),
2610
           "The region after the dense prefix should always be ready to fill");
D
duke 已提交
2611

2612
    size_t region_index_start = sd.addr_to_region_idx(space->bottom());
D
duke 已提交
2613 2614

    // Is there dense prefix work?
2615 2616 2617
    size_t total_dense_prefix_regions =
      region_index_end_dense_prefix - region_index_start;
    // How many regions of the dense prefix should be given to
D
duke 已提交
2618
    // each thread?
2619
    if (total_dense_prefix_regions > 0) {
D
duke 已提交
2620
      uint tasks_for_dense_prefix = 1;
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
      if (total_dense_prefix_regions <=
          (parallel_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)) {
        // Don't over partition.  This assumes that
        // PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING is a small integer value
        // so there are not many regions to process.
        tasks_for_dense_prefix = parallel_gc_threads;
      } else {
        // Over partition
        tasks_for_dense_prefix = parallel_gc_threads *
          PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING;
D
duke 已提交
2631
      }
2632
      size_t regions_per_thread = total_dense_prefix_regions /
D
duke 已提交
2633
        tasks_for_dense_prefix;
2634 2635 2636
      // Give each thread at least 1 region.
      if (regions_per_thread == 0) {
        regions_per_thread = 1;
D
duke 已提交
2637 2638 2639
      }

      for (uint k = 0; k < tasks_for_dense_prefix; k++) {
2640
        if (region_index_start >= region_index_end_dense_prefix) {
D
duke 已提交
2641 2642
          break;
        }
2643 2644 2645
        // region_index_end is not processed
        size_t region_index_end = MIN2(region_index_start + regions_per_thread,
                                       region_index_end_dense_prefix);
2646 2647 2648
        q->enqueue(new UpdateDensePrefixTask(SpaceId(space_id),
                                             region_index_start,
                                             region_index_end));
2649
        region_index_start = region_index_end;
D
duke 已提交
2650 2651 2652 2653
      }
    }
    // This gets any part of the dense prefix that did not
    // fit evenly.
2654
    if (region_index_start < region_index_end_dense_prefix) {
2655 2656 2657
      q->enqueue(new UpdateDensePrefixTask(SpaceId(space_id),
                                           region_index_start,
                                           region_index_end_dense_prefix));
D
duke 已提交
2658
    }
2659
  }
D
duke 已提交
2660 2661
}

2662
void PSParallelCompact::enqueue_region_stealing_tasks(
D
duke 已提交
2663 2664 2665
                                     GCTaskQueue* q,
                                     ParallelTaskTerminator* terminator_ptr,
                                     uint parallel_gc_threads) {
S
sla 已提交
2666
  GCTraceTime tm("steal task setup", print_phases(), true, &_gc_timer);
D
duke 已提交
2667

2668
  // Once a thread has drained it's stack, it should try to steal regions from
D
duke 已提交
2669 2670 2671
  // other threads.
  if (parallel_gc_threads > 1) {
    for (uint j = 0; j < parallel_gc_threads; j++) {
2672
      q->enqueue(new StealRegionCompactionTask(terminator_ptr));
D
duke 已提交
2673 2674 2675 2676
    }
  }
}

2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
#ifdef ASSERT
// Write a histogram of the number of times the block table was filled for a
// region.
void PSParallelCompact::write_block_fill_histogram(outputStream* const out)
{
  if (!TraceParallelOldGCCompactionPhase) return;

  typedef ParallelCompactData::RegionData rd_t;
  ParallelCompactData& sd = summary_data();

  for (unsigned int id = old_space_id; id < last_space_id; ++id) {
    MutableSpace* const spc = _space_info[id].space();
    if (spc->bottom() != spc->top()) {
      const rd_t* const beg = sd.addr_to_region_ptr(spc->bottom());
      HeapWord* const top_aligned_up = sd.region_align_up(spc->top());
      const rd_t* const end = sd.addr_to_region_ptr(top_aligned_up);

      size_t histo[5] = { 0, 0, 0, 0, 0 };
      const size_t histo_len = sizeof(histo) / sizeof(size_t);
      const size_t region_cnt = pointer_delta(end, beg, sizeof(rd_t));

      for (const rd_t* cur = beg; cur < end; ++cur) {
        ++histo[MIN2(cur->blocks_filled_count(), histo_len - 1)];
      }
      out->print("%u %-4s" SIZE_FORMAT_W(5), id, space_names[id], region_cnt);
      for (size_t i = 0; i < histo_len; ++i) {
        out->print(" " SIZE_FORMAT_W(5) " %5.1f%%",
                   histo[i], 100.0 * histo[i] / region_cnt);
      }
      out->cr();
    }
  }
}
#endif // #ifdef ASSERT

D
duke 已提交
2712 2713
void PSParallelCompact::compact() {
  // trace("5");
S
sla 已提交
2714
  GCTraceTime tm("compaction phase", print_phases(), true, &_gc_timer);
D
duke 已提交
2715 2716 2717 2718 2719 2720

  ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
  assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
  PSOldGen* old_gen = heap->old_gen();
  old_gen->start_array()->reset();
  uint parallel_gc_threads = heap->gc_task_manager()->workers();
2721
  uint active_gc_threads = heap->gc_task_manager()->active_workers();
2722
  TaskQueueSetSuper* qset = ParCompactionManager::region_array();
2723
  ParallelTaskTerminator terminator(active_gc_threads, qset);
D
duke 已提交
2724 2725

  GCTaskQueue* q = GCTaskQueue::create();
2726 2727 2728
  enqueue_region_draining_tasks(q, active_gc_threads);
  enqueue_dense_prefix_tasks(q, active_gc_threads);
  enqueue_region_stealing_tasks(q, &terminator, active_gc_threads);
D
duke 已提交
2729 2730

  {
S
sla 已提交
2731
    GCTraceTime tm_pc("par compact", print_phases(), true, &_gc_timer);
D
duke 已提交
2732

2733
    gc_task_manager()->execute_and_wait(q);
D
duke 已提交
2734 2735

#ifdef  ASSERT
2736
    // Verify that all regions have been processed before the deferred updates.
D
duke 已提交
2737 2738 2739 2740 2741 2742 2743 2744
    for (unsigned int id = old_space_id; id < last_space_id; ++id) {
      verify_complete(SpaceId(id));
    }
#endif
  }

  {
    // Update the deferred objects, if any.  Any compaction manager can be used.
S
sla 已提交
2745
    GCTraceTime tm_du("deferred updates", print_phases(), true, &_gc_timer);
D
duke 已提交
2746 2747 2748 2749 2750
    ParCompactionManager* cm = ParCompactionManager::manager_array(0);
    for (unsigned int id = old_space_id; id < last_space_id; ++id) {
      update_deferred_objects(cm, SpaceId(id));
    }
  }
2751 2752

  DEBUG_ONLY(write_block_fill_histogram(gclog_or_tty));
D
duke 已提交
2753 2754 2755 2756
}

#ifdef  ASSERT
void PSParallelCompact::verify_complete(SpaceId space_id) {
2757 2758
  // All Regions between space bottom() to new_top() should be marked as filled
  // and all Regions between new_top() and top() should be available (i.e.,
D
duke 已提交
2759 2760 2761
  // should have been emptied).
  ParallelCompactData& sd = summary_data();
  SpaceInfo si = _space_info[space_id];
2762 2763 2764 2765 2766
  HeapWord* new_top_addr = sd.region_align_up(si.new_top());
  HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
  const size_t beg_region = sd.addr_to_region_idx(si.space()->bottom());
  const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
  const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
D
duke 已提交
2767 2768 2769

  bool issued_a_warning = false;

2770 2771 2772
  size_t cur_region;
  for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
    const RegionData* const c = sd.region(cur_region);
D
duke 已提交
2773
    if (!c->completed()) {
2774
      warning("region " SIZE_FORMAT " not filled:  "
D
duke 已提交
2775
              "destination_count=" SIZE_FORMAT,
2776
              cur_region, c->destination_count());
D
duke 已提交
2777 2778 2779 2780
      issued_a_warning = true;
    }
  }

2781 2782
  for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
    const RegionData* const c = sd.region(cur_region);
D
duke 已提交
2783
    if (!c->available()) {
2784
      warning("region " SIZE_FORMAT " not empty:   "
D
duke 已提交
2785
              "destination_count=" SIZE_FORMAT,
2786
              cur_region, c->destination_count());
D
duke 已提交
2787 2788 2789 2790 2791
      issued_a_warning = true;
    }
  }

  if (issued_a_warning) {
2792
    print_region_ranges();
D
duke 已提交
2793 2794 2795 2796
  }
}
#endif  // #ifdef ASSERT

2797
// Update interior oops in the ranges of regions [beg_region, end_region).
D
duke 已提交
2798 2799 2800
void
PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,
                                                       SpaceId space_id,
2801 2802
                                                       size_t beg_region,
                                                       size_t end_region) {
D
duke 已提交
2803 2804 2805
  ParallelCompactData& sd = summary_data();
  ParMarkBitMap* const mbm = mark_bitmap();

2806 2807 2808
  HeapWord* beg_addr = sd.region_to_addr(beg_region);
  HeapWord* const end_addr = sd.region_to_addr(end_region);
  assert(beg_region <= end_region, "bad region range");
D
duke 已提交
2809 2810 2811
  assert(end_addr <= dense_prefix(space_id), "not in the dense prefix");

#ifdef  ASSERT
2812
  // Claim the regions to avoid triggering an assert when they are marked as
D
duke 已提交
2813
  // filled.
2814 2815
  for (size_t claim_region = beg_region; claim_region < end_region; ++claim_region) {
    assert(sd.region(claim_region)->claim_unsafe(), "claim() failed");
D
duke 已提交
2816 2817 2818 2819 2820
  }
#endif  // #ifdef ASSERT

  if (beg_addr != space(space_id)->bottom()) {
    // Find the first live object or block of dead space that *starts* in this
2821 2822 2823 2824 2825 2826
    // range of regions.  If a partial object crosses onto the region, skip it;
    // it will be marked for 'deferred update' when the object head is
    // processed.  If dead space crosses onto the region, it is also skipped; it
    // will be filled when the prior region is processed.  If neither of those
    // apply, the first word in the region is the start of a live object or dead
    // space.
D
duke 已提交
2827
    assert(beg_addr > space(space_id)->bottom(), "sanity");
2828
    const RegionData* const cp = sd.region(beg_region);
D
duke 已提交
2829
    if (cp->partial_obj_size() != 0) {
2830
      beg_addr = sd.partial_obj_end(beg_region);
D
duke 已提交
2831 2832 2833 2834 2835 2836
    } else if (dead_space_crosses_boundary(cp, mbm->addr_to_bit(beg_addr))) {
      beg_addr = mbm->find_obj_beg(beg_addr, end_addr);
    }
  }

  if (beg_addr < end_addr) {
2837
    // A live object or block of dead space starts in this range of Regions.
D
duke 已提交
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
     HeapWord* const dense_prefix_end = dense_prefix(space_id);

    // Create closures and iterate.
    UpdateOnlyClosure update_closure(mbm, cm, space_id);
    FillClosure fill_closure(cm, space_id);
    ParMarkBitMap::IterationStatus status;
    status = mbm->iterate(&update_closure, &fill_closure, beg_addr, end_addr,
                          dense_prefix_end);
    if (status == ParMarkBitMap::incomplete) {
      update_closure.do_addr(update_closure.source());
    }
  }

2851 2852 2853 2854
  // Mark the regions as filled.
  RegionData* const beg_cp = sd.region(beg_region);
  RegionData* const end_cp = sd.region(end_region);
  for (RegionData* cp = beg_cp; cp < end_cp; ++cp) {
D
duke 已提交
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
    cp->set_completed();
  }
}

// Return the SpaceId for the space containing addr.  If addr is not in the
// heap, last_space_id is returned.  In debug mode it expects the address to be
// in the heap and asserts such.
PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
  assert(Universe::heap()->is_in_reserved(addr), "addr not in the heap");

2865
  for (unsigned int id = old_space_id; id < last_space_id; ++id) {
D
duke 已提交
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
    if (_space_info[id].space()->contains(addr)) {
      return SpaceId(id);
    }
  }

  assert(false, "no space contains the addr");
  return last_space_id;
}

void PSParallelCompact::update_deferred_objects(ParCompactionManager* cm,
                                                SpaceId id) {
  assert(id < last_space_id, "bad space id");

  ParallelCompactData& sd = summary_data();
  const SpaceInfo* const space_info = _space_info + id;
  ObjectStartArray* const start_array = space_info->start_array();

  const MutableSpace* const space = space_info->space();
  assert(space_info->dense_prefix() >= space->bottom(), "dense_prefix not set");
  HeapWord* const beg_addr = space_info->dense_prefix();
2886
  HeapWord* const end_addr = sd.region_align_up(space_info->new_top());
D
duke 已提交
2887

2888 2889 2890 2891 2892
  const RegionData* const beg_region = sd.addr_to_region_ptr(beg_addr);
  const RegionData* const end_region = sd.addr_to_region_ptr(end_addr);
  const RegionData* cur_region;
  for (cur_region = beg_region; cur_region < end_region; ++cur_region) {
    HeapWord* const addr = cur_region->deferred_obj_addr();
D
duke 已提交
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
    if (addr != NULL) {
      if (start_array != NULL) {
        start_array->allocate_block(addr);
      }
      oop(addr)->update_contents(cm);
      assert(oop(addr)->is_oop_or_null(), "should be an oop now");
    }
  }
}

// Skip over count live words starting from beg, and return the address of the
// next live word.  Unless marked, the word corresponding to beg is assumed to
// be dead.  Callers must either ensure beg does not correspond to the middle of
// an object, or account for those live words in some other way.  Callers must
// also ensure that there are enough live words in the range [beg, end) to skip.
HeapWord*
PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
{
  assert(count > 0, "sanity");

  ParMarkBitMap* m = mark_bitmap();
  idx_t bits_to_skip = m->words_to_bits(count);
  idx_t cur_beg = m->addr_to_bit(beg);
  const idx_t search_end = BitMap::word_align_up(m->addr_to_bit(end));

  do {
    cur_beg = m->find_obj_beg(cur_beg, search_end);
    idx_t cur_end = m->find_obj_end(cur_beg, search_end);
    const size_t obj_bits = cur_end - cur_beg + 1;
    if (obj_bits > bits_to_skip) {
      return m->bit_to_addr(cur_beg + bits_to_skip);
    }
    bits_to_skip -= obj_bits;
    cur_beg = cur_end + 1;
  } while (bits_to_skip > 0);

  // Skipping the desired number of words landed just past the end of an object.
  // Find the start of the next object.
  cur_beg = m->find_obj_beg(cur_beg, search_end);
  assert(cur_beg < m->addr_to_bit(end), "not enough live words to skip");
  return m->bit_to_addr(cur_beg);
}

2936 2937 2938
HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
                                            SpaceId src_space_id,
                                            size_t src_region_idx)
D
duke 已提交
2939
{
2940 2941 2942 2943 2944 2945 2946 2947 2948
  assert(summary_data().is_region_aligned(dest_addr), "not aligned");

  const SplitInfo& split_info = _space_info[src_space_id].split_info();
  if (split_info.dest_region_addr() == dest_addr) {
    // The partial object ending at the split point contains the first word to
    // be copied to dest_addr.
    return split_info.first_src_addr();
  }

D
duke 已提交
2949
  const ParallelCompactData& sd = summary_data();
2950
  ParMarkBitMap* const bitmap = mark_bitmap();
2951
  const size_t RegionSize = ParallelCompactData::RegionSize;
D
duke 已提交
2952

2953 2954 2955 2956
  assert(sd.is_region_aligned(dest_addr), "not aligned");
  const RegionData* const src_region_ptr = sd.region(src_region_idx);
  const size_t partial_obj_size = src_region_ptr->partial_obj_size();
  HeapWord* const src_region_destination = src_region_ptr->destination();
D
duke 已提交
2957

2958 2959
  assert(dest_addr >= src_region_destination, "wrong src region");
  assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
D
duke 已提交
2960

2961 2962
  HeapWord* const src_region_beg = sd.region_to_addr(src_region_idx);
  HeapWord* const src_region_end = src_region_beg + RegionSize;
D
duke 已提交
2963

2964 2965 2966
  HeapWord* addr = src_region_beg;
  if (dest_addr == src_region_destination) {
    // Return the first live word in the source region.
D
duke 已提交
2967
    if (partial_obj_size == 0) {
2968 2969
      addr = bitmap->find_obj_beg(addr, src_region_end);
      assert(addr < src_region_end, "no objects start in src region");
D
duke 已提交
2970 2971 2972 2973 2974
    }
    return addr;
  }

  // Must skip some live data.
2975 2976
  size_t words_to_skip = dest_addr - src_region_destination;
  assert(src_region_ptr->data_size() > words_to_skip, "wrong src region");
D
duke 已提交
2977 2978 2979 2980 2981 2982

  if (partial_obj_size >= words_to_skip) {
    // All the live words to skip are part of the partial object.
    addr += words_to_skip;
    if (partial_obj_size == words_to_skip) {
      // Find the first live word past the partial object.
2983 2984
      addr = bitmap->find_obj_beg(addr, src_region_end);
      assert(addr < src_region_end, "wrong src region");
D
duke 已提交
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
    }
    return addr;
  }

  // Skip over the partial object (if any).
  if (partial_obj_size != 0) {
    words_to_skip -= partial_obj_size;
    addr += partial_obj_size;
  }

2995 2996 2997
  // Skip over live words due to objects that start in the region.
  addr = skip_live_words(addr, src_region_end, words_to_skip);
  assert(addr < src_region_end, "wrong src region");
D
duke 已提交
2998 2999 3000 3001
  return addr;
}

void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
3002
                                                     SpaceId src_space_id,
3003
                                                     size_t beg_region,
D
duke 已提交
3004 3005 3006
                                                     HeapWord* end_addr)
{
  ParallelCompactData& sd = summary_data();
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016

#ifdef ASSERT
  MutableSpace* const src_space = _space_info[src_space_id].space();
  HeapWord* const beg_addr = sd.region_to_addr(beg_region);
  assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
         "src_space_id does not match beg_addr");
  assert(src_space->contains(end_addr) || end_addr == src_space->end(),
         "src_space_id does not match end_addr");
#endif // #ifdef ASSERT

3017
  RegionData* const beg = sd.region(beg_region);
3018 3019 3020 3021 3022 3023 3024 3025
  RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));

  // Regions up to new_top() are enqueued if they become available.
  HeapWord* const new_top = _space_info[src_space_id].new_top();
  RegionData* const enqueue_end =
    sd.addr_to_region_ptr(sd.region_align_up(new_top));

  for (RegionData* cur = beg; cur < end; ++cur) {
3026
    assert(cur->data_size() > 0, "region must have live data");
D
duke 已提交
3027
    cur->decrement_destination_count();
3028
    if (cur < enqueue_end && cur->available() && cur->claim()) {
3029
      cm->push_region(sd.region(cur));
D
duke 已提交
3030 3031 3032 3033
    }
  }
}

3034 3035 3036 3037
size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
                                          SpaceId& src_space_id,
                                          HeapWord*& src_space_top,
                                          HeapWord* end_addr)
D
duke 已提交
3038
{
3039
  typedef ParallelCompactData::RegionData RegionData;
D
duke 已提交
3040 3041

  ParallelCompactData& sd = PSParallelCompact::summary_data();
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
  const size_t region_size = ParallelCompactData::RegionSize;

  size_t src_region_idx = 0;

  // Skip empty regions (if any) up to the top of the space.
  HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
  RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
  HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
  const RegionData* const top_region_ptr =
    sd.addr_to_region_ptr(top_aligned_up);
  while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
    ++src_region_ptr;
  }

  if (src_region_ptr < top_region_ptr) {
    // The next source region is in the current space.  Update src_region_idx
    // and the source address to match src_region_ptr.
    src_region_idx = sd.region(src_region_ptr);
    HeapWord* const src_region_addr = sd.region_to_addr(src_region_idx);
    if (src_region_addr > closure.source()) {
      closure.set_source(src_region_addr);
D
duke 已提交
3063
    }
3064
    return src_region_idx;
D
duke 已提交
3065 3066
  }

3067
  // Switch to a new source space and find the first non-empty region.
D
duke 已提交
3068 3069 3070 3071 3072 3073 3074 3075
  unsigned int space_id = src_space_id + 1;
  assert(space_id < last_space_id, "not enough spaces");

  HeapWord* const destination = closure.destination();

  do {
    MutableSpace* space = _space_info[space_id].space();
    HeapWord* const bottom = space->bottom();
3076
    const RegionData* const bottom_cp = sd.addr_to_region_ptr(bottom);
D
duke 已提交
3077 3078 3079

    // Iterate over the spaces that do not compact into themselves.
    if (bottom_cp->destination() != bottom) {
3080 3081
      HeapWord* const top_aligned_up = sd.region_align_up(space->top());
      const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
D
duke 已提交
3082

3083
      for (const RegionData* src_cp = bottom_cp; src_cp < top_cp; ++src_cp) {
D
duke 已提交
3084 3085 3086 3087 3088 3089 3090 3091 3092
        if (src_cp->live_obj_size() > 0) {
          // Found it.
          assert(src_cp->destination() == destination,
                 "first live obj in the space must match the destination");
          assert(src_cp->partial_obj_size() == 0,
                 "a space cannot begin with a partial obj");

          src_space_id = SpaceId(space_id);
          src_space_top = space->top();
3093 3094 3095
          const size_t src_region_idx = sd.region(src_cp);
          closure.set_source(sd.region_to_addr(src_region_idx));
          return src_region_idx;
D
duke 已提交
3096 3097 3098 3099 3100 3101 3102
        } else {
          assert(src_cp->data_size() == 0, "sanity");
        }
      }
    }
  } while (++space_id < last_space_id);

3103
  assert(false, "no source region was found");
D
duke 已提交
3104 3105 3106
  return 0;
}

3107
void PSParallelCompact::fill_region(ParCompactionManager* cm, size_t region_idx)
D
duke 已提交
3108 3109
{
  typedef ParMarkBitMap::IterationStatus IterationStatus;
3110
  const size_t RegionSize = ParallelCompactData::RegionSize;
D
duke 已提交
3111 3112
  ParMarkBitMap* const bitmap = mark_bitmap();
  ParallelCompactData& sd = summary_data();
3113
  RegionData* const region_ptr = sd.region(region_idx);
D
duke 已提交
3114 3115

  // Get the items needed to construct the closure.
3116
  HeapWord* dest_addr = sd.region_to_addr(region_idx);
D
duke 已提交
3117 3118 3119 3120
  SpaceId dest_space_id = space_id(dest_addr);
  ObjectStartArray* start_array = _space_info[dest_space_id].start_array();
  HeapWord* new_top = _space_info[dest_space_id].new_top();
  assert(dest_addr < new_top, "sanity");
3121
  const size_t words = MIN2(pointer_delta(new_top, dest_addr), RegionSize);
D
duke 已提交
3122

3123 3124 3125
  // Get the source region and related info.
  size_t src_region_idx = region_ptr->source_region();
  SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
D
duke 已提交
3126 3127 3128
  HeapWord* src_space_top = _space_info[src_space_id].space()->top();

  MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);
3129
  closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
D
duke 已提交
3130

3131 3132 3133 3134
  // Adjust src_region_idx to prepare for decrementing destination counts (the
  // destination count is not decremented when a region is copied to itself).
  if (src_region_idx == region_idx) {
    src_region_idx += 1;
D
duke 已提交
3135 3136 3137 3138 3139 3140 3141 3142 3143
  }

  if (bitmap->is_unmarked(closure.source())) {
    // The first source word is in the middle of an object; copy the remainder
    // of the object or as much as will fit.  The fact that pointer updates were
    // deferred will be noted when the object header is processed.
    HeapWord* const old_src_addr = closure.source();
    closure.copy_partial_obj();
    if (closure.is_full()) {
3144 3145
      decrement_destination_counts(cm, src_space_id, src_region_idx,
                                   closure.source());
3146 3147
      region_ptr->set_deferred_obj_addr(NULL);
      region_ptr->set_completed();
D
duke 已提交
3148 3149 3150
      return;
    }

3151 3152 3153
    HeapWord* const end_addr = sd.region_align_down(closure.source());
    if (sd.region_align_down(old_src_addr) != end_addr) {
      // The partial object was copied from more than one source region.
3154
      decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
D
duke 已提交
3155

3156
      // Move to the next source region, possibly switching spaces as well.  All
D
duke 已提交
3157
      // args except end_addr may be modified.
3158 3159
      src_region_idx = next_src_region(closure, src_space_id, src_space_top,
                                       end_addr);
D
duke 已提交
3160 3161 3162 3163 3164
    }
  }

  do {
    HeapWord* const cur_addr = closure.source();
3165
    HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
D
duke 已提交
3166 3167 3168 3169
                                    src_space_top);
    IterationStatus status = bitmap->iterate(&closure, cur_addr, end_addr);

    if (status == ParMarkBitMap::incomplete) {
3170 3171
      // The last obj that starts in the source region does not end in the
      // region.
3172
      assert(closure.source() < end_addr, "sanity");
D
duke 已提交
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
      HeapWord* const obj_beg = closure.source();
      HeapWord* const range_end = MIN2(obj_beg + closure.words_remaining(),
                                       src_space_top);
      HeapWord* const obj_end = bitmap->find_obj_end(obj_beg, range_end);
      if (obj_end < range_end) {
        // The end was found; the entire object will fit.
        status = closure.do_addr(obj_beg, bitmap->obj_size(obj_beg, obj_end));
        assert(status != ParMarkBitMap::would_overflow, "sanity");
      } else {
        // The end was not found; the object will not fit.
        assert(range_end < src_space_top, "obj cannot cross space boundary");
        status = ParMarkBitMap::would_overflow;
      }
    }

    if (status == ParMarkBitMap::would_overflow) {
      // The last object did not fit.  Note that interior oop updates were
3190 3191
      // deferred, then copy enough of the object to fill the region.
      region_ptr->set_deferred_obj_addr(closure.destination());
D
duke 已提交
3192 3193
      status = closure.copy_until_full(); // copies from closure.source()

3194 3195
      decrement_destination_counts(cm, src_space_id, src_region_idx,
                                   closure.source());
3196
      region_ptr->set_completed();
D
duke 已提交
3197 3198 3199 3200
      return;
    }

    if (status == ParMarkBitMap::full) {
3201 3202
      decrement_destination_counts(cm, src_space_id, src_region_idx,
                                   closure.source());
3203 3204
      region_ptr->set_deferred_obj_addr(NULL);
      region_ptr->set_completed();
D
duke 已提交
3205 3206 3207
      return;
    }

3208
    decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
D
duke 已提交
3209

3210
    // Move to the next source region, possibly switching spaces as well.  All
D
duke 已提交
3211
    // args except end_addr may be modified.
3212 3213
    src_region_idx = next_src_region(closure, src_space_id, src_space_top,
                                     end_addr);
D
duke 已提交
3214 3215 3216
  } while (true);
}

3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
void PSParallelCompact::fill_blocks(size_t region_idx)
{
  // Fill in the block table elements for the specified region.  Each block
  // table element holds the number of live words in the region that are to the
  // left of the first object that starts in the block.  Thus only blocks in
  // which an object starts need to be filled.
  //
  // The algorithm scans the section of the bitmap that corresponds to the
  // region, keeping a running total of the live words.  When an object start is
  // found, if it's the first to start in the block that contains it, the
  // current total is written to the block table element.
  const size_t Log2BlockSize = ParallelCompactData::Log2BlockSize;
  const size_t Log2RegionSize = ParallelCompactData::Log2RegionSize;
  const size_t RegionSize = ParallelCompactData::RegionSize;

  ParallelCompactData& sd = summary_data();
  const size_t partial_obj_size = sd.region(region_idx)->partial_obj_size();
  if (partial_obj_size >= RegionSize) {
    return; // No objects start in this region.
  }

  // Ensure the first loop iteration decides that the block has changed.
  size_t cur_block = sd.block_count();

  const ParMarkBitMap* const bitmap = mark_bitmap();

  const size_t Log2BitsPerBlock = Log2BlockSize - LogMinObjAlignment;
  assert((size_t)1 << Log2BitsPerBlock ==
         bitmap->words_to_bits(ParallelCompactData::BlockSize), "sanity");

  size_t beg_bit = bitmap->words_to_bits(region_idx << Log2RegionSize);
  const size_t range_end = beg_bit + bitmap->words_to_bits(RegionSize);
  size_t live_bits = bitmap->words_to_bits(partial_obj_size);
  beg_bit = bitmap->find_obj_beg(beg_bit + live_bits, range_end);
  while (beg_bit < range_end) {
    const size_t new_block = beg_bit >> Log2BitsPerBlock;
    if (new_block != cur_block) {
      cur_block = new_block;
      sd.block(cur_block)->set_offset(bitmap->bits_to_words(live_bits));
    }

    const size_t end_bit = bitmap->find_obj_end(beg_bit, range_end);
    if (end_bit < range_end - 1) {
      live_bits += end_bit - beg_bit + 1;
      beg_bit = bitmap->find_obj_beg(end_bit + 1, range_end);
    } else {
      return;
    }
  }
}

D
duke 已提交
3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
void
PSParallelCompact::move_and_update(ParCompactionManager* cm, SpaceId space_id) {
  const MutableSpace* sp = space(space_id);
  if (sp->is_empty()) {
    return;
  }

  ParallelCompactData& sd = PSParallelCompact::summary_data();
  ParMarkBitMap* const bitmap = mark_bitmap();
  HeapWord* const dp_addr = dense_prefix(space_id);
  HeapWord* beg_addr = sp->bottom();
  HeapWord* end_addr = sp->top();

  assert(beg_addr <= dp_addr && dp_addr <= end_addr, "bad dense prefix");

3283 3284 3285 3286
  const size_t beg_region = sd.addr_to_region_idx(beg_addr);
  const size_t dp_region = sd.addr_to_region_idx(dp_addr);
  if (beg_region < dp_region) {
    update_and_deadwood_in_dense_prefix(cm, space_id, beg_region, dp_region);
D
duke 已提交
3287 3288
  }

3289 3290 3291
  // The destination of the first live object that starts in the region is one
  // past the end of the partial object entering the region (if any).
  HeapWord* const dest_addr = sd.partial_obj_end(dp_region);
D
duke 已提交
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308
  HeapWord* const new_top = _space_info[space_id].new_top();
  assert(new_top >= dest_addr, "bad new_top value");
  const size_t words = pointer_delta(new_top, dest_addr);

  if (words > 0) {
    ObjectStartArray* start_array = _space_info[space_id].start_array();
    MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);

    ParMarkBitMap::IterationStatus status;
    status = bitmap->iterate(&closure, dest_addr, end_addr);
    assert(status == ParMarkBitMap::full, "iteration not complete");
    assert(bitmap->find_obj_beg(closure.source(), end_addr) == end_addr,
           "live objects skipped because closure is full");
  }
}

jlong PSParallelCompact::millis_since_last_gc() {
3309 3310 3311 3312
  // We need a monotonically non-deccreasing time in ms but
  // os::javaTimeMillis() does not guarantee monotonicity.
  jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  jlong ret_val = now - _time_of_last_gc;
D
duke 已提交
3313 3314
  // XXX See note in genCollectedHeap::millis_since_last_gc().
  if (ret_val < 0) {
3315
    NOT_PRODUCT(warning("time warp: "INT64_FORMAT, ret_val);)
D
duke 已提交
3316 3317 3318 3319 3320 3321
    return 0;
  }
  return ret_val;
}

void PSParallelCompact::reset_millis_since_last_gc() {
3322 3323 3324
  // We need a monotonically non-deccreasing time in ms but
  // os::javaTimeMillis() does not guarantee monotonicity.
  _time_of_last_gc = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
D
duke 已提交
3325 3326 3327 3328 3329
}

ParMarkBitMap::IterationStatus MoveAndUpdateClosure::copy_until_full()
{
  if (source() != destination()) {
3330
    DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
D
duke 已提交
3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350
    Copy::aligned_conjoint_words(source(), destination(), words_remaining());
  }
  update_state(words_remaining());
  assert(is_full(), "sanity");
  return ParMarkBitMap::full;
}

void MoveAndUpdateClosure::copy_partial_obj()
{
  size_t words = words_remaining();

  HeapWord* const range_end = MIN2(source() + words, bitmap()->region_end());
  HeapWord* const end_addr = bitmap()->find_obj_end(source(), range_end);
  if (end_addr < range_end) {
    words = bitmap()->obj_size(source(), end_addr);
  }

  // This test is necessary; if omitted, the pointer updates to a partial object
  // that crosses the dense prefix boundary could be overwritten.
  if (source() != destination()) {
3351
    DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
D
duke 已提交
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
    Copy::aligned_conjoint_words(source(), destination(), words);
  }
  update_state(words);
}

ParMarkBitMapClosure::IterationStatus
MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
  assert(destination() != NULL, "sanity");
  assert(bitmap()->obj_size(addr) == words, "bad size");

  _source = addr;
  assert(PSParallelCompact::summary_data().calc_new_pointer(source()) ==
         destination(), "wrong destination");

  if (words > words_remaining()) {
    return ParMarkBitMap::would_overflow;
  }

  // The start_array must be updated even if the object is not moving.
  if (_start_array != NULL) {
    _start_array->allocate_block(destination());
  }

  if (destination() != source()) {
3376
    DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
D
duke 已提交
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
    Copy::aligned_conjoint_words(source(), destination(), words);
  }

  oop moved_oop = (oop) destination();
  moved_oop->update_contents(compaction_manager());
  assert(moved_oop->is_oop_or_null(), "Object should be whole at this point");

  update_state(words);
  assert(destination() == (HeapWord*)moved_oop + moved_oop->size(), "sanity");
  return is_full() ? ParMarkBitMap::full : ParMarkBitMap::incomplete;
}

UpdateOnlyClosure::UpdateOnlyClosure(ParMarkBitMap* mbm,
                                     ParCompactionManager* cm,
                                     PSParallelCompact::SpaceId space_id) :
  ParMarkBitMapClosure(mbm, cm),
  _space_id(space_id),
  _start_array(PSParallelCompact::start_array(space_id))
{
}

// Updates the references in the object to their new values.
ParMarkBitMapClosure::IterationStatus
UpdateOnlyClosure::do_addr(HeapWord* addr, size_t words) {
  do_addr(addr);
  return ParMarkBitMap::incomplete;
}