1 /* 2 * Copyright (c) 2001, 2020, 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/systemDictionary.hpp" 27 #include "gc/shared/allocTracer.hpp" 28 #include "gc/shared/barrierSet.hpp" 29 #include "gc/shared/collectedHeap.hpp" 30 #include "gc/shared/collectedHeap.inline.hpp" 31 #include "gc/shared/gcLocker.inline.hpp" 32 #include "gc/shared/gcHeapSummary.hpp" 33 #include "gc/shared/gcTrace.hpp" 34 #include "gc/shared/gcTraceTime.inline.hpp" 35 #include "gc/shared/gcVMOperations.hpp" 36 #include "gc/shared/gcWhen.hpp" 37 #include "gc/shared/memAllocator.hpp" 38 #include "logging/log.hpp" 39 #include "memory/metaspace.hpp" 40 #include "memory/resourceArea.hpp" 41 #include "memory/universe.hpp" 42 #include "oops/instanceMirrorKlass.hpp" 43 #include "oops/oop.inline.hpp" 44 #include "runtime/handles.inline.hpp" 45 #include "runtime/init.hpp" 46 #include "runtime/thread.inline.hpp" 47 #include "runtime/threadSMR.hpp" 48 #include "runtime/vmThread.hpp" 49 #include "services/heapDumper.hpp" 50 #include "utilities/align.hpp" 51 #include "utilities/copy.hpp" 52 53 class ClassLoaderData; 54 55 size_t CollectedHeap::_filler_array_max_size = 0; 56 57 template <> 58 void EventLogBase<GCMessage>::print(outputStream* st, GCMessage& m) { 59 st->print_cr("GC heap %s", m.is_before ? "before" : "after"); 60 st->print_raw(m); 61 } 62 63 void GCHeapLog::log_heap(CollectedHeap* heap, bool before) { 64 if (!should_log()) { 65 return; 66 } 67 68 double timestamp = fetch_timestamp(); 69 MutexLocker ml(&_mutex, Mutex::_no_safepoint_check_flag); 70 int index = compute_log_index(); 71 _records[index].thread = NULL; // Its the GC thread so it's not that interesting. 72 _records[index].timestamp = timestamp; 73 _records[index].data.is_before = before; 74 stringStream st(_records[index].data.buffer(), _records[index].data.size()); 75 76 st.print_cr("{Heap %s GC invocations=%u (full %u):", 77 before ? "before" : "after", 78 heap->total_collections(), 79 heap->total_full_collections()); 80 81 heap->print_on(&st); 82 st.print_cr("}"); 83 } 84 85 size_t CollectedHeap::unused() const { 86 MutexLocker ml(Heap_lock); 87 return capacity() - used(); 88 } 89 90 VirtualSpaceSummary CollectedHeap::create_heap_space_summary() { 91 size_t capacity_in_words = capacity() / HeapWordSize; 92 93 return VirtualSpaceSummary( 94 _reserved.start(), _reserved.start() + capacity_in_words, _reserved.end()); 95 } 96 97 GCHeapSummary CollectedHeap::create_heap_summary() { 98 VirtualSpaceSummary heap_space = create_heap_space_summary(); 99 return GCHeapSummary(heap_space, used()); 100 } 101 102 MetaspaceSummary CollectedHeap::create_metaspace_summary() { 103 const MetaspaceSizes meta_space( 104 MetaspaceUtils::committed_bytes(), 105 MetaspaceUtils::used_bytes(), 106 MetaspaceUtils::reserved_bytes()); 107 const MetaspaceSizes data_space( 108 MetaspaceUtils::committed_bytes(Metaspace::NonClassType), 109 MetaspaceUtils::used_bytes(Metaspace::NonClassType), 110 MetaspaceUtils::reserved_bytes(Metaspace::NonClassType)); 111 const MetaspaceSizes class_space( 112 MetaspaceUtils::committed_bytes(Metaspace::ClassType), 113 MetaspaceUtils::used_bytes(Metaspace::ClassType), 114 MetaspaceUtils::reserved_bytes(Metaspace::ClassType)); 115 116 const MetaspaceChunkFreeListSummary& ms_chunk_free_list_summary = 117 MetaspaceUtils::chunk_free_list_summary(Metaspace::NonClassType); 118 const MetaspaceChunkFreeListSummary& class_chunk_free_list_summary = 119 MetaspaceUtils::chunk_free_list_summary(Metaspace::ClassType); 120 121 return MetaspaceSummary(MetaspaceGC::capacity_until_GC(), meta_space, data_space, class_space, 122 ms_chunk_free_list_summary, class_chunk_free_list_summary); 123 } 124 125 void CollectedHeap::run_task_at_safepoint(AbstractGangTask* task, uint num_workers) { 126 WorkGang* gang = safepoint_workers(); 127 if (gang == NULL) { 128 // GC doesn't support parallel worker threads. 129 // Execute in this thread with worker id 0. 130 task->work(0); 131 } else { 132 gang->run_task(task, num_workers); 133 } 134 } 135 136 void CollectedHeap::print_heap_before_gc() { 137 Universe::print_heap_before_gc(); 138 if (_gc_heap_log != NULL) { 139 _gc_heap_log->log_heap_before(this); 140 } 141 } 142 143 void CollectedHeap::print_heap_after_gc() { 144 Universe::print_heap_after_gc(); 145 if (_gc_heap_log != NULL) { 146 _gc_heap_log->log_heap_after(this); 147 } 148 } 149 150 void CollectedHeap::print() const { print_on(tty); } 151 152 void CollectedHeap::print_on_error(outputStream* st) const { 153 st->print_cr("Heap:"); 154 print_extended_on(st); 155 st->cr(); 156 157 BarrierSet* bs = BarrierSet::barrier_set(); 158 if (bs != NULL) { 159 bs->print_on(st); 160 } 161 } 162 163 void CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) { 164 const GCHeapSummary& heap_summary = create_heap_summary(); 165 gc_tracer->report_gc_heap_summary(when, heap_summary); 166 167 const MetaspaceSummary& metaspace_summary = create_metaspace_summary(); 168 gc_tracer->report_metaspace_summary(when, metaspace_summary); 169 } 170 171 void CollectedHeap::trace_heap_before_gc(const GCTracer* gc_tracer) { 172 trace_heap(GCWhen::BeforeGC, gc_tracer); 173 } 174 175 void CollectedHeap::trace_heap_after_gc(const GCTracer* gc_tracer) { 176 trace_heap(GCWhen::AfterGC, gc_tracer); 177 } 178 179 // Default implementation, for collectors that don't support the feature. 180 bool CollectedHeap::supports_concurrent_gc_breakpoints() const { 181 return false; 182 } 183 184 bool CollectedHeap::is_oop(oop object) const { 185 if (!is_object_aligned(object)) { 186 return false; 187 } 188 189 if (!is_in(object)) { 190 return false; 191 } 192 193 if (is_in(object->klass_or_null())) { 194 return false; 195 } 196 197 return true; 198 } 199 200 // Memory state functions. 201 202 203 CollectedHeap::CollectedHeap() : 204 _is_gc_active(false), 205 _last_whole_heap_examined_time_ns(os::javaTimeNanos()), 206 _total_collections(0), 207 _total_full_collections(0), 208 _gc_cause(GCCause::_no_gc), 209 _gc_lastcause(GCCause::_no_gc) 210 { 211 const size_t max_len = size_t(arrayOopDesc::max_array_length(T_INT)); 212 const size_t elements_per_word = HeapWordSize / sizeof(jint); 213 _filler_array_max_size = align_object_size(filler_array_hdr_size() + 214 max_len / elements_per_word); 215 216 NOT_PRODUCT(_promotion_failure_alot_count = 0;) 217 NOT_PRODUCT(_promotion_failure_alot_gc_number = 0;) 218 219 if (UsePerfData) { 220 EXCEPTION_MARK; 221 222 // create the gc cause jvmstat counters 223 _perf_gc_cause = PerfDataManager::create_string_variable(SUN_GC, "cause", 224 80, GCCause::to_string(_gc_cause), CHECK); 225 226 _perf_gc_lastcause = 227 PerfDataManager::create_string_variable(SUN_GC, "lastCause", 228 80, GCCause::to_string(_gc_lastcause), CHECK); 229 } 230 231 // Create the ring log 232 if (LogEvents) { 233 _gc_heap_log = new GCHeapLog(); 234 } else { 235 _gc_heap_log = NULL; 236 } 237 } 238 239 // This interface assumes that it's being called by the 240 // vm thread. It collects the heap assuming that the 241 // heap lock is already held and that we are executing in 242 // the context of the vm thread. 243 void CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) { 244 Thread* thread = Thread::current(); 245 assert(thread->is_VM_thread(), "Precondition#1"); 246 assert(Heap_lock->is_locked(), "Precondition#2"); 247 GCCauseSetter gcs(this, cause); 248 switch (cause) { 249 case GCCause::_heap_inspection: 250 case GCCause::_heap_dump: 251 case GCCause::_metadata_GC_threshold : { 252 HandleMark hm(thread); 253 do_full_collection(false); // don't clear all soft refs 254 break; 255 } 256 case GCCause::_archive_time_gc: 257 case GCCause::_metadata_GC_clear_soft_refs: { 258 HandleMark hm(thread); 259 do_full_collection(true); // do clear all soft refs 260 break; 261 } 262 default: 263 ShouldNotReachHere(); // Unexpected use of this function 264 } 265 } 266 267 MetaWord* CollectedHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data, 268 size_t word_size, 269 Metaspace::MetadataType mdtype) { 270 uint loop_count = 0; 271 uint gc_count = 0; 272 uint full_gc_count = 0; 273 274 assert(!Heap_lock->owned_by_self(), "Should not be holding the Heap_lock"); 275 276 do { 277 MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype); 278 if (result != NULL) { 279 return result; 280 } 281 282 if (GCLocker::is_active_and_needs_gc()) { 283 // If the GCLocker is active, just expand and allocate. 284 // If that does not succeed, wait if this thread is not 285 // in a critical section itself. 286 result = loader_data->metaspace_non_null()->expand_and_allocate(word_size, mdtype); 287 if (result != NULL) { 288 return result; 289 } 290 JavaThread* jthr = JavaThread::current(); 291 if (!jthr->in_critical()) { 292 // Wait for JNI critical section to be exited 293 GCLocker::stall_until_clear(); 294 // The GC invoked by the last thread leaving the critical 295 // section will be a young collection and a full collection 296 // is (currently) needed for unloading classes so continue 297 // to the next iteration to get a full GC. 298 continue; 299 } else { 300 if (CheckJNICalls) { 301 fatal("Possible deadlock due to allocating while" 302 " in jni critical section"); 303 } 304 return NULL; 305 } 306 } 307 308 { // Need lock to get self consistent gc_count's 309 MutexLocker ml(Heap_lock); 310 gc_count = Universe::heap()->total_collections(); 311 full_gc_count = Universe::heap()->total_full_collections(); 312 } 313 314 // Generate a VM operation 315 VM_CollectForMetadataAllocation op(loader_data, 316 word_size, 317 mdtype, 318 gc_count, 319 full_gc_count, 320 GCCause::_metadata_GC_threshold); 321 VMThread::execute(&op); 322 323 // If GC was locked out, try again. Check before checking success because the 324 // prologue could have succeeded and the GC still have been locked out. 325 if (op.gc_locked()) { 326 continue; 327 } 328 329 if (op.prologue_succeeded()) { 330 return op.result(); 331 } 332 loop_count++; 333 if ((QueuedAllocationWarningCount > 0) && 334 (loop_count % QueuedAllocationWarningCount == 0)) { 335 log_warning(gc, ergo)("satisfy_failed_metadata_allocation() retries %d times," 336 " size=" SIZE_FORMAT, loop_count, word_size); 337 } 338 } while (true); // Until a GC is done 339 } 340 341 MemoryUsage CollectedHeap::memory_usage() { 342 return MemoryUsage(InitialHeapSize, used(), capacity(), max_capacity()); 343 } 344 345 346 #ifndef PRODUCT 347 void CollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr, size_t size) { 348 if (CheckMemoryInitialization && ZapUnusedHeapArea) { 349 // please note mismatch between size (in 32/64 bit words), and ju_addr that always point to a 32 bit word 350 for (juint* ju_addr = reinterpret_cast<juint*>(addr); ju_addr < reinterpret_cast<juint*>(addr + size); ++ju_addr) { 351 assert(*ju_addr == badHeapWordVal, "Found non badHeapWordValue in pre-allocation check"); 352 } 353 } 354 } 355 #endif // PRODUCT 356 357 size_t CollectedHeap::max_tlab_size() const { 358 // TLABs can't be bigger than we can fill with a int[Integer.MAX_VALUE]. 359 // This restriction could be removed by enabling filling with multiple arrays. 360 // If we compute that the reasonable way as 361 // header_size + ((sizeof(jint) * max_jint) / HeapWordSize) 362 // we'll overflow on the multiply, so we do the divide first. 363 // We actually lose a little by dividing first, 364 // but that just makes the TLAB somewhat smaller than the biggest array, 365 // which is fine, since we'll be able to fill that. 366 size_t max_int_size = typeArrayOopDesc::header_size(T_INT) + 367 sizeof(jint) * 368 ((juint) max_jint / (size_t) HeapWordSize); 369 return align_down(max_int_size, MinObjAlignment); 370 } 371 372 size_t CollectedHeap::filler_array_hdr_size() { 373 return align_object_offset(arrayOopDesc::header_size(T_INT)); // align to Long 374 } 375 376 size_t CollectedHeap::filler_array_min_size() { 377 return align_object_size(filler_array_hdr_size()); // align to MinObjAlignment 378 } 379 380 #ifdef ASSERT 381 void CollectedHeap::fill_args_check(HeapWord* start, size_t words) 382 { 383 assert(words >= min_fill_size(), "too small to fill"); 384 assert(is_object_aligned(words), "unaligned size"); 385 } 386 387 void CollectedHeap::zap_filler_array(HeapWord* start, size_t words, bool zap) 388 { 389 if (ZapFillerObjects && zap) { 390 Copy::fill_to_words(start + filler_array_hdr_size(), 391 words - filler_array_hdr_size(), 0XDEAFBABE); 392 } 393 } 394 #endif // ASSERT 395 396 void 397 CollectedHeap::fill_with_array(HeapWord* start, size_t words, bool zap) 398 { 399 assert(words >= filler_array_min_size(), "too small for an array"); 400 assert(words <= filler_array_max_size(), "too big for a single object"); 401 402 const size_t payload_size = words - filler_array_hdr_size(); 403 const size_t len = payload_size * HeapWordSize / sizeof(jint); 404 assert((int)len >= 0, "size too large " SIZE_FORMAT " becomes %d", words, (int)len); 405 406 ObjArrayAllocator allocator(Universe::intArrayKlassObj(), words, (int)len, /* do_zero */ false); 407 allocator.initialize(start); 408 DEBUG_ONLY(zap_filler_array(start, words, zap);) 409 } 410 411 void 412 CollectedHeap::fill_with_object_impl(HeapWord* start, size_t words, bool zap) 413 { 414 assert(words <= filler_array_max_size(), "too big for a single object"); 415 416 if (words >= filler_array_min_size()) { 417 fill_with_array(start, words, zap); 418 } else if (words > 0) { 419 assert(words == min_fill_size(), "unaligned size"); 420 ObjAllocator allocator(SystemDictionary::Object_klass(), words); 421 allocator.initialize(start); 422 } 423 } 424 425 void CollectedHeap::fill_with_object(HeapWord* start, size_t words, bool zap) 426 { 427 DEBUG_ONLY(fill_args_check(start, words);) 428 HandleMark hm(Thread::current()); // Free handles before leaving. 429 fill_with_object_impl(start, words, zap); 430 } 431 432 void CollectedHeap::fill_with_objects(HeapWord* start, size_t words, bool zap) 433 { 434 DEBUG_ONLY(fill_args_check(start, words);) 435 HandleMark hm(Thread::current()); // Free handles before leaving. 436 437 // Multiple objects may be required depending on the filler array maximum size. Fill 438 // the range up to that with objects that are filler_array_max_size sized. The 439 // remainder is filled with a single object. 440 const size_t min = min_fill_size(); 441 const size_t max = filler_array_max_size(); 442 while (words > max) { 443 const size_t cur = (words - max) >= min ? max : max - min; 444 fill_with_array(start, cur, zap); 445 start += cur; 446 words -= cur; 447 } 448 449 fill_with_object_impl(start, words, zap); 450 } 451 452 void CollectedHeap::fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) { 453 CollectedHeap::fill_with_object(start, end, zap); 454 } 455 456 size_t CollectedHeap::min_dummy_object_size() const { 457 return oopDesc::header_size(); 458 } 459 460 size_t CollectedHeap::tlab_alloc_reserve() const { 461 size_t min_size = min_dummy_object_size(); 462 return min_size > (size_t)MinObjAlignment ? align_object_size(min_size) : 0; 463 } 464 465 HeapWord* CollectedHeap::allocate_new_tlab(size_t min_size, 466 size_t requested_size, 467 size_t* actual_size) { 468 guarantee(false, "thread-local allocation buffers not supported"); 469 return NULL; 470 } 471 472 void CollectedHeap::ensure_parsability(bool retire_tlabs) { 473 assert(SafepointSynchronize::is_at_safepoint() || !is_init_completed(), 474 "Should only be called at a safepoint or at start-up"); 475 476 ThreadLocalAllocStats stats; 477 478 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next();) { 479 BarrierSet::barrier_set()->make_parsable(thread); 480 if (UseTLAB) { 481 if (retire_tlabs) { 482 thread->tlab().retire(&stats); 483 } else { 484 thread->tlab().make_parsable(); 485 } 486 } 487 } 488 489 stats.publish(); 490 } 491 492 void CollectedHeap::resize_all_tlabs() { 493 assert(SafepointSynchronize::is_at_safepoint() || !is_init_completed(), 494 "Should only resize tlabs at safepoint"); 495 496 if (UseTLAB && ResizeTLAB) { 497 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) { 498 thread->tlab().resize(); 499 } 500 } 501 } 502 503 jlong CollectedHeap::millis_since_last_whole_heap_examined() { 504 return (os::javaTimeNanos() - _last_whole_heap_examined_time_ns) / NANOSECS_PER_MILLISEC; 505 } 506 507 void CollectedHeap::record_whole_heap_examined_timestamp() { 508 _last_whole_heap_examined_time_ns = os::javaTimeNanos(); 509 } 510 511 void CollectedHeap::full_gc_dump(GCTimer* timer, bool before) { 512 assert(timer != NULL, "timer is null"); 513 if ((HeapDumpBeforeFullGC && before) || (HeapDumpAfterFullGC && !before)) { 514 GCTraceTime(Info, gc) tm(before ? "Heap Dump (before full gc)" : "Heap Dump (after full gc)", timer); 515 HeapDumper::dump_heap(); 516 } 517 518 LogTarget(Trace, gc, classhisto) lt; 519 if (lt.is_enabled()) { 520 GCTraceTime(Trace, gc, classhisto) tm(before ? "Class Histogram (before full gc)" : "Class Histogram (after full gc)", timer); 521 ResourceMark rm; 522 LogStream ls(lt); 523 VM_GC_HeapInspection inspector(&ls, false /* ! full gc */); 524 inspector.doit(); 525 } 526 } 527 528 void CollectedHeap::pre_full_gc_dump(GCTimer* timer) { 529 full_gc_dump(timer, true); 530 } 531 532 void CollectedHeap::post_full_gc_dump(GCTimer* timer) { 533 full_gc_dump(timer, false); 534 } 535 536 void CollectedHeap::initialize_reserved_region(const ReservedHeapSpace& rs) { 537 // It is important to do this in a way such that concurrent readers can't 538 // temporarily think something is in the heap. (Seen this happen in asserts.) 539 _reserved.set_word_size(0); 540 _reserved.set_start((HeapWord*)rs.base()); 541 _reserved.set_end((HeapWord*)rs.end()); 542 } 543 544 void CollectedHeap::post_initialize() { 545 initialize_serviceability(); 546 } 547 548 #ifndef PRODUCT 549 550 bool CollectedHeap::promotion_should_fail(volatile size_t* count) { 551 // Access to count is not atomic; the value does not have to be exact. 552 if (PromotionFailureALot) { 553 const size_t gc_num = total_collections(); 554 const size_t elapsed_gcs = gc_num - _promotion_failure_alot_gc_number; 555 if (elapsed_gcs >= PromotionFailureALotInterval) { 556 // Test for unsigned arithmetic wrap-around. 557 if (++*count >= PromotionFailureALotCount) { 558 *count = 0; 559 return true; 560 } 561 } 562 } 563 return false; 564 } 565 566 bool CollectedHeap::promotion_should_fail() { 567 return promotion_should_fail(&_promotion_failure_alot_count); 568 } 569 570 void CollectedHeap::reset_promotion_should_fail(volatile size_t* count) { 571 if (PromotionFailureALot) { 572 _promotion_failure_alot_gc_number = total_collections(); 573 *count = 0; 574 } 575 } 576 577 void CollectedHeap::reset_promotion_should_fail() { 578 reset_promotion_should_fail(&_promotion_failure_alot_count); 579 } 580 581 #endif // #ifndef PRODUCT 582 583 bool CollectedHeap::supports_object_pinning() const { 584 return false; 585 } 586 587 oop CollectedHeap::pin_object(JavaThread* thread, oop obj) { 588 ShouldNotReachHere(); 589 return NULL; 590 } 591 592 void CollectedHeap::unpin_object(JavaThread* thread, oop obj) { 593 ShouldNotReachHere(); 594 } 595 596 void CollectedHeap::deduplicate_string(oop str) { 597 // Do nothing, unless overridden in subclass. 598 } 599 600 uint32_t CollectedHeap::hash_oop(oop obj) const { 601 const uintptr_t addr = cast_from_oop<uintptr_t>(obj); 602 return static_cast<uint32_t>(addr >> LogMinObjAlignment); 603 }