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