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