Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
38920 views
/*1* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/symbolTable.hpp"26#include "classfile/systemDictionary.hpp"27#include "code/codeCache.hpp"28#include "gc_implementation/parallelScavenge/gcTaskManager.hpp"29#include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"30#include "gc_implementation/parallelScavenge/pcTasks.hpp"31#include "gc_implementation/parallelScavenge/psAdaptiveSizePolicy.hpp"32#include "gc_implementation/parallelScavenge/psCompactionManager.inline.hpp"33#include "gc_implementation/parallelScavenge/psMarkSweep.hpp"34#include "gc_implementation/parallelScavenge/psMarkSweepDecorator.hpp"35#include "gc_implementation/parallelScavenge/psOldGen.hpp"36#include "gc_implementation/parallelScavenge/psParallelCompact.hpp"37#include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"38#include "gc_implementation/parallelScavenge/psScavenge.hpp"39#include "gc_implementation/parallelScavenge/psYoungGen.hpp"40#include "gc_implementation/shared/gcHeapSummary.hpp"41#include "gc_implementation/shared/gcTimer.hpp"42#include "gc_implementation/shared/gcTrace.hpp"43#include "gc_implementation/shared/gcTraceTime.hpp"44#include "gc_implementation/shared/isGCActiveMark.hpp"45#include "gc_interface/gcCause.hpp"46#include "memory/gcLocker.inline.hpp"47#include "memory/referencePolicy.hpp"48#include "memory/referenceProcessor.hpp"49#include "oops/methodData.hpp"50#include "oops/oop.inline.hpp"51#include "oops/oop.pcgc.inline.hpp"52#include "runtime/fprofiler.hpp"53#include "runtime/safepoint.hpp"54#include "runtime/vmThread.hpp"55#include "services/management.hpp"56#include "services/memoryService.hpp"57#include "services/memTracker.hpp"58#include "utilities/events.hpp"59#include "utilities/stack.inline.hpp"60#if INCLUDE_JFR61#include "jfr/jfr.hpp"62#endif // INCLUDE_JFR6364#include <math.h>6566PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC6768// All sizes are in HeapWords.69const size_t ParallelCompactData::Log2RegionSize = 16; // 64K words70const size_t ParallelCompactData::RegionSize = (size_t)1 << Log2RegionSize;71const size_t ParallelCompactData::RegionSizeBytes =72RegionSize << LogHeapWordSize;73const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;74const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;75const size_t ParallelCompactData::RegionAddrMask = ~RegionAddrOffsetMask;7677const size_t ParallelCompactData::Log2BlockSize = 7; // 128 words78const size_t ParallelCompactData::BlockSize = (size_t)1 << Log2BlockSize;79const size_t ParallelCompactData::BlockSizeBytes =80BlockSize << LogHeapWordSize;81const size_t ParallelCompactData::BlockSizeOffsetMask = BlockSize - 1;82const size_t ParallelCompactData::BlockAddrOffsetMask = BlockSizeBytes - 1;83const size_t ParallelCompactData::BlockAddrMask = ~BlockAddrOffsetMask;8485const size_t ParallelCompactData::BlocksPerRegion = RegionSize / BlockSize;86const size_t ParallelCompactData::Log2BlocksPerRegion =87Log2RegionSize - Log2BlockSize;8889const ParallelCompactData::RegionData::region_sz_t90ParallelCompactData::RegionData::dc_shift = 27;9192const ParallelCompactData::RegionData::region_sz_t93ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;9495const ParallelCompactData::RegionData::region_sz_t96ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;9798const ParallelCompactData::RegionData::region_sz_t99ParallelCompactData::RegionData::los_mask = ~dc_mask;100101const ParallelCompactData::RegionData::region_sz_t102ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;103104const ParallelCompactData::RegionData::region_sz_t105ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;106107SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];108bool PSParallelCompact::_print_phases = false;109110ReferenceProcessor* PSParallelCompact::_ref_processor = NULL;111Klass* PSParallelCompact::_updated_int_array_klass_obj = NULL;112113double PSParallelCompact::_dwl_mean;114double PSParallelCompact::_dwl_std_dev;115double PSParallelCompact::_dwl_first_term;116double PSParallelCompact::_dwl_adjustment;117#ifdef ASSERT118bool PSParallelCompact::_dwl_initialized = false;119#endif // #ifdef ASSERT120121void SplitInfo::record(size_t src_region_idx, size_t partial_obj_size,122HeapWord* destination)123{124assert(src_region_idx != 0, "invalid src_region_idx");125assert(partial_obj_size != 0, "invalid partial_obj_size argument");126assert(destination != NULL, "invalid destination argument");127128_src_region_idx = src_region_idx;129_partial_obj_size = partial_obj_size;130_destination = destination;131132// These fields may not be updated below, so make sure they're clear.133assert(_dest_region_addr == NULL, "should have been cleared");134assert(_first_src_addr == NULL, "should have been cleared");135136// Determine the number of destination regions for the partial object.137HeapWord* const last_word = destination + partial_obj_size - 1;138const ParallelCompactData& sd = PSParallelCompact::summary_data();139HeapWord* const beg_region_addr = sd.region_align_down(destination);140HeapWord* const end_region_addr = sd.region_align_down(last_word);141142if (beg_region_addr == end_region_addr) {143// One destination region.144_destination_count = 1;145if (end_region_addr == destination) {146// The destination falls on a region boundary, thus the first word of the147// partial object will be the first word copied to the destination region.148_dest_region_addr = end_region_addr;149_first_src_addr = sd.region_to_addr(src_region_idx);150}151} else {152// Two destination regions. When copied, the partial object will cross a153// destination region boundary, so a word somewhere within the partial154// object will be the first word copied to the second destination region.155_destination_count = 2;156_dest_region_addr = end_region_addr;157const size_t ofs = pointer_delta(end_region_addr, destination);158assert(ofs < _partial_obj_size, "sanity");159_first_src_addr = sd.region_to_addr(src_region_idx) + ofs;160}161}162163void SplitInfo::clear()164{165_src_region_idx = 0;166_partial_obj_size = 0;167_destination = NULL;168_destination_count = 0;169_dest_region_addr = NULL;170_first_src_addr = NULL;171assert(!is_valid(), "sanity");172}173174#ifdef ASSERT175void SplitInfo::verify_clear()176{177assert(_src_region_idx == 0, "not clear");178assert(_partial_obj_size == 0, "not clear");179assert(_destination == NULL, "not clear");180assert(_destination_count == 0, "not clear");181assert(_dest_region_addr == NULL, "not clear");182assert(_first_src_addr == NULL, "not clear");183}184#endif // #ifdef ASSERT185186187void PSParallelCompact::print_on_error(outputStream* st) {188_mark_bitmap.print_on_error(st);189}190191#ifndef PRODUCT192const char* PSParallelCompact::space_names[] = {193"old ", "eden", "from", "to "194};195196void PSParallelCompact::print_region_ranges()197{198tty->print_cr("space bottom top end new_top");199tty->print_cr("------ ---------- ---------- ---------- ----------");200201for (unsigned int id = 0; id < last_space_id; ++id) {202const MutableSpace* space = _space_info[id].space();203tty->print_cr("%u %s "204SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " "205SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ",206id, space_names[id],207summary_data().addr_to_region_idx(space->bottom()),208summary_data().addr_to_region_idx(space->top()),209summary_data().addr_to_region_idx(space->end()),210summary_data().addr_to_region_idx(_space_info[id].new_top()));211}212}213214void215print_generic_summary_region(size_t i, const ParallelCompactData::RegionData* c)216{217#define REGION_IDX_FORMAT SIZE_FORMAT_W(7)218#define REGION_DATA_FORMAT SIZE_FORMAT_W(5)219220ParallelCompactData& sd = PSParallelCompact::summary_data();221size_t dci = c->destination() ? sd.addr_to_region_idx(c->destination()) : 0;222tty->print_cr(REGION_IDX_FORMAT " " PTR_FORMAT " "223REGION_IDX_FORMAT " " PTR_FORMAT " "224REGION_DATA_FORMAT " " REGION_DATA_FORMAT " "225REGION_DATA_FORMAT " " REGION_IDX_FORMAT " %d",226i, c->data_location(), dci, c->destination(),227c->partial_obj_size(), c->live_obj_size(),228c->data_size(), c->source_region(), c->destination_count());229230#undef REGION_IDX_FORMAT231#undef REGION_DATA_FORMAT232}233234void235print_generic_summary_data(ParallelCompactData& summary_data,236HeapWord* const beg_addr,237HeapWord* const end_addr)238{239size_t total_words = 0;240size_t i = summary_data.addr_to_region_idx(beg_addr);241const size_t last = summary_data.addr_to_region_idx(end_addr);242HeapWord* pdest = 0;243244while (i <= last) {245ParallelCompactData::RegionData* c = summary_data.region(i);246if (c->data_size() != 0 || c->destination() != pdest) {247print_generic_summary_region(i, c);248total_words += c->data_size();249pdest = c->destination();250}251++i;252}253254tty->print_cr("summary_data_bytes=" SIZE_FORMAT, total_words * HeapWordSize);255}256257void258print_generic_summary_data(ParallelCompactData& summary_data,259SpaceInfo* space_info)260{261for (unsigned int id = 0; id < PSParallelCompact::last_space_id; ++id) {262const MutableSpace* space = space_info[id].space();263print_generic_summary_data(summary_data, space->bottom(),264MAX2(space->top(), space_info[id].new_top()));265}266}267268void269print_initial_summary_region(size_t i,270const ParallelCompactData::RegionData* c,271bool newline = true)272{273tty->print(SIZE_FORMAT_W(5) " " PTR_FORMAT " "274SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " "275SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",276i, c->destination(),277c->partial_obj_size(), c->live_obj_size(),278c->data_size(), c->source_region(), c->destination_count());279if (newline) tty->cr();280}281282void283print_initial_summary_data(ParallelCompactData& summary_data,284const MutableSpace* space) {285if (space->top() == space->bottom()) {286return;287}288289const size_t region_size = ParallelCompactData::RegionSize;290typedef ParallelCompactData::RegionData RegionData;291HeapWord* const top_aligned_up = summary_data.region_align_up(space->top());292const size_t end_region = summary_data.addr_to_region_idx(top_aligned_up);293const RegionData* c = summary_data.region(end_region - 1);294HeapWord* end_addr = c->destination() + c->data_size();295const size_t live_in_space = pointer_delta(end_addr, space->bottom());296297// Print (and count) the full regions at the beginning of the space.298size_t full_region_count = 0;299size_t i = summary_data.addr_to_region_idx(space->bottom());300while (i < end_region && summary_data.region(i)->data_size() == region_size) {301print_initial_summary_region(i, summary_data.region(i));302++full_region_count;303++i;304}305306size_t live_to_right = live_in_space - full_region_count * region_size;307308double max_reclaimed_ratio = 0.0;309size_t max_reclaimed_ratio_region = 0;310size_t max_dead_to_right = 0;311size_t max_live_to_right = 0;312313// Print the 'reclaimed ratio' for regions while there is something live in314// the region or to the right of it. The remaining regions are empty (and315// uninteresting), and computing the ratio will result in division by 0.316while (i < end_region && live_to_right > 0) {317c = summary_data.region(i);318HeapWord* const region_addr = summary_data.region_to_addr(i);319const size_t used_to_right = pointer_delta(space->top(), region_addr);320const size_t dead_to_right = used_to_right - live_to_right;321const double reclaimed_ratio = double(dead_to_right) / live_to_right;322323if (reclaimed_ratio > max_reclaimed_ratio) {324max_reclaimed_ratio = reclaimed_ratio;325max_reclaimed_ratio_region = i;326max_dead_to_right = dead_to_right;327max_live_to_right = live_to_right;328}329330print_initial_summary_region(i, c, false);331tty->print_cr(" %12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10),332reclaimed_ratio, dead_to_right, live_to_right);333334live_to_right -= c->data_size();335++i;336}337338// Any remaining regions are empty. Print one more if there is one.339if (i < end_region) {340print_initial_summary_region(i, summary_data.region(i));341}342343tty->print_cr("max: " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " "344"l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f",345max_reclaimed_ratio_region, max_dead_to_right,346max_live_to_right, max_reclaimed_ratio);347}348349void350print_initial_summary_data(ParallelCompactData& summary_data,351SpaceInfo* space_info) {352unsigned int id = PSParallelCompact::old_space_id;353const MutableSpace* space;354do {355space = space_info[id].space();356print_initial_summary_data(summary_data, space);357} while (++id < PSParallelCompact::eden_space_id);358359do {360space = space_info[id].space();361print_generic_summary_data(summary_data, space->bottom(), space->top());362} while (++id < PSParallelCompact::last_space_id);363}364#endif // #ifndef PRODUCT365366#ifdef ASSERT367size_t add_obj_count;368size_t add_obj_size;369size_t mark_bitmap_count;370size_t mark_bitmap_size;371#endif // #ifdef ASSERT372373ParallelCompactData::ParallelCompactData()374{375_region_start = 0;376377_region_vspace = 0;378_reserved_byte_size = 0;379_region_data = 0;380_region_count = 0;381382_block_vspace = 0;383_block_data = 0;384_block_count = 0;385}386387bool ParallelCompactData::initialize(MemRegion covered_region)388{389_region_start = covered_region.start();390const size_t region_size = covered_region.word_size();391DEBUG_ONLY(_region_end = _region_start + region_size;)392393assert(region_align_down(_region_start) == _region_start,394"region start not aligned");395assert((region_size & RegionSizeOffsetMask) == 0,396"region size not a multiple of RegionSize");397398bool result = initialize_region_data(region_size) && initialize_block_data();399return result;400}401402PSVirtualSpace*403ParallelCompactData::create_vspace(size_t count, size_t element_size)404{405const size_t raw_bytes = count * element_size;406const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);407const size_t granularity = os::vm_allocation_granularity();408_reserved_byte_size = align_size_up(raw_bytes, MAX2(page_sz, granularity));409410const size_t rs_align = page_sz == (size_t) os::vm_page_size() ? 0 :411MAX2(page_sz, granularity);412ReservedSpace rs(_reserved_byte_size, rs_align, rs_align > 0);413os::trace_page_sizes("par compact", raw_bytes, raw_bytes, page_sz, rs.base(),414rs.size());415416MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);417418PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);419if (vspace != 0) {420if (vspace->expand_by(_reserved_byte_size)) {421return vspace;422}423delete vspace;424// Release memory reserved in the space.425rs.release();426}427428return 0;429}430431bool ParallelCompactData::initialize_region_data(size_t region_size)432{433const size_t count = (region_size + RegionSizeOffsetMask) >> Log2RegionSize;434_region_vspace = create_vspace(count, sizeof(RegionData));435if (_region_vspace != 0) {436_region_data = (RegionData*)_region_vspace->reserved_low_addr();437_region_count = count;438return true;439}440return false;441}442443bool ParallelCompactData::initialize_block_data()444{445assert(_region_count != 0, "region data must be initialized first");446const size_t count = _region_count << Log2BlocksPerRegion;447_block_vspace = create_vspace(count, sizeof(BlockData));448if (_block_vspace != 0) {449_block_data = (BlockData*)_block_vspace->reserved_low_addr();450_block_count = count;451return true;452}453return false;454}455456void ParallelCompactData::clear()457{458memset(_region_data, 0, _region_vspace->committed_size());459memset(_block_data, 0, _block_vspace->committed_size());460}461462void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {463assert(beg_region <= _region_count, "beg_region out of range");464assert(end_region <= _region_count, "end_region out of range");465assert(RegionSize % BlockSize == 0, "RegionSize not a multiple of BlockSize");466467const size_t region_cnt = end_region - beg_region;468memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));469470const size_t beg_block = beg_region * BlocksPerRegion;471const size_t block_cnt = region_cnt * BlocksPerRegion;472memset(_block_data + beg_block, 0, block_cnt * sizeof(BlockData));473}474475HeapWord* ParallelCompactData::partial_obj_end(size_t region_idx) const476{477const RegionData* cur_cp = region(region_idx);478const RegionData* const end_cp = region(region_count() - 1);479480HeapWord* result = region_to_addr(region_idx);481if (cur_cp < end_cp) {482do {483result += cur_cp->partial_obj_size();484} while (cur_cp->partial_obj_size() == RegionSize && ++cur_cp < end_cp);485}486return result;487}488489void ParallelCompactData::add_obj(HeapWord* addr, size_t len)490{491const size_t obj_ofs = pointer_delta(addr, _region_start);492const size_t beg_region = obj_ofs >> Log2RegionSize;493const size_t end_region = (obj_ofs + len - 1) >> Log2RegionSize;494495DEBUG_ONLY(Atomic::inc_ptr(&add_obj_count);)496DEBUG_ONLY(Atomic::add_ptr(len, &add_obj_size);)497498if (beg_region == end_region) {499// All in one region.500_region_data[beg_region].add_live_obj(len);501return;502}503504// First region.505const size_t beg_ofs = region_offset(addr);506_region_data[beg_region].add_live_obj(RegionSize - beg_ofs);507508Klass* klass = ((oop)addr)->klass();509// Middle regions--completely spanned by this object.510for (size_t region = beg_region + 1; region < end_region; ++region) {511_region_data[region].set_partial_obj_size(RegionSize);512_region_data[region].set_partial_obj_addr(addr);513}514515// Last region.516const size_t end_ofs = region_offset(addr + len - 1);517_region_data[end_region].set_partial_obj_size(end_ofs + 1);518_region_data[end_region].set_partial_obj_addr(addr);519}520521void522ParallelCompactData::summarize_dense_prefix(HeapWord* beg, HeapWord* end)523{524assert(region_offset(beg) == 0, "not RegionSize aligned");525assert(region_offset(end) == 0, "not RegionSize aligned");526527size_t cur_region = addr_to_region_idx(beg);528const size_t end_region = addr_to_region_idx(end);529HeapWord* addr = beg;530while (cur_region < end_region) {531_region_data[cur_region].set_destination(addr);532_region_data[cur_region].set_destination_count(0);533_region_data[cur_region].set_source_region(cur_region);534_region_data[cur_region].set_data_location(addr);535536// Update live_obj_size so the region appears completely full.537size_t live_size = RegionSize - _region_data[cur_region].partial_obj_size();538_region_data[cur_region].set_live_obj_size(live_size);539540++cur_region;541addr += RegionSize;542}543}544545// Find the point at which a space can be split and, if necessary, record the546// split point.547//548// If the current src region (which overflowed the destination space) doesn't549// have a partial object, the split point is at the beginning of the current src550// region (an "easy" split, no extra bookkeeping required).551//552// If the current src region has a partial object, the split point is in the553// region where that partial object starts (call it the split_region). If554// split_region has a partial object, then the split point is just after that555// partial object (a "hard" split where we have to record the split data and556// zero the partial_obj_size field). With a "hard" split, we know that the557// partial_obj ends within split_region because the partial object that caused558// the overflow starts in split_region. If split_region doesn't have a partial559// obj, then the split is at the beginning of split_region (another "easy"560// split).561HeapWord*562ParallelCompactData::summarize_split_space(size_t src_region,563SplitInfo& split_info,564HeapWord* destination,565HeapWord* target_end,566HeapWord** target_next)567{568assert(destination <= target_end, "sanity");569assert(destination + _region_data[src_region].data_size() > target_end,570"region should not fit into target space");571assert(is_region_aligned(target_end), "sanity");572573size_t split_region = src_region;574HeapWord* split_destination = destination;575size_t partial_obj_size = _region_data[src_region].partial_obj_size();576577if (destination + partial_obj_size > target_end) {578// The split point is just after the partial object (if any) in the579// src_region that contains the start of the object that overflowed the580// destination space.581//582// Find the start of the "overflow" object and set split_region to the583// region containing it.584HeapWord* const overflow_obj = _region_data[src_region].partial_obj_addr();585split_region = addr_to_region_idx(overflow_obj);586587// Clear the source_region field of all destination regions whose first word588// came from data after the split point (a non-null source_region field589// implies a region must be filled).590//591// An alternative to the simple loop below: clear during post_compact(),592// which uses memcpy instead of individual stores, and is easy to593// parallelize. (The downside is that it clears the entire RegionData594// object as opposed to just one field.)595//596// post_compact() would have to clear the summary data up to the highest597// address that was written during the summary phase, which would be598//599// max(top, max(new_top, clear_top))600//601// where clear_top is a new field in SpaceInfo. Would have to set clear_top602// to target_end.603const RegionData* const sr = region(split_region);604const size_t beg_idx =605addr_to_region_idx(region_align_up(sr->destination() +606sr->partial_obj_size()));607const size_t end_idx = addr_to_region_idx(target_end);608609if (TraceParallelOldGCSummaryPhase) {610gclog_or_tty->print_cr("split: clearing source_region field in ["611SIZE_FORMAT ", " SIZE_FORMAT ")",612beg_idx, end_idx);613}614for (size_t idx = beg_idx; idx < end_idx; ++idx) {615_region_data[idx].set_source_region(0);616}617618// Set split_destination and partial_obj_size to reflect the split region.619split_destination = sr->destination();620partial_obj_size = sr->partial_obj_size();621}622623// The split is recorded only if a partial object extends onto the region.624if (partial_obj_size != 0) {625_region_data[split_region].set_partial_obj_size(0);626split_info.record(split_region, partial_obj_size, split_destination);627}628629// Setup the continuation addresses.630*target_next = split_destination + partial_obj_size;631HeapWord* const source_next = region_to_addr(split_region) + partial_obj_size;632633if (TraceParallelOldGCSummaryPhase) {634const char * split_type = partial_obj_size == 0 ? "easy" : "hard";635gclog_or_tty->print_cr("%s split: src=" PTR_FORMAT " src_c=" SIZE_FORMAT636" pos=" SIZE_FORMAT,637split_type, source_next, split_region,638partial_obj_size);639gclog_or_tty->print_cr("%s split: dst=" PTR_FORMAT " dst_c=" SIZE_FORMAT640" tn=" PTR_FORMAT,641split_type, split_destination,642addr_to_region_idx(split_destination),643*target_next);644645if (partial_obj_size != 0) {646HeapWord* const po_beg = split_info.destination();647HeapWord* const po_end = po_beg + split_info.partial_obj_size();648gclog_or_tty->print_cr("%s split: "649"po_beg=" PTR_FORMAT " " SIZE_FORMAT " "650"po_end=" PTR_FORMAT " " SIZE_FORMAT,651split_type,652po_beg, addr_to_region_idx(po_beg),653po_end, addr_to_region_idx(po_end));654}655}656657return source_next;658}659660bool ParallelCompactData::summarize(SplitInfo& split_info,661HeapWord* source_beg, HeapWord* source_end,662HeapWord** source_next,663HeapWord* target_beg, HeapWord* target_end,664HeapWord** target_next)665{666if (TraceParallelOldGCSummaryPhase) {667HeapWord* const source_next_val = source_next == NULL ? NULL : *source_next;668tty->print_cr("sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT669"tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,670source_beg, source_end, source_next_val,671target_beg, target_end, *target_next);672}673674size_t cur_region = addr_to_region_idx(source_beg);675const size_t end_region = addr_to_region_idx(region_align_up(source_end));676677HeapWord *dest_addr = target_beg;678while (cur_region < end_region) {679// The destination must be set even if the region has no data.680_region_data[cur_region].set_destination(dest_addr);681682size_t words = _region_data[cur_region].data_size();683if (words > 0) {684// If cur_region does not fit entirely into the target space, find a point685// at which the source space can be 'split' so that part is copied to the686// target space and the rest is copied elsewhere.687if (dest_addr + words > target_end) {688assert(source_next != NULL, "source_next is NULL when splitting");689*source_next = summarize_split_space(cur_region, split_info, dest_addr,690target_end, target_next);691return false;692}693694// Compute the destination_count for cur_region, and if necessary, update695// source_region for a destination region. The source_region field is696// updated if cur_region is the first (left-most) region to be copied to a697// destination region.698//699// The destination_count calculation is a bit subtle. A region that has700// data that compacts into itself does not count itself as a destination.701// This maintains the invariant that a zero count means the region is702// available and can be claimed and then filled.703uint destination_count = 0;704if (split_info.is_split(cur_region)) {705// The current region has been split: the partial object will be copied706// to one destination space and the remaining data will be copied to707// another destination space. Adjust the initial destination_count and,708// if necessary, set the source_region field if the partial object will709// cross a destination region boundary.710destination_count = split_info.destination_count();711if (destination_count == 2) {712size_t dest_idx = addr_to_region_idx(split_info.dest_region_addr());713_region_data[dest_idx].set_source_region(cur_region);714}715}716717HeapWord* const last_addr = dest_addr + words - 1;718const size_t dest_region_1 = addr_to_region_idx(dest_addr);719const size_t dest_region_2 = addr_to_region_idx(last_addr);720721// Initially assume that the destination regions will be the same and722// adjust the value below if necessary. Under this assumption, if723// cur_region == dest_region_2, then cur_region will be compacted724// completely into itself.725destination_count += cur_region == dest_region_2 ? 0 : 1;726if (dest_region_1 != dest_region_2) {727// Destination regions differ; adjust destination_count.728destination_count += 1;729// Data from cur_region will be copied to the start of dest_region_2.730_region_data[dest_region_2].set_source_region(cur_region);731} else if (region_offset(dest_addr) == 0) {732// Data from cur_region will be copied to the start of the destination733// region.734_region_data[dest_region_1].set_source_region(cur_region);735}736737_region_data[cur_region].set_destination_count(destination_count);738_region_data[cur_region].set_data_location(region_to_addr(cur_region));739dest_addr += words;740}741742++cur_region;743}744745*target_next = dest_addr;746return true;747}748749HeapWord* ParallelCompactData::calc_new_pointer(HeapWord* addr) {750assert(addr != NULL, "Should detect NULL oop earlier");751assert(PSParallelCompact::gc_heap()->is_in(addr), "not in heap");752assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "not marked");753754// Region covering the object.755RegionData* const region_ptr = addr_to_region_ptr(addr);756HeapWord* result = region_ptr->destination();757758// If the entire Region is live, the new location is region->destination + the759// offset of the object within in the Region.760761// Run some performance tests to determine if this special case pays off. It762// is worth it for pointers into the dense prefix. If the optimization to763// avoid pointer updates in regions that only point to the dense prefix is764// ever implemented, this should be revisited.765if (region_ptr->data_size() == RegionSize) {766result += region_offset(addr);767return result;768}769770// Otherwise, the new location is region->destination + block offset + the771// number of live words in the Block that are (a) to the left of addr and (b)772// due to objects that start in the Block.773774// Fill in the block table if necessary. This is unsynchronized, so multiple775// threads may fill the block table for a region (harmless, since it is776// idempotent).777if (!region_ptr->blocks_filled()) {778PSParallelCompact::fill_blocks(addr_to_region_idx(addr));779region_ptr->set_blocks_filled();780}781782HeapWord* const search_start = block_align_down(addr);783const size_t block_offset = addr_to_block_ptr(addr)->offset();784785const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();786const size_t live = bitmap->live_words_in_range(search_start, oop(addr));787result += block_offset + live;788DEBUG_ONLY(PSParallelCompact::check_new_location(addr, result));789return result;790}791792#ifdef ASSERT793void ParallelCompactData::verify_clear(const PSVirtualSpace* vspace)794{795const size_t* const beg = (const size_t*)vspace->committed_low_addr();796const size_t* const end = (const size_t*)vspace->committed_high_addr();797for (const size_t* p = beg; p < end; ++p) {798assert(*p == 0, "not zero");799}800}801802void ParallelCompactData::verify_clear()803{804verify_clear(_region_vspace);805verify_clear(_block_vspace);806}807#endif // #ifdef ASSERT808809STWGCTimer PSParallelCompact::_gc_timer;810ParallelOldTracer PSParallelCompact::_gc_tracer;811elapsedTimer PSParallelCompact::_accumulated_time;812unsigned int PSParallelCompact::_total_invocations = 0;813unsigned int PSParallelCompact::_maximum_compaction_gc_num = 0;814jlong PSParallelCompact::_time_of_last_gc = 0;815CollectorCounters* PSParallelCompact::_counters = NULL;816ParMarkBitMap PSParallelCompact::_mark_bitmap;817ParallelCompactData PSParallelCompact::_summary_data;818819PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;820821bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }822823void PSParallelCompact::KeepAliveClosure::do_oop(oop* p) { PSParallelCompact::KeepAliveClosure::do_oop_work(p); }824void PSParallelCompact::KeepAliveClosure::do_oop(narrowOop* p) { PSParallelCompact::KeepAliveClosure::do_oop_work(p); }825826PSParallelCompact::AdjustPointerClosure PSParallelCompact::_adjust_pointer_closure;827PSParallelCompact::AdjustKlassClosure PSParallelCompact::_adjust_klass_closure;828829void PSParallelCompact::AdjustPointerClosure::do_oop(oop* p) { adjust_pointer(p); }830void PSParallelCompact::AdjustPointerClosure::do_oop(narrowOop* p) { adjust_pointer(p); }831832void PSParallelCompact::FollowStackClosure::do_void() { _compaction_manager->follow_marking_stacks(); }833834void PSParallelCompact::MarkAndPushClosure::do_oop(oop* p) {835mark_and_push(_compaction_manager, p);836}837void PSParallelCompact::MarkAndPushClosure::do_oop(narrowOop* p) { mark_and_push(_compaction_manager, p); }838839void PSParallelCompact::FollowKlassClosure::do_klass(Klass* klass) {840klass->oops_do(_mark_and_push_closure);841}842void PSParallelCompact::AdjustKlassClosure::do_klass(Klass* klass) {843klass->oops_do(&PSParallelCompact::_adjust_pointer_closure);844}845846void PSParallelCompact::post_initialize() {847ParallelScavengeHeap* heap = gc_heap();848assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");849850MemRegion mr = heap->reserved_region();851_ref_processor =852new ReferenceProcessor(mr, // span853ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing854(int) ParallelGCThreads, // mt processing degree855true, // mt discovery856(int) ParallelGCThreads, // mt discovery degree857true, // atomic_discovery858&_is_alive_closure); // non-header is alive closure859_counters = new CollectorCounters("PSParallelCompact", 1);860861// Initialize static fields in ParCompactionManager.862ParCompactionManager::initialize(mark_bitmap());863}864865bool PSParallelCompact::initialize() {866ParallelScavengeHeap* heap = gc_heap();867assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");868MemRegion mr = heap->reserved_region();869870// Was the old gen get allocated successfully?871if (!heap->old_gen()->is_allocated()) {872return false;873}874875initialize_space_info();876initialize_dead_wood_limiter();877878if (!_mark_bitmap.initialize(mr)) {879vm_shutdown_during_initialization(880err_msg("Unable to allocate " SIZE_FORMAT "KB bitmaps for parallel "881"garbage collection for the requested " SIZE_FORMAT "KB heap.",882_mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));883return false;884}885886if (!_summary_data.initialize(mr)) {887vm_shutdown_during_initialization(888err_msg("Unable to allocate " SIZE_FORMAT "KB card tables for parallel "889"garbage collection for the requested " SIZE_FORMAT "KB heap.",890_summary_data.reserved_byte_size()/K, mr.byte_size()/K));891return false;892}893894return true;895}896897void PSParallelCompact::initialize_space_info()898{899memset(&_space_info, 0, sizeof(_space_info));900901ParallelScavengeHeap* heap = gc_heap();902PSYoungGen* young_gen = heap->young_gen();903904_space_info[old_space_id].set_space(heap->old_gen()->object_space());905_space_info[eden_space_id].set_space(young_gen->eden_space());906_space_info[from_space_id].set_space(young_gen->from_space());907_space_info[to_space_id].set_space(young_gen->to_space());908909_space_info[old_space_id].set_start_array(heap->old_gen()->start_array());910}911912void PSParallelCompact::initialize_dead_wood_limiter()913{914const size_t max = 100;915_dwl_mean = double(MIN2(ParallelOldDeadWoodLimiterMean, max)) / 100.0;916_dwl_std_dev = double(MIN2(ParallelOldDeadWoodLimiterStdDev, max)) / 100.0;917_dwl_first_term = 1.0 / (sqrt(2.0 * M_PI) * _dwl_std_dev);918DEBUG_ONLY(_dwl_initialized = true;)919_dwl_adjustment = normal_distribution(1.0);920}921922// Simple class for storing info about the heap at the start of GC, to be used923// after GC for comparison/printing.924class PreGCValues {925public:926PreGCValues() { }927PreGCValues(ParallelScavengeHeap* heap) { fill(heap); }928929void fill(ParallelScavengeHeap* heap) {930_heap_used = heap->used();931_young_gen_used = heap->young_gen()->used_in_bytes();932_old_gen_used = heap->old_gen()->used_in_bytes();933_metadata_used = MetaspaceAux::used_bytes();934};935936size_t heap_used() const { return _heap_used; }937size_t young_gen_used() const { return _young_gen_used; }938size_t old_gen_used() const { return _old_gen_used; }939size_t metadata_used() const { return _metadata_used; }940941private:942size_t _heap_used;943size_t _young_gen_used;944size_t _old_gen_used;945size_t _metadata_used;946};947948void949PSParallelCompact::clear_data_covering_space(SpaceId id)950{951// At this point, top is the value before GC, new_top() is the value that will952// be set at the end of GC. The marking bitmap is cleared to top; nothing953// should be marked above top. The summary data is cleared to the larger of954// top & new_top.955MutableSpace* const space = _space_info[id].space();956HeapWord* const bot = space->bottom();957HeapWord* const top = space->top();958HeapWord* const max_top = MAX2(top, _space_info[id].new_top());959960const idx_t beg_bit = _mark_bitmap.addr_to_bit(bot);961const idx_t end_bit = BitMap::word_align_up(_mark_bitmap.addr_to_bit(top));962_mark_bitmap.clear_range(beg_bit, end_bit);963964const size_t beg_region = _summary_data.addr_to_region_idx(bot);965const size_t end_region =966_summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));967_summary_data.clear_range(beg_region, end_region);968969// Clear the data used to 'split' regions.970SplitInfo& split_info = _space_info[id].split_info();971if (split_info.is_valid()) {972split_info.clear();973}974DEBUG_ONLY(split_info.verify_clear();)975}976977void PSParallelCompact::pre_compact(PreGCValues* pre_gc_values)978{979// Update the from & to space pointers in space_info, since they are swapped980// at each young gen gc. Do the update unconditionally (even though a981// promotion failure does not swap spaces) because an unknown number of minor982// collections will have swapped the spaces an unknown number of times.983GCTraceTime tm("pre compact", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());984ParallelScavengeHeap* heap = gc_heap();985_space_info[from_space_id].set_space(heap->young_gen()->from_space());986_space_info[to_space_id].set_space(heap->young_gen()->to_space());987988pre_gc_values->fill(heap);989990DEBUG_ONLY(add_obj_count = add_obj_size = 0;)991DEBUG_ONLY(mark_bitmap_count = mark_bitmap_size = 0;)992993// Increment the invocation count994heap->increment_total_collections(true);995996// We need to track unique mark sweep invocations as well.997_total_invocations++;998999heap->print_heap_before_gc();1000heap->trace_heap_before_gc(&_gc_tracer);10011002// Fill in TLABs1003heap->accumulate_statistics_all_tlabs();1004heap->ensure_parsability(true); // retire TLABs10051006if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {1007HandleMark hm; // Discard invalid handles created during verification1008Universe::verify(" VerifyBeforeGC:");1009}10101011// Verify object start arrays1012if (VerifyObjectStartArray &&1013VerifyBeforeGC) {1014heap->old_gen()->verify_object_start_array();1015}10161017DEBUG_ONLY(mark_bitmap()->verify_clear();)1018DEBUG_ONLY(summary_data().verify_clear();)10191020// Have worker threads release resources the next time they run a task.1021gc_task_manager()->release_all_resources();1022}10231024void PSParallelCompact::post_compact()1025{1026GCTraceTime tm("post compact", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());10271028for (unsigned int id = old_space_id; id < last_space_id; ++id) {1029// Clear the marking bitmap, summary data and split info.1030clear_data_covering_space(SpaceId(id));1031// Update top(). Must be done after clearing the bitmap and summary data.1032_space_info[id].publish_new_top();1033}10341035MutableSpace* const eden_space = _space_info[eden_space_id].space();1036MutableSpace* const from_space = _space_info[from_space_id].space();1037MutableSpace* const to_space = _space_info[to_space_id].space();10381039ParallelScavengeHeap* heap = gc_heap();1040bool eden_empty = eden_space->is_empty();1041if (!eden_empty) {1042eden_empty = absorb_live_data_from_eden(heap->size_policy(),1043heap->young_gen(), heap->old_gen());1044}10451046// Update heap occupancy information which is used as input to the soft ref1047// clearing policy at the next gc.1048Universe::update_heap_info_at_gc();10491050bool young_gen_empty = eden_empty && from_space->is_empty() &&1051to_space->is_empty();10521053BarrierSet* bs = heap->barrier_set();1054if (bs->is_a(BarrierSet::ModRef)) {1055ModRefBarrierSet* modBS = (ModRefBarrierSet*)bs;1056MemRegion old_mr = heap->old_gen()->reserved();10571058if (young_gen_empty) {1059modBS->clear(MemRegion(old_mr.start(), old_mr.end()));1060} else {1061modBS->invalidate(MemRegion(old_mr.start(), old_mr.end()));1062}1063}10641065// Delete metaspaces for unloaded class loaders and clean up loader_data graph1066ClassLoaderDataGraph::purge();1067MetaspaceAux::verify_metrics();10681069Threads::gc_epilogue();1070CodeCache::gc_epilogue();1071JvmtiExport::gc_epilogue();10721073COMPILER2_PRESENT(DerivedPointerTable::update_pointers());10741075ref_processor()->enqueue_discovered_references(NULL);10761077if (ZapUnusedHeapArea) {1078heap->gen_mangle_unused_area();1079}10801081// Update time of last GC1082reset_millis_since_last_gc();1083}10841085HeapWord*1086PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id,1087bool maximum_compaction)1088{1089const size_t region_size = ParallelCompactData::RegionSize;1090const ParallelCompactData& sd = summary_data();10911092const MutableSpace* const space = _space_info[id].space();1093HeapWord* const top_aligned_up = sd.region_align_up(space->top());1094const RegionData* const beg_cp = sd.addr_to_region_ptr(space->bottom());1095const RegionData* const end_cp = sd.addr_to_region_ptr(top_aligned_up);10961097// Skip full regions at the beginning of the space--they are necessarily part1098// of the dense prefix.1099size_t full_count = 0;1100const RegionData* cp;1101for (cp = beg_cp; cp < end_cp && cp->data_size() == region_size; ++cp) {1102++full_count;1103}11041105assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");1106const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;1107const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval;1108if (maximum_compaction || cp == end_cp || interval_ended) {1109_maximum_compaction_gc_num = total_invocations();1110return sd.region_to_addr(cp);1111}11121113HeapWord* const new_top = _space_info[id].new_top();1114const size_t space_live = pointer_delta(new_top, space->bottom());1115const size_t space_used = space->used_in_words();1116const size_t space_capacity = space->capacity_in_words();11171118const double cur_density = double(space_live) / space_capacity;1119const double deadwood_density =1120(1.0 - cur_density) * (1.0 - cur_density) * cur_density * cur_density;1121const size_t deadwood_goal = size_t(space_capacity * deadwood_density);11221123if (TraceParallelOldGCDensePrefix) {1124tty->print_cr("cur_dens=%5.3f dw_dens=%5.3f dw_goal=" SIZE_FORMAT,1125cur_density, deadwood_density, deadwood_goal);1126tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "1127"space_cap=" SIZE_FORMAT,1128space_live, space_used,1129space_capacity);1130}11311132// XXX - Use binary search?1133HeapWord* dense_prefix = sd.region_to_addr(cp);1134const RegionData* full_cp = cp;1135const RegionData* const top_cp = sd.addr_to_region_ptr(space->top() - 1);1136while (cp < end_cp) {1137HeapWord* region_destination = cp->destination();1138const size_t cur_deadwood = pointer_delta(dense_prefix, region_destination);1139if (TraceParallelOldGCDensePrefix && Verbose) {1140tty->print_cr("c#=" SIZE_FORMAT_W(4) " dst=" PTR_FORMAT " "1141"dp=" SIZE_FORMAT_W(8) " " "cdw=" SIZE_FORMAT_W(8),1142sd.region(cp), region_destination,1143dense_prefix, cur_deadwood);1144}11451146if (cur_deadwood >= deadwood_goal) {1147// Found the region that has the correct amount of deadwood to the left.1148// This typically occurs after crossing a fairly sparse set of regions, so1149// iterate backwards over those sparse regions, looking for the region1150// that has the lowest density of live objects 'to the right.'1151size_t space_to_left = sd.region(cp) * region_size;1152size_t live_to_left = space_to_left - cur_deadwood;1153size_t space_to_right = space_capacity - space_to_left;1154size_t live_to_right = space_live - live_to_left;1155double density_to_right = double(live_to_right) / space_to_right;1156while (cp > full_cp) {1157--cp;1158const size_t prev_region_live_to_right = live_to_right -1159cp->data_size();1160const size_t prev_region_space_to_right = space_to_right + region_size;1161double prev_region_density_to_right =1162double(prev_region_live_to_right) / prev_region_space_to_right;1163if (density_to_right <= prev_region_density_to_right) {1164return dense_prefix;1165}1166if (TraceParallelOldGCDensePrefix && Verbose) {1167tty->print_cr("backing up from c=" SIZE_FORMAT_W(4) " d2r=%10.8f "1168"pc_d2r=%10.8f", sd.region(cp), density_to_right,1169prev_region_density_to_right);1170}1171dense_prefix -= region_size;1172live_to_right = prev_region_live_to_right;1173space_to_right = prev_region_space_to_right;1174density_to_right = prev_region_density_to_right;1175}1176return dense_prefix;1177}11781179dense_prefix += region_size;1180++cp;1181}11821183return dense_prefix;1184}11851186#ifndef PRODUCT1187void PSParallelCompact::print_dense_prefix_stats(const char* const algorithm,1188const SpaceId id,1189const bool maximum_compaction,1190HeapWord* const addr)1191{1192const size_t region_idx = summary_data().addr_to_region_idx(addr);1193RegionData* const cp = summary_data().region(region_idx);1194const MutableSpace* const space = _space_info[id].space();1195HeapWord* const new_top = _space_info[id].new_top();11961197const size_t space_live = pointer_delta(new_top, space->bottom());1198const size_t dead_to_left = pointer_delta(addr, cp->destination());1199const size_t space_cap = space->capacity_in_words();1200const double dead_to_left_pct = double(dead_to_left) / space_cap;1201const size_t live_to_right = new_top - cp->destination();1202const size_t dead_to_right = space->top() - addr - live_to_right;12031204tty->print_cr("%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W(5) " "1205"spl=" SIZE_FORMAT " "1206"d2l=" SIZE_FORMAT " d2l%%=%6.4f "1207"d2r=" SIZE_FORMAT " l2r=" SIZE_FORMAT1208" ratio=%10.8f",1209algorithm, addr, region_idx,1210space_live,1211dead_to_left, dead_to_left_pct,1212dead_to_right, live_to_right,1213double(dead_to_right) / live_to_right);1214}1215#endif // #ifndef PRODUCT12161217// Return a fraction indicating how much of the generation can be treated as1218// "dead wood" (i.e., not reclaimed). The function uses a normal distribution1219// based on the density of live objects in the generation to determine a limit,1220// which is then adjusted so the return value is min_percent when the density is1221// 1.1222//1223// The following table shows some return values for a different values of the1224// standard deviation (ParallelOldDeadWoodLimiterStdDev); the mean is 0.5 and1225// min_percent is 1.1226//1227// fraction allowed as dead wood1228// -----------------------------------------------------------------1229// density std_dev=70 std_dev=75 std_dev=80 std_dev=85 std_dev=90 std_dev=951230// ------- ---------- ---------- ---------- ---------- ---------- ----------1231// 0.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.010000001232// 0.05000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.019749411233// 0.10000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.028692721234// 0.15000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.036760661235// 0.20000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.043889751236// 0.25000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.050023131237// 0.30000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.055111321238// 0.35000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.059112891239// 0.40000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.061995001240// 0.45000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.063733861241// 0.50000 0.13832410 0.11599237 0.09847664 0.08456518 0.07338887 0.064315101242// 0.55000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.063733861243// 0.60000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.061995001244// 0.65000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.059112891245// 0.70000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.055111321246// 0.75000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.050023131247// 0.80000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.043889751248// 0.85000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.036760661249// 0.90000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.028692721250// 0.95000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.019749411251// 1.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.0100000012521253double PSParallelCompact::dead_wood_limiter(double density, size_t min_percent)1254{1255assert(_dwl_initialized, "uninitialized");12561257// The raw limit is the value of the normal distribution at x = density.1258const double raw_limit = normal_distribution(density);12591260// Adjust the raw limit so it becomes the minimum when the density is 1.1261//1262// First subtract the adjustment value (which is simply the precomputed value1263// normal_distribution(1.0)); this yields a value of 0 when the density is 1.1264// Then add the minimum value, so the minimum is returned when the density is1265// 1. Finally, prevent negative values, which occur when the mean is not 0.5.1266const double min = double(min_percent) / 100.0;1267const double limit = raw_limit - _dwl_adjustment + min;1268return MAX2(limit, 0.0);1269}12701271ParallelCompactData::RegionData*1272PSParallelCompact::first_dead_space_region(const RegionData* beg,1273const RegionData* end)1274{1275const size_t region_size = ParallelCompactData::RegionSize;1276ParallelCompactData& sd = summary_data();1277size_t left = sd.region(beg);1278size_t right = end > beg ? sd.region(end) - 1 : left;12791280// Binary search.1281while (left < right) {1282// Equivalent to (left + right) / 2, but does not overflow.1283const size_t middle = left + (right - left) / 2;1284RegionData* const middle_ptr = sd.region(middle);1285HeapWord* const dest = middle_ptr->destination();1286HeapWord* const addr = sd.region_to_addr(middle);1287assert(dest != NULL, "sanity");1288assert(dest <= addr, "must move left");12891290if (middle > left && dest < addr) {1291right = middle - 1;1292} else if (middle < right && middle_ptr->data_size() == region_size) {1293left = middle + 1;1294} else {1295return middle_ptr;1296}1297}1298return sd.region(left);1299}13001301ParallelCompactData::RegionData*1302PSParallelCompact::dead_wood_limit_region(const RegionData* beg,1303const RegionData* end,1304size_t dead_words)1305{1306ParallelCompactData& sd = summary_data();1307size_t left = sd.region(beg);1308size_t right = end > beg ? sd.region(end) - 1 : left;13091310// Binary search.1311while (left < right) {1312// Equivalent to (left + right) / 2, but does not overflow.1313const size_t middle = left + (right - left) / 2;1314RegionData* const middle_ptr = sd.region(middle);1315HeapWord* const dest = middle_ptr->destination();1316HeapWord* const addr = sd.region_to_addr(middle);1317assert(dest != NULL, "sanity");1318assert(dest <= addr, "must move left");13191320const size_t dead_to_left = pointer_delta(addr, dest);1321if (middle > left && dead_to_left > dead_words) {1322right = middle - 1;1323} else if (middle < right && dead_to_left < dead_words) {1324left = middle + 1;1325} else {1326return middle_ptr;1327}1328}1329return sd.region(left);1330}13311332// The result is valid during the summary phase, after the initial summarization1333// of each space into itself, and before final summarization.1334inline double1335PSParallelCompact::reclaimed_ratio(const RegionData* const cp,1336HeapWord* const bottom,1337HeapWord* const top,1338HeapWord* const new_top)1339{1340ParallelCompactData& sd = summary_data();13411342assert(cp != NULL, "sanity");1343assert(bottom != NULL, "sanity");1344assert(top != NULL, "sanity");1345assert(new_top != NULL, "sanity");1346assert(top >= new_top, "summary data problem?");1347assert(new_top > bottom, "space is empty; should not be here");1348assert(new_top >= cp->destination(), "sanity");1349assert(top >= sd.region_to_addr(cp), "sanity");13501351HeapWord* const destination = cp->destination();1352const size_t dense_prefix_live = pointer_delta(destination, bottom);1353const size_t compacted_region_live = pointer_delta(new_top, destination);1354const size_t compacted_region_used = pointer_delta(top,1355sd.region_to_addr(cp));1356const size_t reclaimable = compacted_region_used - compacted_region_live;13571358const double divisor = dense_prefix_live + 1.25 * compacted_region_live;1359return double(reclaimable) / divisor;1360}13611362// Return the address of the end of the dense prefix, a.k.a. the start of the1363// compacted region. The address is always on a region boundary.1364//1365// Completely full regions at the left are skipped, since no compaction can1366// occur in those regions. Then the maximum amount of dead wood to allow is1367// computed, based on the density (amount live / capacity) of the generation;1368// the region with approximately that amount of dead space to the left is1369// identified as the limit region. Regions between the last completely full1370// region and the limit region are scanned and the one that has the best1371// (maximum) reclaimed_ratio() is selected.1372HeapWord*1373PSParallelCompact::compute_dense_prefix(const SpaceId id,1374bool maximum_compaction)1375{1376if (ParallelOldGCSplitALot) {1377if (_space_info[id].dense_prefix() != _space_info[id].space()->bottom()) {1378// The value was chosen to provoke splitting a young gen space; use it.1379return _space_info[id].dense_prefix();1380}1381}13821383const size_t region_size = ParallelCompactData::RegionSize;1384const ParallelCompactData& sd = summary_data();13851386const MutableSpace* const space = _space_info[id].space();1387HeapWord* const top = space->top();1388HeapWord* const top_aligned_up = sd.region_align_up(top);1389HeapWord* const new_top = _space_info[id].new_top();1390HeapWord* const new_top_aligned_up = sd.region_align_up(new_top);1391HeapWord* const bottom = space->bottom();1392const RegionData* const beg_cp = sd.addr_to_region_ptr(bottom);1393const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);1394const RegionData* const new_top_cp =1395sd.addr_to_region_ptr(new_top_aligned_up);13961397// Skip full regions at the beginning of the space--they are necessarily part1398// of the dense prefix.1399const RegionData* const full_cp = first_dead_space_region(beg_cp, new_top_cp);1400assert(full_cp->destination() == sd.region_to_addr(full_cp) ||1401space->is_empty(), "no dead space allowed to the left");1402assert(full_cp->data_size() < region_size || full_cp == new_top_cp - 1,1403"region must have dead space");14041405// The gc number is saved whenever a maximum compaction is done, and used to1406// determine when the maximum compaction interval has expired. This avoids1407// successive max compactions for different reasons.1408assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");1409const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;1410const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval ||1411total_invocations() == HeapFirstMaximumCompactionCount;1412if (maximum_compaction || full_cp == top_cp || interval_ended) {1413_maximum_compaction_gc_num = total_invocations();1414return sd.region_to_addr(full_cp);1415}14161417const size_t space_live = pointer_delta(new_top, bottom);1418const size_t space_used = space->used_in_words();1419const size_t space_capacity = space->capacity_in_words();14201421const double density = double(space_live) / double(space_capacity);1422const size_t min_percent_free = MarkSweepDeadRatio;1423const double limiter = dead_wood_limiter(density, min_percent_free);1424const size_t dead_wood_max = space_used - space_live;1425const size_t dead_wood_limit = MIN2(size_t(space_capacity * limiter),1426dead_wood_max);14271428if (TraceParallelOldGCDensePrefix) {1429tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "1430"space_cap=" SIZE_FORMAT,1431space_live, space_used,1432space_capacity);1433tty->print_cr("dead_wood_limiter(%6.4f, %d)=%6.4f "1434"dead_wood_max=" SIZE_FORMAT " dead_wood_limit=" SIZE_FORMAT,1435density, min_percent_free, limiter,1436dead_wood_max, dead_wood_limit);1437}14381439// Locate the region with the desired amount of dead space to the left.1440const RegionData* const limit_cp =1441dead_wood_limit_region(full_cp, top_cp, dead_wood_limit);14421443// Scan from the first region with dead space to the limit region and find the1444// one with the best (largest) reclaimed ratio.1445double best_ratio = 0.0;1446const RegionData* best_cp = full_cp;1447for (const RegionData* cp = full_cp; cp < limit_cp; ++cp) {1448double tmp_ratio = reclaimed_ratio(cp, bottom, top, new_top);1449if (tmp_ratio > best_ratio) {1450best_cp = cp;1451best_ratio = tmp_ratio;1452}1453}14541455#if 01456// Something to consider: if the region with the best ratio is 'close to' the1457// first region w/free space, choose the first region with free space1458// ("first-free"). The first-free region is usually near the start of the1459// heap, which means we are copying most of the heap already, so copy a bit1460// more to get complete compaction.1461if (pointer_delta(best_cp, full_cp, sizeof(RegionData)) < 4) {1462_maximum_compaction_gc_num = total_invocations();1463best_cp = full_cp;1464}1465#endif // #if 014661467return sd.region_to_addr(best_cp);1468}14691470#ifndef PRODUCT1471void1472PSParallelCompact::fill_with_live_objects(SpaceId id, HeapWord* const start,1473size_t words)1474{1475if (TraceParallelOldGCSummaryPhase) {1476tty->print_cr("fill_with_live_objects [" PTR_FORMAT " " PTR_FORMAT ") "1477SIZE_FORMAT, start, start + words, words);1478}14791480ObjectStartArray* const start_array = _space_info[id].start_array();1481CollectedHeap::fill_with_objects(start, words);1482for (HeapWord* p = start; p < start + words; p += oop(p)->size()) {1483_mark_bitmap.mark_obj(p, words);1484_summary_data.add_obj(p, words);1485start_array->allocate_block(p);1486}1487}14881489void1490PSParallelCompact::summarize_new_objects(SpaceId id, HeapWord* start)1491{1492ParallelCompactData& sd = summary_data();1493MutableSpace* space = _space_info[id].space();14941495// Find the source and destination start addresses.1496HeapWord* const src_addr = sd.region_align_down(start);1497HeapWord* dst_addr;1498if (src_addr < start) {1499dst_addr = sd.addr_to_region_ptr(src_addr)->destination();1500} else if (src_addr > space->bottom()) {1501// The start (the original top() value) is aligned to a region boundary so1502// the associated region does not have a destination. Compute the1503// destination from the previous region.1504RegionData* const cp = sd.addr_to_region_ptr(src_addr) - 1;1505dst_addr = cp->destination() + cp->data_size();1506} else {1507// Filling the entire space.1508dst_addr = space->bottom();1509}1510assert(dst_addr != NULL, "sanity");15111512// Update the summary data.1513bool result = _summary_data.summarize(_space_info[id].split_info(),1514src_addr, space->top(), NULL,1515dst_addr, space->end(),1516_space_info[id].new_top_addr());1517assert(result, "should not fail: bad filler object size");1518}15191520void1521PSParallelCompact::provoke_split_fill_survivor(SpaceId id)1522{1523if (total_invocations() % (ParallelOldGCSplitInterval * 3) != 0) {1524return;1525}15261527MutableSpace* const space = _space_info[id].space();1528if (space->is_empty()) {1529HeapWord* b = space->bottom();1530HeapWord* t = b + space->capacity_in_words() / 2;1531space->set_top(t);1532if (ZapUnusedHeapArea) {1533space->set_top_for_allocations();1534}15351536size_t min_size = CollectedHeap::min_fill_size();1537size_t obj_len = min_size;1538while (b + obj_len <= t) {1539CollectedHeap::fill_with_object(b, obj_len);1540mark_bitmap()->mark_obj(b, obj_len);1541summary_data().add_obj(b, obj_len);1542b += obj_len;1543obj_len = (obj_len & (min_size*3)) + min_size; // 8 16 24 32 8 16 24 32 ...1544}1545if (b < t) {1546// The loop didn't completely fill to t (top); adjust top downward.1547space->set_top(b);1548if (ZapUnusedHeapArea) {1549space->set_top_for_allocations();1550}1551}15521553HeapWord** nta = _space_info[id].new_top_addr();1554bool result = summary_data().summarize(_space_info[id].split_info(),1555space->bottom(), space->top(), NULL,1556space->bottom(), space->end(), nta);1557assert(result, "space must fit into itself");1558}1559}15601561void1562PSParallelCompact::provoke_split(bool & max_compaction)1563{1564if (total_invocations() % ParallelOldGCSplitInterval != 0) {1565return;1566}15671568const size_t region_size = ParallelCompactData::RegionSize;1569ParallelCompactData& sd = summary_data();15701571MutableSpace* const eden_space = _space_info[eden_space_id].space();1572MutableSpace* const from_space = _space_info[from_space_id].space();1573const size_t eden_live = pointer_delta(eden_space->top(),1574_space_info[eden_space_id].new_top());1575const size_t from_live = pointer_delta(from_space->top(),1576_space_info[from_space_id].new_top());15771578const size_t min_fill_size = CollectedHeap::min_fill_size();1579const size_t eden_free = pointer_delta(eden_space->end(), eden_space->top());1580const size_t eden_fillable = eden_free >= min_fill_size ? eden_free : 0;1581const size_t from_free = pointer_delta(from_space->end(), from_space->top());1582const size_t from_fillable = from_free >= min_fill_size ? from_free : 0;15831584// Choose the space to split; need at least 2 regions live (or fillable).1585SpaceId id;1586MutableSpace* space;1587size_t live_words;1588size_t fill_words;1589if (eden_live + eden_fillable >= region_size * 2) {1590id = eden_space_id;1591space = eden_space;1592live_words = eden_live;1593fill_words = eden_fillable;1594} else if (from_live + from_fillable >= region_size * 2) {1595id = from_space_id;1596space = from_space;1597live_words = from_live;1598fill_words = from_fillable;1599} else {1600return; // Give up.1601}1602assert(fill_words == 0 || fill_words >= min_fill_size, "sanity");16031604if (live_words < region_size * 2) {1605// Fill from top() to end() w/live objects of mixed sizes.1606HeapWord* const fill_start = space->top();1607live_words += fill_words;16081609space->set_top(fill_start + fill_words);1610if (ZapUnusedHeapArea) {1611space->set_top_for_allocations();1612}16131614HeapWord* cur_addr = fill_start;1615while (fill_words > 0) {1616const size_t r = (size_t)os::random() % (region_size / 2) + min_fill_size;1617size_t cur_size = MIN2(align_object_size_(r), fill_words);1618if (fill_words - cur_size < min_fill_size) {1619cur_size = fill_words; // Avoid leaving a fragment too small to fill.1620}16211622CollectedHeap::fill_with_object(cur_addr, cur_size);1623mark_bitmap()->mark_obj(cur_addr, cur_size);1624sd.add_obj(cur_addr, cur_size);16251626cur_addr += cur_size;1627fill_words -= cur_size;1628}16291630summarize_new_objects(id, fill_start);1631}16321633max_compaction = false;16341635// Manipulate the old gen so that it has room for about half of the live data1636// in the target young gen space (live_words / 2).1637id = old_space_id;1638space = _space_info[id].space();1639const size_t free_at_end = space->free_in_words();1640const size_t free_target = align_object_size(live_words / 2);1641const size_t dead = pointer_delta(space->top(), _space_info[id].new_top());16421643if (free_at_end >= free_target + min_fill_size) {1644// Fill space above top() and set the dense prefix so everything survives.1645HeapWord* const fill_start = space->top();1646const size_t fill_size = free_at_end - free_target;1647space->set_top(space->top() + fill_size);1648if (ZapUnusedHeapArea) {1649space->set_top_for_allocations();1650}1651fill_with_live_objects(id, fill_start, fill_size);1652summarize_new_objects(id, fill_start);1653_space_info[id].set_dense_prefix(sd.region_align_down(space->top()));1654} else if (dead + free_at_end > free_target) {1655// Find a dense prefix that makes the right amount of space available.1656HeapWord* cur = sd.region_align_down(space->top());1657HeapWord* cur_destination = sd.addr_to_region_ptr(cur)->destination();1658size_t dead_to_right = pointer_delta(space->end(), cur_destination);1659while (dead_to_right < free_target) {1660cur -= region_size;1661cur_destination = sd.addr_to_region_ptr(cur)->destination();1662dead_to_right = pointer_delta(space->end(), cur_destination);1663}1664_space_info[id].set_dense_prefix(cur);1665}1666}1667#endif // #ifndef PRODUCT16681669void PSParallelCompact::summarize_spaces_quick()1670{1671for (unsigned int i = 0; i < last_space_id; ++i) {1672const MutableSpace* space = _space_info[i].space();1673HeapWord** nta = _space_info[i].new_top_addr();1674bool result = _summary_data.summarize(_space_info[i].split_info(),1675space->bottom(), space->top(), NULL,1676space->bottom(), space->end(), nta);1677assert(result, "space must fit into itself");1678_space_info[i].set_dense_prefix(space->bottom());1679}16801681#ifndef PRODUCT1682if (ParallelOldGCSplitALot) {1683provoke_split_fill_survivor(to_space_id);1684}1685#endif // #ifndef PRODUCT1686}16871688void PSParallelCompact::fill_dense_prefix_end(SpaceId id)1689{1690HeapWord* const dense_prefix_end = dense_prefix(id);1691const RegionData* region = _summary_data.addr_to_region_ptr(dense_prefix_end);1692const idx_t dense_prefix_bit = _mark_bitmap.addr_to_bit(dense_prefix_end);1693if (dead_space_crosses_boundary(region, dense_prefix_bit)) {1694// Only enough dead space is filled so that any remaining dead space to the1695// left is larger than the minimum filler object. (The remainder is filled1696// during the copy/update phase.)1697//1698// The size of the dead space to the right of the boundary is not a1699// concern, since compaction will be able to use whatever space is1700// available.1701//1702// Here '||' is the boundary, 'x' represents a don't care bit and a box1703// surrounds the space to be filled with an object.1704//1705// In the 32-bit VM, each bit represents two 32-bit words:1706// +---+1707// a) beg_bits: ... x x x | 0 | || 0 x x ...1708// end_bits: ... x x x | 0 | || 0 x x ...1709// +---+1710//1711// In the 64-bit VM, each bit represents one 64-bit word:1712// +------------+1713// b) beg_bits: ... x x x | 0 || 0 | x x ...1714// end_bits: ... x x 1 | 0 || 0 | x x ...1715// +------------+1716// +-------+1717// c) beg_bits: ... x x | 0 0 | || 0 x x ...1718// end_bits: ... x 1 | 0 0 | || 0 x x ...1719// +-------+1720// +-----------+1721// d) beg_bits: ... x | 0 0 0 | || 0 x x ...1722// end_bits: ... 1 | 0 0 0 | || 0 x x ...1723// +-----------+1724// +-------+1725// e) beg_bits: ... 0 0 | 0 0 | || 0 x x ...1726// end_bits: ... 0 0 | 0 0 | || 0 x x ...1727// +-------+17281729// Initially assume case a, c or e will apply.1730size_t obj_len = CollectedHeap::min_fill_size();1731HeapWord* obj_beg = dense_prefix_end - obj_len;17321733#ifdef _LP641734if (MinObjAlignment > 1) { // object alignment > heap word size1735// Cases a, c or e.1736} else if (_mark_bitmap.is_obj_end(dense_prefix_bit - 2)) {1737// Case b above.1738obj_beg = dense_prefix_end - 1;1739} else if (!_mark_bitmap.is_obj_end(dense_prefix_bit - 3) &&1740_mark_bitmap.is_obj_end(dense_prefix_bit - 4)) {1741// Case d above.1742obj_beg = dense_prefix_end - 3;1743obj_len = 3;1744}1745#endif // #ifdef _LP6417461747CollectedHeap::fill_with_object(obj_beg, obj_len);1748_mark_bitmap.mark_obj(obj_beg, obj_len);1749_summary_data.add_obj(obj_beg, obj_len);1750assert(start_array(id) != NULL, "sanity");1751start_array(id)->allocate_block(obj_beg);1752}1753}17541755void1756PSParallelCompact::clear_source_region(HeapWord* beg_addr, HeapWord* end_addr)1757{1758RegionData* const beg_ptr = _summary_data.addr_to_region_ptr(beg_addr);1759HeapWord* const end_aligned_up = _summary_data.region_align_up(end_addr);1760RegionData* const end_ptr = _summary_data.addr_to_region_ptr(end_aligned_up);1761for (RegionData* cur = beg_ptr; cur < end_ptr; ++cur) {1762cur->set_source_region(0);1763}1764}17651766void1767PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction)1768{1769assert(id < last_space_id, "id out of range");1770assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom() ||1771ParallelOldGCSplitALot && id == old_space_id,1772"should have been reset in summarize_spaces_quick()");17731774const MutableSpace* space = _space_info[id].space();1775if (_space_info[id].new_top() != space->bottom()) {1776HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction);1777_space_info[id].set_dense_prefix(dense_prefix_end);17781779#ifndef PRODUCT1780if (TraceParallelOldGCDensePrefix) {1781print_dense_prefix_stats("ratio", id, maximum_compaction,1782dense_prefix_end);1783HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction);1784print_dense_prefix_stats("density", id, maximum_compaction, addr);1785}1786#endif // #ifndef PRODUCT17871788// Recompute the summary data, taking into account the dense prefix. If1789// every last byte will be reclaimed, then the existing summary data which1790// compacts everything can be left in place.1791if (!maximum_compaction && dense_prefix_end != space->bottom()) {1792// If dead space crosses the dense prefix boundary, it is (at least1793// partially) filled with a dummy object, marked live and added to the1794// summary data. This simplifies the copy/update phase and must be done1795// before the final locations of objects are determined, to prevent1796// leaving a fragment of dead space that is too small to fill.1797fill_dense_prefix_end(id);17981799// Compute the destination of each Region, and thus each object.1800_summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end);1801_summary_data.summarize(_space_info[id].split_info(),1802dense_prefix_end, space->top(), NULL,1803dense_prefix_end, space->end(),1804_space_info[id].new_top_addr());1805}1806}18071808if (TraceParallelOldGCSummaryPhase) {1809const size_t region_size = ParallelCompactData::RegionSize;1810HeapWord* const dense_prefix_end = _space_info[id].dense_prefix();1811const size_t dp_region = _summary_data.addr_to_region_idx(dense_prefix_end);1812const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom());1813HeapWord* const new_top = _space_info[id].new_top();1814const HeapWord* nt_aligned_up = _summary_data.region_align_up(new_top);1815const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end);1816tty->print_cr("id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " "1817"dp_region=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " "1818"cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT,1819id, space->capacity_in_words(), dense_prefix_end,1820dp_region, dp_words / region_size,1821cr_words / region_size, new_top);1822}1823}18241825#ifndef PRODUCT1826void PSParallelCompact::summary_phase_msg(SpaceId dst_space_id,1827HeapWord* dst_beg, HeapWord* dst_end,1828SpaceId src_space_id,1829HeapWord* src_beg, HeapWord* src_end)1830{1831if (TraceParallelOldGCSummaryPhase) {1832tty->print_cr("summarizing %d [%s] into %d [%s]: "1833"src=" PTR_FORMAT "-" PTR_FORMAT " "1834SIZE_FORMAT "-" SIZE_FORMAT " "1835"dst=" PTR_FORMAT "-" PTR_FORMAT " "1836SIZE_FORMAT "-" SIZE_FORMAT,1837src_space_id, space_names[src_space_id],1838dst_space_id, space_names[dst_space_id],1839src_beg, src_end,1840_summary_data.addr_to_region_idx(src_beg),1841_summary_data.addr_to_region_idx(src_end),1842dst_beg, dst_end,1843_summary_data.addr_to_region_idx(dst_beg),1844_summary_data.addr_to_region_idx(dst_end));1845}1846}1847#endif // #ifndef PRODUCT18481849void PSParallelCompact::summary_phase(ParCompactionManager* cm,1850bool maximum_compaction)1851{1852GCTraceTime tm("summary phase", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());1853// trace("2");18541855#ifdef ASSERT1856if (TraceParallelOldGCMarkingPhase) {1857tty->print_cr("add_obj_count=" SIZE_FORMAT " "1858"add_obj_bytes=" SIZE_FORMAT,1859add_obj_count, add_obj_size * HeapWordSize);1860tty->print_cr("mark_bitmap_count=" SIZE_FORMAT " "1861"mark_bitmap_bytes=" SIZE_FORMAT,1862mark_bitmap_count, mark_bitmap_size * HeapWordSize);1863}1864#endif // #ifdef ASSERT18651866// Quick summarization of each space into itself, to see how much is live.1867summarize_spaces_quick();18681869if (TraceParallelOldGCSummaryPhase) {1870tty->print_cr("summary_phase: after summarizing each space to self");1871Universe::print();1872NOT_PRODUCT(print_region_ranges());1873if (Verbose) {1874NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));1875}1876}18771878// The amount of live data that will end up in old space (assuming it fits).1879size_t old_space_total_live = 0;1880for (unsigned int id = old_space_id; id < last_space_id; ++id) {1881old_space_total_live += pointer_delta(_space_info[id].new_top(),1882_space_info[id].space()->bottom());1883}18841885MutableSpace* const old_space = _space_info[old_space_id].space();1886const size_t old_capacity = old_space->capacity_in_words();1887if (old_space_total_live > old_capacity) {1888// XXX - should also try to expand1889maximum_compaction = true;1890}1891#ifndef PRODUCT1892if (ParallelOldGCSplitALot && old_space_total_live < old_capacity) {1893provoke_split(maximum_compaction);1894}1895#endif // #ifndef PRODUCT18961897// Old generations.1898summarize_space(old_space_id, maximum_compaction);18991900// Summarize the remaining spaces in the young gen. The initial target space1901// is the old gen. If a space does not fit entirely into the target, then the1902// remainder is compacted into the space itself and that space becomes the new1903// target.1904SpaceId dst_space_id = old_space_id;1905HeapWord* dst_space_end = old_space->end();1906HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();1907for (unsigned int id = eden_space_id; id < last_space_id; ++id) {1908const MutableSpace* space = _space_info[id].space();1909const size_t live = pointer_delta(_space_info[id].new_top(),1910space->bottom());1911const size_t available = pointer_delta(dst_space_end, *new_top_addr);19121913NOT_PRODUCT(summary_phase_msg(dst_space_id, *new_top_addr, dst_space_end,1914SpaceId(id), space->bottom(), space->top());)1915if (live > 0 && live <= available) {1916// All the live data will fit.1917bool done = _summary_data.summarize(_space_info[id].split_info(),1918space->bottom(), space->top(),1919NULL,1920*new_top_addr, dst_space_end,1921new_top_addr);1922assert(done, "space must fit into old gen");19231924// Reset the new_top value for the space.1925_space_info[id].set_new_top(space->bottom());1926} else if (live > 0) {1927// Attempt to fit part of the source space into the target space.1928HeapWord* next_src_addr = NULL;1929bool done = _summary_data.summarize(_space_info[id].split_info(),1930space->bottom(), space->top(),1931&next_src_addr,1932*new_top_addr, dst_space_end,1933new_top_addr);1934assert(!done, "space should not fit into old gen");1935assert(next_src_addr != NULL, "sanity");19361937// The source space becomes the new target, so the remainder is compacted1938// within the space itself.1939dst_space_id = SpaceId(id);1940dst_space_end = space->end();1941new_top_addr = _space_info[id].new_top_addr();1942NOT_PRODUCT(summary_phase_msg(dst_space_id,1943space->bottom(), dst_space_end,1944SpaceId(id), next_src_addr, space->top());)1945done = _summary_data.summarize(_space_info[id].split_info(),1946next_src_addr, space->top(),1947NULL,1948space->bottom(), dst_space_end,1949new_top_addr);1950assert(done, "space must fit when compacted into itself");1951assert(*new_top_addr <= space->top(), "usage should not grow");1952}1953}19541955if (TraceParallelOldGCSummaryPhase) {1956tty->print_cr("summary_phase: after final summarization");1957Universe::print();1958NOT_PRODUCT(print_region_ranges());1959if (Verbose) {1960NOT_PRODUCT(print_generic_summary_data(_summary_data, _space_info));1961}1962}1963}19641965// This method should contain all heap-specific policy for invoking a full1966// collection. invoke_no_policy() will only attempt to compact the heap; it1967// will do nothing further. If we need to bail out for policy reasons, scavenge1968// before full gc, or any other specialized behavior, it needs to be added here.1969//1970// Note that this method should only be called from the vm_thread while at a1971// safepoint.1972//1973// Note that the all_soft_refs_clear flag in the collector policy1974// may be true because this method can be called without intervening1975// activity. For example when the heap space is tight and full measure1976// are being taken to free space.1977void PSParallelCompact::invoke(bool maximum_heap_compaction) {1978assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");1979assert(Thread::current() == (Thread*)VMThread::vm_thread(),1980"should be in vm thread");19811982ParallelScavengeHeap* heap = gc_heap();1983GCCause::Cause gc_cause = heap->gc_cause();1984assert(!heap->is_gc_active(), "not reentrant");19851986PSAdaptiveSizePolicy* policy = heap->size_policy();1987IsGCActiveMark mark;19881989if (ScavengeBeforeFullGC) {1990PSScavenge::invoke_no_policy();1991}19921993const bool clear_all_soft_refs =1994heap->collector_policy()->should_clear_all_soft_refs();19951996PSParallelCompact::invoke_no_policy(clear_all_soft_refs ||1997maximum_heap_compaction);1998}19992000// This method contains no policy. You should probably2001// be calling invoke() instead.2002bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {2003assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");2004assert(ref_processor() != NULL, "Sanity");20052006if (GC_locker::check_active_before_gc()) {2007return false;2008}20092010ParallelScavengeHeap* heap = gc_heap();20112012_gc_timer.register_gc_start();2013_gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());20142015TimeStamp marking_start;2016TimeStamp compaction_start;2017TimeStamp collection_exit;20182019GCCause::Cause gc_cause = heap->gc_cause();2020PSYoungGen* young_gen = heap->young_gen();2021PSOldGen* old_gen = heap->old_gen();2022PSAdaptiveSizePolicy* size_policy = heap->size_policy();20232024// The scope of casr should end after code that can change2025// CollectorPolicy::_should_clear_all_soft_refs.2026ClearedAllSoftRefs casr(maximum_heap_compaction,2027heap->collector_policy());20282029if (ZapUnusedHeapArea) {2030// Save information needed to minimize mangling2031heap->record_gen_tops_before_GC();2032}20332034heap->pre_full_gc_dump(&_gc_timer);20352036_print_phases = PrintGCDetails && PrintParallelOldGCPhaseTimes;20372038// Make sure data structures are sane, make the heap parsable, and do other2039// miscellaneous bookkeeping.2040PreGCValues pre_gc_values;2041pre_compact(&pre_gc_values);20422043// Get the compaction manager reserved for the VM thread.2044ParCompactionManager* const vmthread_cm =2045ParCompactionManager::manager_array(gc_task_manager()->workers());20462047// Place after pre_compact() where the number of invocations is incremented.2048AdaptiveSizePolicyOutput(size_policy, heap->total_collections());20492050{2051ResourceMark rm;2052HandleMark hm;20532054// Set the number of GC threads to be used in this collection2055gc_task_manager()->set_active_gang();2056gc_task_manager()->task_idle_workers();2057heap->set_par_threads(gc_task_manager()->active_workers());20582059TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);2060GCTraceTime t1(GCCauseString("Full GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer.gc_id());2061TraceCollectorStats tcs(counters());2062TraceMemoryManagerStats tms(true /* Full GC */,gc_cause);20632064if (TraceGen1Time) accumulated_time()->start();20652066// Let the size policy know we're starting2067size_policy->major_collection_begin();20682069CodeCache::gc_prologue();2070Threads::gc_prologue();20712072COMPILER2_PRESENT(DerivedPointerTable::clear());20732074ref_processor()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);2075ref_processor()->setup_policy(maximum_heap_compaction);20762077bool marked_for_unloading = false;20782079marking_start.update();2080marking_phase(vmthread_cm, maximum_heap_compaction, &_gc_tracer);20812082bool max_on_system_gc = UseMaximumCompactionOnSystemGC2083&& gc_cause == GCCause::_java_lang_system_gc;2084summary_phase(vmthread_cm, maximum_heap_compaction || max_on_system_gc);20852086COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity"));2087COMPILER2_PRESENT(DerivedPointerTable::set_active(false));20882089// adjust_roots() updates Universe::_intArrayKlassObj which is2090// needed by the compaction for filling holes in the dense prefix.2091adjust_roots();20922093compaction_start.update();2094compact();20952096// Reset the mark bitmap, summary data, and do other bookkeeping. Must be2097// done before resizing.2098post_compact();20992100// Let the size policy know we're done2101size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);21022103if (UseAdaptiveSizePolicy) {2104if (PrintAdaptiveSizePolicy) {2105gclog_or_tty->print("AdaptiveSizeStart: ");2106gclog_or_tty->stamp();2107gclog_or_tty->print_cr(" collection: %d ",2108heap->total_collections());2109if (Verbose) {2110gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d",2111old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());2112}2113}21142115// Don't check if the size_policy is ready here. Let2116// the size_policy check that internally.2117if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&2118((gc_cause != GCCause::_java_lang_system_gc) ||2119UseAdaptiveSizePolicyWithSystemGC)) {2120// Calculate optimal free space amounts2121assert(young_gen->max_size() >2122young_gen->from_space()->capacity_in_bytes() +2123young_gen->to_space()->capacity_in_bytes(),2124"Sizes of space in young gen are out-of-bounds");21252126size_t young_live = young_gen->used_in_bytes();2127size_t eden_live = young_gen->eden_space()->used_in_bytes();2128size_t old_live = old_gen->used_in_bytes();2129size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();2130size_t max_old_gen_size = old_gen->max_gen_size();2131size_t max_eden_size = young_gen->max_size() -2132young_gen->from_space()->capacity_in_bytes() -2133young_gen->to_space()->capacity_in_bytes();21342135// Used for diagnostics2136size_policy->clear_generation_free_space_flags();21372138size_policy->compute_generations_free_space(young_live,2139eden_live,2140old_live,2141cur_eden,2142max_old_gen_size,2143max_eden_size,2144true /* full gc*/);21452146size_policy->check_gc_overhead_limit(young_live,2147eden_live,2148max_old_gen_size,2149max_eden_size,2150true /* full gc*/,2151gc_cause,2152heap->collector_policy());21532154size_policy->decay_supplemental_growth(true /* full gc*/);21552156heap->resize_old_gen(2157size_policy->calculated_old_free_size_in_bytes());21582159// Don't resize the young generation at an major collection. A2160// desired young generation size may have been calculated but2161// resizing the young generation complicates the code because the2162// resizing of the old generation may have moved the boundary2163// between the young generation and the old generation. Let the2164// young generation resizing happen at the minor collections.2165}2166if (PrintAdaptiveSizePolicy) {2167gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",2168heap->total_collections());2169}2170}21712172if (UsePerfData) {2173PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();2174counters->update_counters();2175counters->update_old_capacity(old_gen->capacity_in_bytes());2176counters->update_young_capacity(young_gen->capacity_in_bytes());2177}21782179heap->resize_all_tlabs();21802181// Resize the metaspace capactiy after a collection2182MetaspaceGC::compute_new_size();21832184if (TraceGen1Time) accumulated_time()->stop();21852186if (PrintGC) {2187if (PrintGCDetails) {2188// No GC timestamp here. This is after GC so it would be confusing.2189young_gen->print_used_change(pre_gc_values.young_gen_used());2190old_gen->print_used_change(pre_gc_values.old_gen_used());2191heap->print_heap_change(pre_gc_values.heap_used());2192MetaspaceAux::print_metaspace_change(pre_gc_values.metadata_used());2193} else {2194heap->print_heap_change(pre_gc_values.heap_used());2195}2196}21972198// Track memory usage and detect low memory2199MemoryService::track_memory_usage();2200heap->update_counters();2201gc_task_manager()->release_idle_workers();2202}22032204#ifdef ASSERT2205for (size_t i = 0; i < ParallelGCThreads + 1; ++i) {2206ParCompactionManager* const cm =2207ParCompactionManager::manager_array(int(i));2208assert(cm->marking_stack()->is_empty(), "should be empty");2209assert(ParCompactionManager::region_list(int(i))->is_empty(), "should be empty");2210}2211#endif // ASSERT22122213if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {2214HandleMark hm; // Discard invalid handles created during verification2215Universe::verify(" VerifyAfterGC:");2216}22172218// Re-verify object start arrays2219if (VerifyObjectStartArray &&2220VerifyAfterGC) {2221old_gen->verify_object_start_array();2222}22232224if (ZapUnusedHeapArea) {2225old_gen->object_space()->check_mangled_unused_area_complete();2226}22272228NOT_PRODUCT(ref_processor()->verify_no_references_recorded());22292230collection_exit.update();22312232heap->print_heap_after_gc();2233heap->trace_heap_after_gc(&_gc_tracer);22342235if (PrintGCTaskTimeStamps) {2236gclog_or_tty->print_cr("VM-Thread " INT64_FORMAT " " INT64_FORMAT " "2237INT64_FORMAT,2238marking_start.ticks(), compaction_start.ticks(),2239collection_exit.ticks());2240gc_task_manager()->print_task_time_stamps();2241}22422243heap->post_full_gc_dump(&_gc_timer);22442245#ifdef TRACESPINNING2246ParallelTaskTerminator::print_termination_counts();2247#endif22482249_gc_timer.register_gc_end();22502251_gc_tracer.report_dense_prefix(dense_prefix(old_space_id));2252_gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());22532254return true;2255}22562257bool PSParallelCompact::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,2258PSYoungGen* young_gen,2259PSOldGen* old_gen) {2260MutableSpace* const eden_space = young_gen->eden_space();2261assert(!eden_space->is_empty(), "eden must be non-empty");2262assert(young_gen->virtual_space()->alignment() ==2263old_gen->virtual_space()->alignment(), "alignments do not match");22642265if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary)) {2266return false;2267}22682269// Both generations must be completely committed.2270if (young_gen->virtual_space()->uncommitted_size() != 0) {2271return false;2272}2273if (old_gen->virtual_space()->uncommitted_size() != 0) {2274return false;2275}22762277// Figure out how much to take from eden. Include the average amount promoted2278// in the total; otherwise the next young gen GC will simply bail out to a2279// full GC.2280const size_t alignment = old_gen->virtual_space()->alignment();2281const size_t eden_used = eden_space->used_in_bytes();2282const size_t promoted = (size_t)size_policy->avg_promoted()->padded_average();2283const size_t absorb_size = align_size_up(eden_used + promoted, alignment);2284const size_t eden_capacity = eden_space->capacity_in_bytes();22852286if (absorb_size >= eden_capacity) {2287return false; // Must leave some space in eden.2288}22892290const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;2291if (new_young_size < young_gen->min_gen_size()) {2292return false; // Respect young gen minimum size.2293}22942295if (TraceAdaptiveGCBoundary && Verbose) {2296gclog_or_tty->print(" absorbing " SIZE_FORMAT "K: "2297"eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "2298"from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "2299"young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",2300absorb_size / K,2301eden_capacity / K, (eden_capacity - absorb_size) / K,2302young_gen->from_space()->used_in_bytes() / K,2303young_gen->to_space()->used_in_bytes() / K,2304young_gen->capacity_in_bytes() / K, new_young_size / K);2305}23062307// Fill the unused part of the old gen.2308MutableSpace* const old_space = old_gen->object_space();2309HeapWord* const unused_start = old_space->top();2310size_t const unused_words = pointer_delta(old_space->end(), unused_start);23112312if (unused_words > 0) {2313if (unused_words < CollectedHeap::min_fill_size()) {2314return false; // If the old gen cannot be filled, must give up.2315}2316CollectedHeap::fill_with_objects(unused_start, unused_words);2317}23182319// Take the live data from eden and set both top and end in the old gen to2320// eden top. (Need to set end because reset_after_change() mangles the region2321// from end to virtual_space->high() in debug builds).2322HeapWord* const new_top = eden_space->top();2323old_gen->virtual_space()->expand_into(young_gen->virtual_space(),2324absorb_size);2325young_gen->reset_after_change();2326old_space->set_top(new_top);2327old_space->set_end(new_top);2328old_gen->reset_after_change();23292330// Update the object start array for the filler object and the data from eden.2331ObjectStartArray* const start_array = old_gen->start_array();2332for (HeapWord* p = unused_start; p < new_top; p += oop(p)->size()) {2333start_array->allocate_block(p);2334}23352336// Could update the promoted average here, but it is not typically updated at2337// full GCs and the value to use is unclear. Something like2338//2339// cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.23402341size_policy->set_bytes_absorbed_from_eden(absorb_size);2342return true;2343}23442345GCTaskManager* const PSParallelCompact::gc_task_manager() {2346assert(ParallelScavengeHeap::gc_task_manager() != NULL,2347"shouldn't return NULL");2348return ParallelScavengeHeap::gc_task_manager();2349}23502351void PSParallelCompact::marking_phase(ParCompactionManager* cm,2352bool maximum_heap_compaction,2353ParallelOldTracer *gc_tracer) {2354// Recursively traverse all live objects and mark them2355GCTraceTime tm("marking phase", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());23562357ParallelScavengeHeap* heap = gc_heap();2358uint parallel_gc_threads = heap->gc_task_manager()->workers();2359uint active_gc_threads = heap->gc_task_manager()->active_workers();2360TaskQueueSetSuper* qset = ParCompactionManager::stack_array();2361ParallelTaskTerminator terminator(active_gc_threads, qset);23622363PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);2364PSParallelCompact::FollowStackClosure follow_stack_closure(cm);23652366// Need new claim bits before marking starts.2367ClassLoaderDataGraph::clear_claimed_marks();23682369{2370GCTraceTime tm_m("par mark", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());23712372ParallelScavengeHeap::ParStrongRootsScope psrs;23732374GCTaskQueue* q = GCTaskQueue::create();23752376q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::universe));2377q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jni_handles));2378// We scan the thread roots in parallel2379Threads::create_thread_roots_marking_tasks(q);2380q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::object_synchronizer));2381q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::flat_profiler));2382q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::management));2383q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::system_dictionary));2384q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::class_loader_data));2385q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jvmti));2386q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::code_cache));23872388if (active_gc_threads > 1) {2389for (uint j = 0; j < active_gc_threads; j++) {2390q->enqueue(new StealMarkingTask(&terminator));2391}2392}23932394gc_task_manager()->execute_and_wait(q);2395}23962397// Process reference objects found during marking2398{2399GCTraceTime tm_r("reference processing", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());24002401ReferenceProcessorStats stats;2402if (ref_processor()->processing_is_mt()) {2403RefProcTaskExecutor task_executor;2404stats = ref_processor()->process_discovered_references(2405is_alive_closure(), &mark_and_push_closure, &follow_stack_closure,2406&task_executor, &_gc_timer, _gc_tracer.gc_id());2407} else {2408stats = ref_processor()->process_discovered_references(2409is_alive_closure(), &mark_and_push_closure, &follow_stack_closure, NULL,2410&_gc_timer, _gc_tracer.gc_id());2411}24122413gc_tracer->report_gc_reference_stats(stats);2414}24152416GCTraceTime tm_c("class unloading", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());24172418// This is the point where the entire marking should have completed.2419assert(cm->marking_stacks_empty(), "Marking should have completed");24202421// Follow system dictionary roots and unload classes.2422bool purged_class = SystemDictionary::do_unloading(is_alive_closure());24232424// Unload nmethods.2425CodeCache::do_unloading(is_alive_closure(), purged_class);24262427// Prune dead klasses from subklass/sibling/implementor lists.2428Klass::clean_weak_klass_links(is_alive_closure());24292430// Delete entries for dead interned strings.2431StringTable::unlink(is_alive_closure());24322433// Clean up unreferenced symbols in symbol table.2434SymbolTable::unlink();2435_gc_tracer.report_object_count_after_gc(is_alive_closure());2436}24372438void PSParallelCompact::follow_class_loader(ParCompactionManager* cm,2439ClassLoaderData* cld) {2440PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);2441PSParallelCompact::FollowKlassClosure follow_klass_closure(&mark_and_push_closure);24422443cld->oops_do(&mark_and_push_closure, &follow_klass_closure, true);2444}24452446void PSParallelCompact::adjust_roots() {2447// Adjust the pointers to reflect the new locations2448GCTraceTime tm("adjust roots", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());24492450// Need new claim bits when tracing through and adjusting pointers.2451ClassLoaderDataGraph::clear_claimed_marks();24522453// General strong roots.2454Universe::oops_do(adjust_pointer_closure());2455JNIHandles::oops_do(adjust_pointer_closure()); // Global (strong) JNI handles2456CLDToOopClosure adjust_from_cld(adjust_pointer_closure());2457Threads::oops_do(adjust_pointer_closure(), &adjust_from_cld, NULL);2458ObjectSynchronizer::oops_do(adjust_pointer_closure());2459FlatProfiler::oops_do(adjust_pointer_closure());2460Management::oops_do(adjust_pointer_closure());2461JvmtiExport::oops_do(adjust_pointer_closure());2462SystemDictionary::oops_do(adjust_pointer_closure());2463ClassLoaderDataGraph::oops_do(adjust_pointer_closure(), adjust_klass_closure(), true);24642465// Now adjust pointers in remaining weak roots. (All of which should2466// have been cleared if they pointed to non-surviving objects.)2467// Global (weak) JNI handles2468JNIHandles::weak_oops_do(adjust_pointer_closure());2469JFR_ONLY(Jfr::weak_oops_do(adjust_pointer_closure()));24702471CodeBlobToOopClosure adjust_from_blobs(adjust_pointer_closure(), CodeBlobToOopClosure::FixRelocations);2472CodeCache::blobs_do(&adjust_from_blobs);2473StringTable::oops_do(adjust_pointer_closure());2474ref_processor()->weak_oops_do(adjust_pointer_closure());2475// Roots were visited so references into the young gen in roots2476// may have been scanned. Process them also.2477// Should the reference processor have a span that excludes2478// young gen objects?2479PSScavenge::reference_processor()->weak_oops_do(adjust_pointer_closure());2480}24812482void PSParallelCompact::enqueue_region_draining_tasks(GCTaskQueue* q,2483uint parallel_gc_threads)2484{2485GCTraceTime tm("drain task setup", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());24862487// Find the threads that are active2488unsigned int which = 0;24892490const uint task_count = MAX2(parallel_gc_threads, 1U);2491for (uint j = 0; j < task_count; j++) {2492q->enqueue(new DrainStacksCompactionTask(j));2493ParCompactionManager::verify_region_list_empty(j);2494// Set the region stacks variables to "no" region stack values2495// so that they will be recognized and needing a region stack2496// in the stealing tasks if they do not get one by executing2497// a draining stack.2498ParCompactionManager* cm = ParCompactionManager::manager_array(j);2499cm->set_region_stack(NULL);2500cm->set_region_stack_index((uint)max_uintx);2501}2502ParCompactionManager::reset_recycled_stack_index();25032504// Find all regions that are available (can be filled immediately) and2505// distribute them to the thread stacks. The iteration is done in reverse2506// order (high to low) so the regions will be removed in ascending order.25072508const ParallelCompactData& sd = PSParallelCompact::summary_data();25092510size_t fillable_regions = 0; // A count for diagnostic purposes.2511// A region index which corresponds to the tasks created above.2512// "which" must be 0 <= which < task_count25132514which = 0;2515// id + 1 is used to test termination so unsigned can2516// be used with an old_space_id == 0.2517for (unsigned int id = to_space_id; id + 1 > old_space_id; --id) {2518SpaceInfo* const space_info = _space_info + id;2519MutableSpace* const space = space_info->space();2520HeapWord* const new_top = space_info->new_top();25212522const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());2523const size_t end_region =2524sd.addr_to_region_idx(sd.region_align_up(new_top));25252526for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {2527if (sd.region(cur)->claim_unsafe()) {2528ParCompactionManager::region_list_push(which, cur);25292530if (TraceParallelOldGCCompactionPhase && Verbose) {2531const size_t count_mod_8 = fillable_regions & 7;2532if (count_mod_8 == 0) gclog_or_tty->print("fillable: ");2533gclog_or_tty->print(" " SIZE_FORMAT_W(7), cur);2534if (count_mod_8 == 7) gclog_or_tty->cr();2535}25362537NOT_PRODUCT(++fillable_regions;)25382539// Assign regions to tasks in round-robin fashion.2540if (++which == task_count) {2541assert(which <= parallel_gc_threads,2542"Inconsistent number of workers");2543which = 0;2544}2545}2546}2547}25482549if (TraceParallelOldGCCompactionPhase) {2550if (Verbose && (fillable_regions & 7) != 0) gclog_or_tty->cr();2551gclog_or_tty->print_cr("%u initially fillable regions", fillable_regions);2552}2553}25542555#define PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING 425562557void PSParallelCompact::enqueue_dense_prefix_tasks(GCTaskQueue* q,2558uint parallel_gc_threads) {2559GCTraceTime tm("dense prefix task setup", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());25602561ParallelCompactData& sd = PSParallelCompact::summary_data();25622563// Iterate over all the spaces adding tasks for updating2564// regions in the dense prefix. Assume that 1 gc thread2565// will work on opening the gaps and the remaining gc threads2566// will work on the dense prefix.2567unsigned int space_id;2568for (space_id = old_space_id; space_id < last_space_id; ++ space_id) {2569HeapWord* const dense_prefix_end = _space_info[space_id].dense_prefix();2570const MutableSpace* const space = _space_info[space_id].space();25712572if (dense_prefix_end == space->bottom()) {2573// There is no dense prefix for this space.2574continue;2575}25762577// The dense prefix is before this region.2578size_t region_index_end_dense_prefix =2579sd.addr_to_region_idx(dense_prefix_end);2580RegionData* const dense_prefix_cp =2581sd.region(region_index_end_dense_prefix);2582assert(dense_prefix_end == space->end() ||2583dense_prefix_cp->available() ||2584dense_prefix_cp->claimed(),2585"The region after the dense prefix should always be ready to fill");25862587size_t region_index_start = sd.addr_to_region_idx(space->bottom());25882589// Is there dense prefix work?2590size_t total_dense_prefix_regions =2591region_index_end_dense_prefix - region_index_start;2592// How many regions of the dense prefix should be given to2593// each thread?2594if (total_dense_prefix_regions > 0) {2595uint tasks_for_dense_prefix = 1;2596if (total_dense_prefix_regions <=2597(parallel_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)) {2598// Don't over partition. This assumes that2599// PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING is a small integer value2600// so there are not many regions to process.2601tasks_for_dense_prefix = parallel_gc_threads;2602} else {2603// Over partition2604tasks_for_dense_prefix = parallel_gc_threads *2605PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING;2606}2607size_t regions_per_thread = total_dense_prefix_regions /2608tasks_for_dense_prefix;2609// Give each thread at least 1 region.2610if (regions_per_thread == 0) {2611regions_per_thread = 1;2612}26132614for (uint k = 0; k < tasks_for_dense_prefix; k++) {2615if (region_index_start >= region_index_end_dense_prefix) {2616break;2617}2618// region_index_end is not processed2619size_t region_index_end = MIN2(region_index_start + regions_per_thread,2620region_index_end_dense_prefix);2621q->enqueue(new UpdateDensePrefixTask(SpaceId(space_id),2622region_index_start,2623region_index_end));2624region_index_start = region_index_end;2625}2626}2627// This gets any part of the dense prefix that did not2628// fit evenly.2629if (region_index_start < region_index_end_dense_prefix) {2630q->enqueue(new UpdateDensePrefixTask(SpaceId(space_id),2631region_index_start,2632region_index_end_dense_prefix));2633}2634}2635}26362637void PSParallelCompact::enqueue_region_stealing_tasks(2638GCTaskQueue* q,2639ParallelTaskTerminator* terminator_ptr,2640uint parallel_gc_threads) {2641GCTraceTime tm("steal task setup", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());26422643// Once a thread has drained it's stack, it should try to steal regions from2644// other threads.2645if (parallel_gc_threads > 1) {2646for (uint j = 0; j < parallel_gc_threads; j++) {2647q->enqueue(new StealRegionCompactionTask(terminator_ptr));2648}2649}2650}26512652#ifdef ASSERT2653// Write a histogram of the number of times the block table was filled for a2654// region.2655void PSParallelCompact::write_block_fill_histogram(outputStream* const out)2656{2657if (!TraceParallelOldGCCompactionPhase) return;26582659typedef ParallelCompactData::RegionData rd_t;2660ParallelCompactData& sd = summary_data();26612662for (unsigned int id = old_space_id; id < last_space_id; ++id) {2663MutableSpace* const spc = _space_info[id].space();2664if (spc->bottom() != spc->top()) {2665const rd_t* const beg = sd.addr_to_region_ptr(spc->bottom());2666HeapWord* const top_aligned_up = sd.region_align_up(spc->top());2667const rd_t* const end = sd.addr_to_region_ptr(top_aligned_up);26682669size_t histo[5] = { 0, 0, 0, 0, 0 };2670const size_t histo_len = sizeof(histo) / sizeof(size_t);2671const size_t region_cnt = pointer_delta(end, beg, sizeof(rd_t));26722673for (const rd_t* cur = beg; cur < end; ++cur) {2674++histo[MIN2(cur->blocks_filled_count(), histo_len - 1)];2675}2676out->print("%u %-4s" SIZE_FORMAT_W(5), id, space_names[id], region_cnt);2677for (size_t i = 0; i < histo_len; ++i) {2678out->print(" " SIZE_FORMAT_W(5) " %5.1f%%",2679histo[i], 100.0 * histo[i] / region_cnt);2680}2681out->cr();2682}2683}2684}2685#endif // #ifdef ASSERT26862687void PSParallelCompact::compact() {2688// trace("5");2689GCTraceTime tm("compaction phase", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());26902691ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();2692assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");2693PSOldGen* old_gen = heap->old_gen();2694old_gen->start_array()->reset();2695uint parallel_gc_threads = heap->gc_task_manager()->workers();2696uint active_gc_threads = heap->gc_task_manager()->active_workers();2697TaskQueueSetSuper* qset = ParCompactionManager::region_array();2698ParallelTaskTerminator terminator(active_gc_threads, qset);26992700GCTaskQueue* q = GCTaskQueue::create();2701enqueue_region_draining_tasks(q, active_gc_threads);2702enqueue_dense_prefix_tasks(q, active_gc_threads);2703enqueue_region_stealing_tasks(q, &terminator, active_gc_threads);27042705{2706GCTraceTime tm_pc("par compact", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());27072708gc_task_manager()->execute_and_wait(q);27092710#ifdef ASSERT2711// Verify that all regions have been processed before the deferred updates.2712for (unsigned int id = old_space_id; id < last_space_id; ++id) {2713verify_complete(SpaceId(id));2714}2715#endif2716}27172718{2719// Update the deferred objects, if any. Any compaction manager can be used.2720GCTraceTime tm_du("deferred updates", print_phases(), true, &_gc_timer, _gc_tracer.gc_id());2721ParCompactionManager* cm = ParCompactionManager::manager_array(0);2722for (unsigned int id = old_space_id; id < last_space_id; ++id) {2723update_deferred_objects(cm, SpaceId(id));2724}2725}27262727DEBUG_ONLY(write_block_fill_histogram(gclog_or_tty));2728}27292730#ifdef ASSERT2731void PSParallelCompact::verify_complete(SpaceId space_id) {2732// All Regions between space bottom() to new_top() should be marked as filled2733// and all Regions between new_top() and top() should be available (i.e.,2734// should have been emptied).2735ParallelCompactData& sd = summary_data();2736SpaceInfo si = _space_info[space_id];2737HeapWord* new_top_addr = sd.region_align_up(si.new_top());2738HeapWord* old_top_addr = sd.region_align_up(si.space()->top());2739const size_t beg_region = sd.addr_to_region_idx(si.space()->bottom());2740const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);2741const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);27422743bool issued_a_warning = false;27442745size_t cur_region;2746for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {2747const RegionData* const c = sd.region(cur_region);2748if (!c->completed()) {2749warning("region " SIZE_FORMAT " not filled: "2750"destination_count=" SIZE_FORMAT,2751cur_region, c->destination_count());2752issued_a_warning = true;2753}2754}27552756for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {2757const RegionData* const c = sd.region(cur_region);2758if (!c->available()) {2759warning("region " SIZE_FORMAT " not empty: "2760"destination_count=" SIZE_FORMAT,2761cur_region, c->destination_count());2762issued_a_warning = true;2763}2764}27652766if (issued_a_warning) {2767print_region_ranges();2768}2769}2770#endif // #ifdef ASSERT27712772// Update interior oops in the ranges of regions [beg_region, end_region).2773void2774PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,2775SpaceId space_id,2776size_t beg_region,2777size_t end_region) {2778ParallelCompactData& sd = summary_data();2779ParMarkBitMap* const mbm = mark_bitmap();27802781HeapWord* beg_addr = sd.region_to_addr(beg_region);2782HeapWord* const end_addr = sd.region_to_addr(end_region);2783assert(beg_region <= end_region, "bad region range");2784assert(end_addr <= dense_prefix(space_id), "not in the dense prefix");27852786#ifdef ASSERT2787// Claim the regions to avoid triggering an assert when they are marked as2788// filled.2789for (size_t claim_region = beg_region; claim_region < end_region; ++claim_region) {2790assert(sd.region(claim_region)->claim_unsafe(), "claim() failed");2791}2792#endif // #ifdef ASSERT27932794if (beg_addr != space(space_id)->bottom()) {2795// Find the first live object or block of dead space that *starts* in this2796// range of regions. If a partial object crosses onto the region, skip it;2797// it will be marked for 'deferred update' when the object head is2798// processed. If dead space crosses onto the region, it is also skipped; it2799// will be filled when the prior region is processed. If neither of those2800// apply, the first word in the region is the start of a live object or dead2801// space.2802assert(beg_addr > space(space_id)->bottom(), "sanity");2803const RegionData* const cp = sd.region(beg_region);2804if (cp->partial_obj_size() != 0) {2805beg_addr = sd.partial_obj_end(beg_region);2806} else if (dead_space_crosses_boundary(cp, mbm->addr_to_bit(beg_addr))) {2807beg_addr = mbm->find_obj_beg(beg_addr, end_addr);2808}2809}28102811if (beg_addr < end_addr) {2812// A live object or block of dead space starts in this range of Regions.2813HeapWord* const dense_prefix_end = dense_prefix(space_id);28142815// Create closures and iterate.2816UpdateOnlyClosure update_closure(mbm, cm, space_id);2817FillClosure fill_closure(cm, space_id);2818ParMarkBitMap::IterationStatus status;2819status = mbm->iterate(&update_closure, &fill_closure, beg_addr, end_addr,2820dense_prefix_end);2821if (status == ParMarkBitMap::incomplete) {2822update_closure.do_addr(update_closure.source());2823}2824}28252826// Mark the regions as filled.2827RegionData* const beg_cp = sd.region(beg_region);2828RegionData* const end_cp = sd.region(end_region);2829for (RegionData* cp = beg_cp; cp < end_cp; ++cp) {2830cp->set_completed();2831}2832}28332834// Return the SpaceId for the space containing addr. If addr is not in the2835// heap, last_space_id is returned. In debug mode it expects the address to be2836// in the heap and asserts such.2837PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {2838assert(Universe::heap()->is_in_reserved(addr), "addr not in the heap");28392840for (unsigned int id = old_space_id; id < last_space_id; ++id) {2841if (_space_info[id].space()->contains(addr)) {2842return SpaceId(id);2843}2844}28452846assert(false, "no space contains the addr");2847return last_space_id;2848}28492850void PSParallelCompact::update_deferred_objects(ParCompactionManager* cm,2851SpaceId id) {2852assert(id < last_space_id, "bad space id");28532854ParallelCompactData& sd = summary_data();2855const SpaceInfo* const space_info = _space_info + id;2856ObjectStartArray* const start_array = space_info->start_array();28572858const MutableSpace* const space = space_info->space();2859assert(space_info->dense_prefix() >= space->bottom(), "dense_prefix not set");2860HeapWord* const beg_addr = space_info->dense_prefix();2861HeapWord* const end_addr = sd.region_align_up(space_info->new_top());28622863const RegionData* const beg_region = sd.addr_to_region_ptr(beg_addr);2864const RegionData* const end_region = sd.addr_to_region_ptr(end_addr);2865const RegionData* cur_region;2866for (cur_region = beg_region; cur_region < end_region; ++cur_region) {2867HeapWord* const addr = cur_region->deferred_obj_addr();2868if (addr != NULL) {2869if (start_array != NULL) {2870start_array->allocate_block(addr);2871}2872oop(addr)->update_contents(cm);2873assert(oop(addr)->is_oop_or_null(), "should be an oop now");2874}2875}2876}28772878// Skip over count live words starting from beg, and return the address of the2879// next live word. Unless marked, the word corresponding to beg is assumed to2880// be dead. Callers must either ensure beg does not correspond to the middle of2881// an object, or account for those live words in some other way. Callers must2882// also ensure that there are enough live words in the range [beg, end) to skip.2883HeapWord*2884PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)2885{2886assert(count > 0, "sanity");28872888ParMarkBitMap* m = mark_bitmap();2889idx_t bits_to_skip = m->words_to_bits(count);2890idx_t cur_beg = m->addr_to_bit(beg);2891const idx_t search_end = BitMap::word_align_up(m->addr_to_bit(end));28922893do {2894cur_beg = m->find_obj_beg(cur_beg, search_end);2895idx_t cur_end = m->find_obj_end(cur_beg, search_end);2896const size_t obj_bits = cur_end - cur_beg + 1;2897if (obj_bits > bits_to_skip) {2898return m->bit_to_addr(cur_beg + bits_to_skip);2899}2900bits_to_skip -= obj_bits;2901cur_beg = cur_end + 1;2902} while (bits_to_skip > 0);29032904// Skipping the desired number of words landed just past the end of an object.2905// Find the start of the next object.2906cur_beg = m->find_obj_beg(cur_beg, search_end);2907assert(cur_beg < m->addr_to_bit(end), "not enough live words to skip");2908return m->bit_to_addr(cur_beg);2909}29102911HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,2912SpaceId src_space_id,2913size_t src_region_idx)2914{2915assert(summary_data().is_region_aligned(dest_addr), "not aligned");29162917const SplitInfo& split_info = _space_info[src_space_id].split_info();2918if (split_info.dest_region_addr() == dest_addr) {2919// The partial object ending at the split point contains the first word to2920// be copied to dest_addr.2921return split_info.first_src_addr();2922}29232924const ParallelCompactData& sd = summary_data();2925ParMarkBitMap* const bitmap = mark_bitmap();2926const size_t RegionSize = ParallelCompactData::RegionSize;29272928assert(sd.is_region_aligned(dest_addr), "not aligned");2929const RegionData* const src_region_ptr = sd.region(src_region_idx);2930const size_t partial_obj_size = src_region_ptr->partial_obj_size();2931HeapWord* const src_region_destination = src_region_ptr->destination();29322933assert(dest_addr >= src_region_destination, "wrong src region");2934assert(src_region_ptr->data_size() > 0, "src region cannot be empty");29352936HeapWord* const src_region_beg = sd.region_to_addr(src_region_idx);2937HeapWord* const src_region_end = src_region_beg + RegionSize;29382939HeapWord* addr = src_region_beg;2940if (dest_addr == src_region_destination) {2941// Return the first live word in the source region.2942if (partial_obj_size == 0) {2943addr = bitmap->find_obj_beg(addr, src_region_end);2944assert(addr < src_region_end, "no objects start in src region");2945}2946return addr;2947}29482949// Must skip some live data.2950size_t words_to_skip = dest_addr - src_region_destination;2951assert(src_region_ptr->data_size() > words_to_skip, "wrong src region");29522953if (partial_obj_size >= words_to_skip) {2954// All the live words to skip are part of the partial object.2955addr += words_to_skip;2956if (partial_obj_size == words_to_skip) {2957// Find the first live word past the partial object.2958addr = bitmap->find_obj_beg(addr, src_region_end);2959assert(addr < src_region_end, "wrong src region");2960}2961return addr;2962}29632964// Skip over the partial object (if any).2965if (partial_obj_size != 0) {2966words_to_skip -= partial_obj_size;2967addr += partial_obj_size;2968}29692970// Skip over live words due to objects that start in the region.2971addr = skip_live_words(addr, src_region_end, words_to_skip);2972assert(addr < src_region_end, "wrong src region");2973return addr;2974}29752976void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,2977SpaceId src_space_id,2978size_t beg_region,2979HeapWord* end_addr)2980{2981ParallelCompactData& sd = summary_data();29822983#ifdef ASSERT2984MutableSpace* const src_space = _space_info[src_space_id].space();2985HeapWord* const beg_addr = sd.region_to_addr(beg_region);2986assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),2987"src_space_id does not match beg_addr");2988assert(src_space->contains(end_addr) || end_addr == src_space->end(),2989"src_space_id does not match end_addr");2990#endif // #ifdef ASSERT29912992RegionData* const beg = sd.region(beg_region);2993RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));29942995// Regions up to new_top() are enqueued if they become available.2996HeapWord* const new_top = _space_info[src_space_id].new_top();2997RegionData* const enqueue_end =2998sd.addr_to_region_ptr(sd.region_align_up(new_top));29993000for (RegionData* cur = beg; cur < end; ++cur) {3001assert(cur->data_size() > 0, "region must have live data");3002cur->decrement_destination_count();3003if (cur < enqueue_end && cur->available() && cur->claim()) {3004cm->push_region(sd.region(cur));3005}3006}3007}30083009size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,3010SpaceId& src_space_id,3011HeapWord*& src_space_top,3012HeapWord* end_addr)3013{3014typedef ParallelCompactData::RegionData RegionData;30153016ParallelCompactData& sd = PSParallelCompact::summary_data();3017const size_t region_size = ParallelCompactData::RegionSize;30183019size_t src_region_idx = 0;30203021// Skip empty regions (if any) up to the top of the space.3022HeapWord* const src_aligned_up = sd.region_align_up(end_addr);3023RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);3024HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);3025const RegionData* const top_region_ptr =3026sd.addr_to_region_ptr(top_aligned_up);3027while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {3028++src_region_ptr;3029}30303031if (src_region_ptr < top_region_ptr) {3032// The next source region is in the current space. Update src_region_idx3033// and the source address to match src_region_ptr.3034src_region_idx = sd.region(src_region_ptr);3035HeapWord* const src_region_addr = sd.region_to_addr(src_region_idx);3036if (src_region_addr > closure.source()) {3037closure.set_source(src_region_addr);3038}3039return src_region_idx;3040}30413042// Switch to a new source space and find the first non-empty region.3043unsigned int space_id = src_space_id + 1;3044assert(space_id < last_space_id, "not enough spaces");30453046HeapWord* const destination = closure.destination();30473048do {3049MutableSpace* space = _space_info[space_id].space();3050HeapWord* const bottom = space->bottom();3051const RegionData* const bottom_cp = sd.addr_to_region_ptr(bottom);30523053// Iterate over the spaces that do not compact into themselves.3054if (bottom_cp->destination() != bottom) {3055HeapWord* const top_aligned_up = sd.region_align_up(space->top());3056const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);30573058for (const RegionData* src_cp = bottom_cp; src_cp < top_cp; ++src_cp) {3059if (src_cp->live_obj_size() > 0) {3060// Found it.3061assert(src_cp->destination() == destination,3062"first live obj in the space must match the destination");3063assert(src_cp->partial_obj_size() == 0,3064"a space cannot begin with a partial obj");30653066src_space_id = SpaceId(space_id);3067src_space_top = space->top();3068const size_t src_region_idx = sd.region(src_cp);3069closure.set_source(sd.region_to_addr(src_region_idx));3070return src_region_idx;3071} else {3072assert(src_cp->data_size() == 0, "sanity");3073}3074}3075}3076} while (++space_id < last_space_id);30773078assert(false, "no source region was found");3079return 0;3080}30813082void PSParallelCompact::fill_region(ParCompactionManager* cm, size_t region_idx)3083{3084typedef ParMarkBitMap::IterationStatus IterationStatus;3085const size_t RegionSize = ParallelCompactData::RegionSize;3086ParMarkBitMap* const bitmap = mark_bitmap();3087ParallelCompactData& sd = summary_data();3088RegionData* const region_ptr = sd.region(region_idx);30893090// Get the items needed to construct the closure.3091HeapWord* dest_addr = sd.region_to_addr(region_idx);3092SpaceId dest_space_id = space_id(dest_addr);3093ObjectStartArray* start_array = _space_info[dest_space_id].start_array();3094HeapWord* new_top = _space_info[dest_space_id].new_top();3095assert(dest_addr < new_top, "sanity");3096const size_t words = MIN2(pointer_delta(new_top, dest_addr), RegionSize);30973098// Get the source region and related info.3099size_t src_region_idx = region_ptr->source_region();3100SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));3101HeapWord* src_space_top = _space_info[src_space_id].space()->top();31023103MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);3104closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));31053106// Adjust src_region_idx to prepare for decrementing destination counts (the3107// destination count is not decremented when a region is copied to itself).3108if (src_region_idx == region_idx) {3109src_region_idx += 1;3110}31113112if (bitmap->is_unmarked(closure.source())) {3113// The first source word is in the middle of an object; copy the remainder3114// of the object or as much as will fit. The fact that pointer updates were3115// deferred will be noted when the object header is processed.3116HeapWord* const old_src_addr = closure.source();3117closure.copy_partial_obj();3118if (closure.is_full()) {3119decrement_destination_counts(cm, src_space_id, src_region_idx,3120closure.source());3121region_ptr->set_deferred_obj_addr(NULL);3122region_ptr->set_completed();3123return;3124}31253126HeapWord* const end_addr = sd.region_align_down(closure.source());3127if (sd.region_align_down(old_src_addr) != end_addr) {3128// The partial object was copied from more than one source region.3129decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);31303131// Move to the next source region, possibly switching spaces as well. All3132// args except end_addr may be modified.3133src_region_idx = next_src_region(closure, src_space_id, src_space_top,3134end_addr);3135}3136}31373138do {3139HeapWord* const cur_addr = closure.source();3140HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),3141src_space_top);3142IterationStatus status = bitmap->iterate(&closure, cur_addr, end_addr);31433144if (status == ParMarkBitMap::incomplete) {3145// The last obj that starts in the source region does not end in the3146// region.3147assert(closure.source() < end_addr, "sanity");3148HeapWord* const obj_beg = closure.source();3149HeapWord* const range_end = MIN2(obj_beg + closure.words_remaining(),3150src_space_top);3151HeapWord* const obj_end = bitmap->find_obj_end(obj_beg, range_end);3152if (obj_end < range_end) {3153// The end was found; the entire object will fit.3154status = closure.do_addr(obj_beg, bitmap->obj_size(obj_beg, obj_end));3155assert(status != ParMarkBitMap::would_overflow, "sanity");3156} else {3157// The end was not found; the object will not fit.3158assert(range_end < src_space_top, "obj cannot cross space boundary");3159status = ParMarkBitMap::would_overflow;3160}3161}31623163if (status == ParMarkBitMap::would_overflow) {3164// The last object did not fit. Note that interior oop updates were3165// deferred, then copy enough of the object to fill the region.3166region_ptr->set_deferred_obj_addr(closure.destination());3167status = closure.copy_until_full(); // copies from closure.source()31683169decrement_destination_counts(cm, src_space_id, src_region_idx,3170closure.source());3171region_ptr->set_completed();3172return;3173}31743175if (status == ParMarkBitMap::full) {3176decrement_destination_counts(cm, src_space_id, src_region_idx,3177closure.source());3178region_ptr->set_deferred_obj_addr(NULL);3179region_ptr->set_completed();3180return;3181}31823183decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);31843185// Move to the next source region, possibly switching spaces as well. All3186// args except end_addr may be modified.3187src_region_idx = next_src_region(closure, src_space_id, src_space_top,3188end_addr);3189} while (true);3190}31913192void PSParallelCompact::fill_blocks(size_t region_idx)3193{3194// Fill in the block table elements for the specified region. Each block3195// table element holds the number of live words in the region that are to the3196// left of the first object that starts in the block. Thus only blocks in3197// which an object starts need to be filled.3198//3199// The algorithm scans the section of the bitmap that corresponds to the3200// region, keeping a running total of the live words. When an object start is3201// found, if it's the first to start in the block that contains it, the3202// current total is written to the block table element.3203const size_t Log2BlockSize = ParallelCompactData::Log2BlockSize;3204const size_t Log2RegionSize = ParallelCompactData::Log2RegionSize;3205const size_t RegionSize = ParallelCompactData::RegionSize;32063207ParallelCompactData& sd = summary_data();3208const size_t partial_obj_size = sd.region(region_idx)->partial_obj_size();3209if (partial_obj_size >= RegionSize) {3210return; // No objects start in this region.3211}32123213// Ensure the first loop iteration decides that the block has changed.3214size_t cur_block = sd.block_count();32153216const ParMarkBitMap* const bitmap = mark_bitmap();32173218const size_t Log2BitsPerBlock = Log2BlockSize - LogMinObjAlignment;3219assert((size_t)1 << Log2BitsPerBlock ==3220bitmap->words_to_bits(ParallelCompactData::BlockSize), "sanity");32213222size_t beg_bit = bitmap->words_to_bits(region_idx << Log2RegionSize);3223const size_t range_end = beg_bit + bitmap->words_to_bits(RegionSize);3224size_t live_bits = bitmap->words_to_bits(partial_obj_size);3225beg_bit = bitmap->find_obj_beg(beg_bit + live_bits, range_end);3226while (beg_bit < range_end) {3227const size_t new_block = beg_bit >> Log2BitsPerBlock;3228if (new_block != cur_block) {3229cur_block = new_block;3230sd.block(cur_block)->set_offset(bitmap->bits_to_words(live_bits));3231}32323233const size_t end_bit = bitmap->find_obj_end(beg_bit, range_end);3234if (end_bit < range_end - 1) {3235live_bits += end_bit - beg_bit + 1;3236beg_bit = bitmap->find_obj_beg(end_bit + 1, range_end);3237} else {3238return;3239}3240}3241}32423243void3244PSParallelCompact::move_and_update(ParCompactionManager* cm, SpaceId space_id) {3245const MutableSpace* sp = space(space_id);3246if (sp->is_empty()) {3247return;3248}32493250ParallelCompactData& sd = PSParallelCompact::summary_data();3251ParMarkBitMap* const bitmap = mark_bitmap();3252HeapWord* const dp_addr = dense_prefix(space_id);3253HeapWord* beg_addr = sp->bottom();3254HeapWord* end_addr = sp->top();32553256assert(beg_addr <= dp_addr && dp_addr <= end_addr, "bad dense prefix");32573258const size_t beg_region = sd.addr_to_region_idx(beg_addr);3259const size_t dp_region = sd.addr_to_region_idx(dp_addr);3260if (beg_region < dp_region) {3261update_and_deadwood_in_dense_prefix(cm, space_id, beg_region, dp_region);3262}32633264// The destination of the first live object that starts in the region is one3265// past the end of the partial object entering the region (if any).3266HeapWord* const dest_addr = sd.partial_obj_end(dp_region);3267HeapWord* const new_top = _space_info[space_id].new_top();3268assert(new_top >= dest_addr, "bad new_top value");3269const size_t words = pointer_delta(new_top, dest_addr);32703271if (words > 0) {3272ObjectStartArray* start_array = _space_info[space_id].start_array();3273MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);32743275ParMarkBitMap::IterationStatus status;3276status = bitmap->iterate(&closure, dest_addr, end_addr);3277assert(status == ParMarkBitMap::full, "iteration not complete");3278assert(bitmap->find_obj_beg(closure.source(), end_addr) == end_addr,3279"live objects skipped because closure is full");3280}3281}32823283jlong PSParallelCompact::millis_since_last_gc() {3284// We need a monotonically non-deccreasing time in ms but3285// os::javaTimeMillis() does not guarantee monotonicity.3286jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;3287jlong ret_val = now - _time_of_last_gc;3288// XXX See note in genCollectedHeap::millis_since_last_gc().3289if (ret_val < 0) {3290NOT_PRODUCT(warning("time warp: " INT64_FORMAT, ret_val);)3291return 0;3292}3293return ret_val;3294}32953296void PSParallelCompact::reset_millis_since_last_gc() {3297// We need a monotonically non-deccreasing time in ms but3298// os::javaTimeMillis() does not guarantee monotonicity.3299_time_of_last_gc = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;3300}33013302ParMarkBitMap::IterationStatus MoveAndUpdateClosure::copy_until_full()3303{3304if (source() != destination()) {3305DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)3306Copy::aligned_conjoint_words(source(), destination(), words_remaining());3307}3308update_state(words_remaining());3309assert(is_full(), "sanity");3310return ParMarkBitMap::full;3311}33123313void MoveAndUpdateClosure::copy_partial_obj()3314{3315size_t words = words_remaining();33163317HeapWord* const range_end = MIN2(source() + words, bitmap()->region_end());3318HeapWord* const end_addr = bitmap()->find_obj_end(source(), range_end);3319if (end_addr < range_end) {3320words = bitmap()->obj_size(source(), end_addr);3321}33223323// This test is necessary; if omitted, the pointer updates to a partial object3324// that crosses the dense prefix boundary could be overwritten.3325if (source() != destination()) {3326DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)3327Copy::aligned_conjoint_words(source(), destination(), words);3328}3329update_state(words);3330}33313332ParMarkBitMapClosure::IterationStatus3333MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {3334assert(destination() != NULL, "sanity");3335assert(bitmap()->obj_size(addr) == words, "bad size");33363337_source = addr;3338assert(PSParallelCompact::summary_data().calc_new_pointer(source()) ==3339destination(), "wrong destination");33403341if (words > words_remaining()) {3342return ParMarkBitMap::would_overflow;3343}33443345// The start_array must be updated even if the object is not moving.3346if (_start_array != NULL) {3347_start_array->allocate_block(destination());3348}33493350if (destination() != source()) {3351DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)3352Copy::aligned_conjoint_words(source(), destination(), words);3353}33543355oop moved_oop = (oop) destination();3356moved_oop->update_contents(compaction_manager());3357assert(moved_oop->is_oop_or_null(), "Object should be whole at this point");33583359update_state(words);3360assert(destination() == (HeapWord*)moved_oop + moved_oop->size(), "sanity");3361return is_full() ? ParMarkBitMap::full : ParMarkBitMap::incomplete;3362}33633364UpdateOnlyClosure::UpdateOnlyClosure(ParMarkBitMap* mbm,3365ParCompactionManager* cm,3366PSParallelCompact::SpaceId space_id) :3367ParMarkBitMapClosure(mbm, cm),3368_space_id(space_id),3369_start_array(PSParallelCompact::start_array(space_id))3370{3371}33723373// Updates the references in the object to their new values.3374ParMarkBitMapClosure::IterationStatus3375UpdateOnlyClosure::do_addr(HeapWord* addr, size_t words) {3376do_addr(addr);3377return ParMarkBitMap::incomplete;3378}337933803381