1 /*
   2  * Copyright (c) 2001, 2018, 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.inline.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/gcWhen.hpp"
  36 #include "gc/shared/vmGCOperations.hpp"
  37 #include "logging/log.hpp"
  38 #include "memory/metaspace.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "oops/instanceMirrorKlass.hpp"
  41 #include "oops/oop.inline.hpp"
  42 #include "runtime/init.hpp"
  43 #include "runtime/thread.inline.hpp"
  44 #include "runtime/threadSMR.hpp"
  45 #include "services/heapDumper.hpp"
  46 #include "utilities/align.hpp"
  47 
  48 class ClassLoaderData;
  49 
  50 #ifdef ASSERT
  51 int CollectedHeap::_fire_out_of_memory_count = 0;
  52 #endif
  53 
  54 size_t CollectedHeap::_filler_array_max_size = 0;
  55 
  56 template <>
  57 void EventLogBase<GCMessage>::print(outputStream* st, GCMessage& m) {
  58   st->print_cr("GC heap %s", m.is_before ? "before" : "after");
  59   st->print_raw(m);
  60 }
  61 
  62 void GCHeapLog::log_heap(CollectedHeap* heap, bool before) {
  63   if (!should_log()) {
  64     return;
  65   }
  66 
  67   double timestamp = fetch_timestamp();
  68   MutexLockerEx ml(&_mutex, Mutex::_no_safepoint_check_flag);
  69   int index = compute_log_index();
  70   _records[index].thread = NULL; // Its the GC thread so it's not that interesting.
  71   _records[index].timestamp = timestamp;
  72   _records[index].data.is_before = before;
  73   stringStream st(_records[index].data.buffer(), _records[index].data.size());
  74 
  75   st.print_cr("{Heap %s GC invocations=%u (full %u):",
  76                  before ? "before" : "after",
  77                  heap->total_collections(),
  78                  heap->total_full_collections());
  79 
  80   heap->print_on(&st);
  81   st.print_cr("}");
  82 }
  83 
  84 VirtualSpaceSummary CollectedHeap::create_heap_space_summary() {
  85   size_t capacity_in_words = capacity() / HeapWordSize;
  86 
  87   return VirtualSpaceSummary(
  88     reserved_region().start(), reserved_region().start() + capacity_in_words, reserved_region().end());
  89 }
  90 
  91 GCHeapSummary CollectedHeap::create_heap_summary() {
  92   VirtualSpaceSummary heap_space = create_heap_space_summary();
  93   return GCHeapSummary(heap_space, used());
  94 }
  95 
  96 MetaspaceSummary CollectedHeap::create_metaspace_summary() {
  97   const MetaspaceSizes meta_space(
  98       MetaspaceAux::committed_bytes(),
  99       MetaspaceAux::used_bytes(),
 100       MetaspaceAux::reserved_bytes());
 101   const MetaspaceSizes data_space(
 102       MetaspaceAux::committed_bytes(Metaspace::NonClassType),
 103       MetaspaceAux::used_bytes(Metaspace::NonClassType),
 104       MetaspaceAux::reserved_bytes(Metaspace::NonClassType));
 105   const MetaspaceSizes class_space(
 106       MetaspaceAux::committed_bytes(Metaspace::ClassType),
 107       MetaspaceAux::used_bytes(Metaspace::ClassType),
 108       MetaspaceAux::reserved_bytes(Metaspace::ClassType));
 109 
 110   const MetaspaceChunkFreeListSummary& ms_chunk_free_list_summary =
 111     MetaspaceAux::chunk_free_list_summary(Metaspace::NonClassType);
 112   const MetaspaceChunkFreeListSummary& class_chunk_free_list_summary =
 113     MetaspaceAux::chunk_free_list_summary(Metaspace::ClassType);
 114 
 115   return MetaspaceSummary(MetaspaceGC::capacity_until_GC(), meta_space, data_space, class_space,
 116                           ms_chunk_free_list_summary, class_chunk_free_list_summary);
 117 }
 118 
 119 void CollectedHeap::print_heap_before_gc() {
 120   Universe::print_heap_before_gc();
 121   if (_gc_heap_log != NULL) {
 122     _gc_heap_log->log_heap_before(this);
 123   }
 124 }
 125 
 126 void CollectedHeap::print_heap_after_gc() {
 127   Universe::print_heap_after_gc();
 128   if (_gc_heap_log != NULL) {
 129     _gc_heap_log->log_heap_after(this);
 130   }
 131 }
 132 
 133 void CollectedHeap::print_on_error(outputStream* st) const {
 134   st->print_cr("Heap:");
 135   print_extended_on(st);
 136   st->cr();
 137 
 138   _barrier_set->print_on(st);
 139 }
 140 
 141 void CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
 142   const GCHeapSummary& heap_summary = create_heap_summary();
 143   gc_tracer->report_gc_heap_summary(when, heap_summary);
 144 
 145   const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
 146   gc_tracer->report_metaspace_summary(when, metaspace_summary);
 147 }
 148 
 149 void CollectedHeap::trace_heap_before_gc(const GCTracer* gc_tracer) {
 150   trace_heap(GCWhen::BeforeGC, gc_tracer);
 151 }
 152 
 153 void CollectedHeap::trace_heap_after_gc(const GCTracer* gc_tracer) {
 154   trace_heap(GCWhen::AfterGC, gc_tracer);
 155 }
 156 
 157 // WhiteBox API support for concurrent collectors.  These are the
 158 // default implementations, for collectors which don't support this
 159 // feature.
 160 bool CollectedHeap::supports_concurrent_phase_control() const {
 161   return false;
 162 }
 163 
 164 const char* const* CollectedHeap::concurrent_phases() const {
 165   static const char* const result[] = { NULL };
 166   return result;
 167 }
 168 
 169 bool CollectedHeap::request_concurrent_phase(const char* phase) {
 170   return false;
 171 }
 172 
 173 // Memory state functions.
 174 
 175 
 176 CollectedHeap::CollectedHeap() :
 177   _barrier_set(NULL),
 178   _is_gc_active(false),
 179   _total_collections(0),
 180   _total_full_collections(0),
 181   _gc_cause(GCCause::_no_gc),
 182   _gc_lastcause(GCCause::_no_gc)
 183 {
 184   const size_t max_len = size_t(arrayOopDesc::max_array_length(T_INT));
 185   const size_t elements_per_word = HeapWordSize / sizeof(jint);
 186   _filler_array_max_size = align_object_size(filler_array_hdr_size() +
 187                                              max_len / elements_per_word);
 188 
 189   NOT_PRODUCT(_promotion_failure_alot_count = 0;)
 190   NOT_PRODUCT(_promotion_failure_alot_gc_number = 0;)
 191 
 192   if (UsePerfData) {
 193     EXCEPTION_MARK;
 194 
 195     // create the gc cause jvmstat counters
 196     _perf_gc_cause = PerfDataManager::create_string_variable(SUN_GC, "cause",
 197                              80, GCCause::to_string(_gc_cause), CHECK);
 198 
 199     _perf_gc_lastcause =
 200                 PerfDataManager::create_string_variable(SUN_GC, "lastCause",
 201                              80, GCCause::to_string(_gc_lastcause), CHECK);
 202   }
 203 
 204   // Create the ring log
 205   if (LogEvents) {
 206     _gc_heap_log = new GCHeapLog();
 207   } else {
 208     _gc_heap_log = NULL;
 209   }
 210 }
 211 
 212 // This interface assumes that it's being called by the
 213 // vm thread. It collects the heap assuming that the
 214 // heap lock is already held and that we are executing in
 215 // the context of the vm thread.
 216 void CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
 217   assert(Thread::current()->is_VM_thread(), "Precondition#1");
 218   assert(Heap_lock->is_locked(), "Precondition#2");
 219   GCCauseSetter gcs(this, cause);
 220   switch (cause) {
 221     case GCCause::_heap_inspection:
 222     case GCCause::_heap_dump:
 223     case GCCause::_metadata_GC_threshold : {
 224       HandleMark hm;
 225       do_full_collection(false);        // don't clear all soft refs
 226       break;
 227     }
 228     case GCCause::_metadata_GC_clear_soft_refs: {
 229       HandleMark hm;
 230       do_full_collection(true);         // do clear all soft refs
 231       break;
 232     }
 233     default:
 234       ShouldNotReachHere(); // Unexpected use of this function
 235   }
 236 }
 237 
 238 MetaWord* CollectedHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
 239                                                             size_t word_size,
 240                                                             Metaspace::MetadataType mdtype) {
 241   return MetaspaceGC::satisfy_failed_metadata_allocation(loader_data, word_size, mdtype);
 242 }
 243 
 244 void CollectedHeap::set_barrier_set(BarrierSet* barrier_set) {
 245   _barrier_set = barrier_set;
 246   BarrierSet::set_bs(barrier_set);
 247 }
 248 
 249 #ifndef PRODUCT
 250 void CollectedHeap::check_for_bad_heap_word_value(HeapWord* addr, size_t size) {
 251   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 252     for (size_t slot = 0; slot < size; slot += 1) {
 253       assert((*(intptr_t*) (addr + slot)) != ((intptr_t) badHeapWordVal),
 254              "Found badHeapWordValue in post-allocation check");
 255     }
 256   }
 257 }
 258 
 259 void CollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr, size_t size) {
 260   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 261     for (size_t slot = 0; slot < size; slot += 1) {
 262       assert((*(intptr_t*) (addr + slot)) == ((intptr_t) badHeapWordVal),
 263              "Found non badHeapWordValue in pre-allocation check");
 264     }
 265   }
 266 }
 267 #endif // PRODUCT
 268 
 269 #ifdef ASSERT
 270 void CollectedHeap::check_for_valid_allocation_state() {
 271   Thread *thread = Thread::current();
 272   // How to choose between a pending exception and a potential
 273   // OutOfMemoryError?  Don't allow pending exceptions.
 274   // This is a VM policy failure, so how do we exhaustively test it?
 275   assert(!thread->has_pending_exception(),
 276          "shouldn't be allocating with pending exception");
 277   if (StrictSafepointChecks) {
 278     assert(thread->allow_allocation(),
 279            "Allocation done by thread for which allocation is blocked "
 280            "by No_Allocation_Verifier!");
 281     // Allocation of an oop can always invoke a safepoint,
 282     // hence, the true argument
 283     thread->check_for_valid_safepoint_state(true);
 284   }
 285 }
 286 #endif
 287 
 288 HeapWord* CollectedHeap::allocate_from_tlab_slow(Klass* klass, Thread* thread, size_t size) {
 289 
 290   // Retain tlab and allocate object in shared space if
 291   // the amount free in the tlab is too large to discard.
 292   if (thread->tlab().free() > thread->tlab().refill_waste_limit()) {
 293     thread->tlab().record_slow_allocation(size);
 294     return NULL;
 295   }
 296 
 297   // Discard tlab and allocate a new one.
 298   // To minimize fragmentation, the last TLAB may be smaller than the rest.
 299   size_t new_tlab_size = thread->tlab().compute_size(size);
 300 
 301   thread->tlab().clear_before_allocation();
 302 
 303   if (new_tlab_size == 0) {
 304     return NULL;
 305   }
 306 
 307   // Allocate a new TLAB...
 308   HeapWord* obj = Universe::heap()->allocate_new_tlab(new_tlab_size);
 309   if (obj == NULL) {
 310     return NULL;
 311   }
 312 
 313   AllocTracer::send_allocation_in_new_tlab(klass, obj, new_tlab_size * HeapWordSize, size * HeapWordSize, thread);
 314 
 315   if (ZeroTLAB) {
 316     // ..and clear it.
 317     Copy::zero_to_words(obj, new_tlab_size);
 318   } else {
 319     // ...and zap just allocated object.
 320 #ifdef ASSERT
 321     // Skip mangling the space corresponding to the object header to
 322     // ensure that the returned space is not considered parsable by
 323     // any concurrent GC thread.
 324     size_t hdr_size = oopDesc::header_size();
 325     Copy::fill_to_words(obj + hdr_size, new_tlab_size - hdr_size, badHeapWordVal);
 326 #endif // ASSERT
 327   }
 328   thread->tlab().fill(obj, obj + size, new_tlab_size);
 329   return obj;
 330 }
 331 
 332 size_t CollectedHeap::max_tlab_size() const {
 333   // TLABs can't be bigger than we can fill with a int[Integer.MAX_VALUE].
 334   // This restriction could be removed by enabling filling with multiple arrays.
 335   // If we compute that the reasonable way as
 336   //    header_size + ((sizeof(jint) * max_jint) / HeapWordSize)
 337   // we'll overflow on the multiply, so we do the divide first.
 338   // We actually lose a little by dividing first,
 339   // but that just makes the TLAB  somewhat smaller than the biggest array,
 340   // which is fine, since we'll be able to fill that.
 341   size_t max_int_size = typeArrayOopDesc::header_size(T_INT) +
 342               sizeof(jint) *
 343               ((juint) max_jint / (size_t) HeapWordSize);
 344   return align_down(max_int_size, MinObjAlignment);
 345 }
 346 
 347 size_t CollectedHeap::filler_array_hdr_size() {
 348   return align_object_offset(arrayOopDesc::header_size(T_INT)); // align to Long
 349 }
 350 
 351 size_t CollectedHeap::filler_array_min_size() {
 352   return align_object_size(filler_array_hdr_size()); // align to MinObjAlignment
 353 }
 354 
 355 #ifdef ASSERT
 356 void CollectedHeap::fill_args_check(HeapWord* start, size_t words)
 357 {
 358   assert(words >= min_fill_size(), "too small to fill");
 359   assert(is_object_aligned(words), "unaligned size");
 360   assert(Universe::heap()->is_in_reserved(start), "not in heap");
 361   assert(Universe::heap()->is_in_reserved(start + words - 1), "not in heap");
 362 }
 363 
 364 void CollectedHeap::zap_filler_array(HeapWord* start, size_t words, bool zap)
 365 {
 366   if (ZapFillerObjects && zap) {
 367     Copy::fill_to_words(start + filler_array_hdr_size(),
 368                         words - filler_array_hdr_size(), 0XDEAFBABE);
 369   }
 370 }
 371 #endif // ASSERT
 372 
 373 void
 374 CollectedHeap::fill_with_array(HeapWord* start, size_t words, bool zap)
 375 {
 376   assert(words >= filler_array_min_size(), "too small for an array");
 377   assert(words <= filler_array_max_size(), "too big for a single object");
 378 
 379   const size_t payload_size = words - filler_array_hdr_size();
 380   const size_t len = payload_size * HeapWordSize / sizeof(jint);
 381   assert((int)len >= 0, "size too large " SIZE_FORMAT " becomes %d", words, (int)len);
 382 
 383   // Set the length first for concurrent GC.
 384   ((arrayOop)start)->set_length((int)len);
 385   post_allocation_setup_common(Universe::intArrayKlassObj(), start);
 386   DEBUG_ONLY(zap_filler_array(start, words, zap);)
 387 }
 388 
 389 void
 390 CollectedHeap::fill_with_object_impl(HeapWord* start, size_t words, bool zap)
 391 {
 392   assert(words <= filler_array_max_size(), "too big for a single object");
 393 
 394   if (words >= filler_array_min_size()) {
 395     fill_with_array(start, words, zap);
 396   } else if (words > 0) {
 397     assert(words == min_fill_size(), "unaligned size");
 398     post_allocation_setup_common(SystemDictionary::Object_klass(), start);
 399   }
 400 }
 401 
 402 void CollectedHeap::fill_with_object(HeapWord* start, size_t words, bool zap)
 403 {
 404   DEBUG_ONLY(fill_args_check(start, words);)
 405   HandleMark hm;  // Free handles before leaving.
 406   fill_with_object_impl(start, words, zap);
 407 }
 408 
 409 void CollectedHeap::fill_with_objects(HeapWord* start, size_t words, bool zap)
 410 {
 411   DEBUG_ONLY(fill_args_check(start, words);)
 412   HandleMark hm;  // Free handles before leaving.
 413 
 414   // Multiple objects may be required depending on the filler array maximum size. Fill
 415   // the range up to that with objects that are filler_array_max_size sized. The
 416   // remainder is filled with a single object.
 417   const size_t min = min_fill_size();
 418   const size_t max = filler_array_max_size();
 419   while (words > max) {
 420     const size_t cur = (words - max) >= min ? max : max - min;
 421     fill_with_array(start, cur, zap);
 422     start += cur;
 423     words -= cur;
 424   }
 425 
 426   fill_with_object_impl(start, words, zap);
 427 }
 428 
 429 HeapWord* CollectedHeap::allocate_new_tlab(size_t size) {
 430   guarantee(false, "thread-local allocation buffers not supported");
 431   return NULL;
 432 }
 433 
 434 void CollectedHeap::ensure_parsability(bool retire_tlabs) {
 435   // The second disjunct in the assertion below makes a concession
 436   // for the start-up verification done while the VM is being
 437   // created. Callers be careful that you know that mutators
 438   // aren't going to interfere -- for instance, this is permissible
 439   // if we are still single-threaded and have either not yet
 440   // started allocating (nothing much to verify) or we have
 441   // started allocating but are now a full-fledged JavaThread
 442   // (and have thus made our TLAB's) available for filling.
 443   assert(SafepointSynchronize::is_at_safepoint() ||
 444          !is_init_completed(),
 445          "Should only be called at a safepoint or at start-up"
 446          " otherwise concurrent mutator activity may make heap "
 447          " unparsable again");
 448   const bool use_tlab = UseTLAB;
 449   // The main thread starts allocating via a TLAB even before it
 450   // has added itself to the threads list at vm boot-up.
 451   JavaThreadIteratorWithHandle jtiwh;
 452   assert(!use_tlab || jtiwh.length() > 0,
 453          "Attempt to fill tlabs before main thread has been added"
 454          " to threads list is doomed to failure!");
 455   BarrierSet *bs = barrier_set();
 456   for (; JavaThread *thread = jtiwh.next(); ) {
 457      if (use_tlab) thread->tlab().make_parsable(retire_tlabs);
 458      bs->make_parsable(thread);
 459   }
 460 }
 461 
 462 void CollectedHeap::accumulate_statistics_all_tlabs() {
 463   if (UseTLAB) {
 464     assert(SafepointSynchronize::is_at_safepoint() ||
 465          !is_init_completed(),
 466          "should only accumulate statistics on tlabs at safepoint");
 467 
 468     ThreadLocalAllocBuffer::accumulate_statistics_before_gc();
 469   }
 470 }
 471 
 472 void CollectedHeap::resize_all_tlabs() {
 473   if (UseTLAB) {
 474     assert(SafepointSynchronize::is_at_safepoint() ||
 475          !is_init_completed(),
 476          "should only resize tlabs at safepoint");
 477 
 478     ThreadLocalAllocBuffer::resize_all_tlabs();
 479   }
 480 }
 481 
 482 void CollectedHeap::full_gc_dump(GCTimer* timer, bool before) {
 483   assert(timer != NULL, "timer is null");
 484   if ((HeapDumpBeforeFullGC && before) || (HeapDumpAfterFullGC && !before)) {
 485     GCTraceTime(Info, gc) tm(before ? "Heap Dump (before full gc)" : "Heap Dump (after full gc)", timer);
 486     HeapDumper::dump_heap();
 487   }
 488 
 489   LogTarget(Trace, gc, classhisto) lt;
 490   if (lt.is_enabled()) {
 491     GCTraceTime(Trace, gc, classhisto) tm(before ? "Class Histogram (before full gc)" : "Class Histogram (after full gc)", timer);
 492     ResourceMark rm;
 493     LogStream ls(lt);
 494     VM_GC_HeapInspection inspector(&ls, false /* ! full gc */);
 495     inspector.doit();
 496   }
 497 }
 498 
 499 void CollectedHeap::pre_full_gc_dump(GCTimer* timer) {
 500   full_gc_dump(timer, true);
 501 }
 502 
 503 void CollectedHeap::post_full_gc_dump(GCTimer* timer) {
 504   full_gc_dump(timer, false);
 505 }
 506 
 507 void CollectedHeap::initialize_reserved_region(HeapWord *start, HeapWord *end) {
 508   // It is important to do this in a way such that concurrent readers can't
 509   // temporarily think something is in the heap.  (Seen this happen in asserts.)
 510   _reserved.set_word_size(0);
 511   _reserved.set_start(start);
 512   _reserved.set_end(end);
 513 }
 514 
 515 void CollectedHeap::post_initialize() {
 516   initialize_serviceability();
 517 }