1 /*
   2  * Copyright (c) 2001, 2015, 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/gcHeapSummary.hpp"
  32 #include "gc/shared/gcTrace.hpp"
  33 #include "gc/shared/gcTraceTime.hpp"
  34 #include "gc/shared/gcWhen.hpp"
  35 #include "gc/shared/vmGCOperations.hpp"
  36 #include "memory/metaspace.hpp"
  37 #include "oops/instanceMirrorKlass.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "runtime/init.hpp"
  40 #include "runtime/thread.inline.hpp"
  41 #include "services/heapDumper.hpp"
  42 
  43 
  44 #ifdef ASSERT
  45 int CollectedHeap::_fire_out_of_memory_count = 0;
  46 #endif
  47 
  48 size_t CollectedHeap::_filler_array_max_size = 0;
  49 
  50 template <>
  51 void EventLogBase<GCMessage>::print(outputStream* st, GCMessage& m) {
  52   st->print_cr("GC heap %s", m.is_before ? "before" : "after");
  53   st->print_raw(m);
  54 }
  55 
  56 void GCHeapLog::log_heap(bool before) {
  57   if (!should_log()) {
  58     return;
  59   }
  60 
  61   double timestamp = fetch_timestamp();
  62   MutexLockerEx ml(&_mutex, Mutex::_no_safepoint_check_flag);
  63   int index = compute_log_index();
  64   _records[index].thread = NULL; // Its the GC thread so it's not that interesting.
  65   _records[index].timestamp = timestamp;
  66   _records[index].data.is_before = before;
  67   stringStream st(_records[index].data.buffer(), _records[index].data.size());
  68   if (before) {
  69     Universe::print_heap_before_gc(&st, true);
  70   } else {
  71     Universe::print_heap_after_gc(&st, true);
  72   }
  73 }
  74 
  75 VirtualSpaceSummary CollectedHeap::create_heap_space_summary() {
  76   size_t capacity_in_words = capacity() / HeapWordSize;
  77 
  78   return VirtualSpaceSummary(
  79     reserved_region().start(), reserved_region().start() + capacity_in_words, reserved_region().end());
  80 }
  81 
  82 GCHeapSummary CollectedHeap::create_heap_summary() {
  83   VirtualSpaceSummary heap_space = create_heap_space_summary();
  84   return GCHeapSummary(heap_space, used());
  85 }
  86 
  87 MetaspaceSummary CollectedHeap::create_metaspace_summary() {
  88   const MetaspaceSizes meta_space(
  89       MetaspaceAux::committed_bytes(),
  90       MetaspaceAux::used_bytes(),
  91       MetaspaceAux::reserved_bytes());
  92   const MetaspaceSizes data_space(
  93       MetaspaceAux::committed_bytes(Metaspace::NonClassType),
  94       MetaspaceAux::used_bytes(Metaspace::NonClassType),
  95       MetaspaceAux::reserved_bytes(Metaspace::NonClassType));
  96   const MetaspaceSizes class_space(
  97       MetaspaceAux::committed_bytes(Metaspace::ClassType),
  98       MetaspaceAux::used_bytes(Metaspace::ClassType),
  99       MetaspaceAux::reserved_bytes(Metaspace::ClassType));
 100 
 101   const MetaspaceChunkFreeListSummary& ms_chunk_free_list_summary =
 102     MetaspaceAux::chunk_free_list_summary(Metaspace::NonClassType);
 103   const MetaspaceChunkFreeListSummary& class_chunk_free_list_summary =
 104     MetaspaceAux::chunk_free_list_summary(Metaspace::ClassType);
 105 
 106   return MetaspaceSummary(MetaspaceGC::capacity_until_GC(), meta_space, data_space, class_space,
 107                           ms_chunk_free_list_summary, class_chunk_free_list_summary);
 108 }
 109 
 110 void CollectedHeap::print_heap_before_gc() {
 111   if (PrintHeapAtGC) {
 112     Universe::print_heap_before_gc();
 113   }
 114   if (_gc_heap_log != NULL) {
 115     _gc_heap_log->log_heap_before();
 116   }
 117 }
 118 
 119 void CollectedHeap::print_heap_after_gc() {
 120   if (PrintHeapAtGC) {
 121     Universe::print_heap_after_gc();
 122   }
 123   if (_gc_heap_log != NULL) {
 124     _gc_heap_log->log_heap_after();
 125   }
 126 }
 127 
 128 void CollectedHeap::print_on_error(outputStream* st) const {
 129   st->print_cr("Heap:");
 130   print_extended_on(st);
 131   st->cr();
 132 
 133   _barrier_set->print_on(st);
 134 }
 135 
 136 void CollectedHeap::register_nmethod(nmethod* nm) {
 137   assert_locked_or_safepoint(CodeCache_lock);
 138 }
 139 
 140 void CollectedHeap::unregister_nmethod(nmethod* nm) {
 141   assert_locked_or_safepoint(CodeCache_lock);
 142 }
 143 
 144 void CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
 145   const GCHeapSummary& heap_summary = create_heap_summary();
 146   gc_tracer->report_gc_heap_summary(when, heap_summary);
 147 
 148   const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
 149   gc_tracer->report_metaspace_summary(when, metaspace_summary);
 150 }
 151 
 152 void CollectedHeap::trace_heap_before_gc(const GCTracer* gc_tracer) {
 153   trace_heap(GCWhen::BeforeGC, gc_tracer);
 154 }
 155 
 156 void CollectedHeap::trace_heap_after_gc(const GCTracer* gc_tracer) {
 157   trace_heap(GCWhen::AfterGC, gc_tracer);
 158 }
 159 
 160 // Memory state functions.
 161 
 162 
 163 CollectedHeap::CollectedHeap() {
 164   const size_t max_len = size_t(arrayOopDesc::max_array_length(T_INT));
 165   const size_t elements_per_word = HeapWordSize / sizeof(jint);
 166   _filler_array_max_size = align_object_size(filler_array_hdr_size() +
 167                                              max_len / elements_per_word);
 168 
 169   _barrier_set = NULL;
 170   _is_gc_active = false;
 171   _total_collections = _total_full_collections = 0;
 172   _gc_cause = _gc_lastcause = GCCause::_no_gc;
 173   NOT_PRODUCT(_promotion_failure_alot_count = 0;)
 174   NOT_PRODUCT(_promotion_failure_alot_gc_number = 0;)
 175 
 176   if (UsePerfData) {
 177     EXCEPTION_MARK;
 178 
 179     // create the gc cause jvmstat counters
 180     _perf_gc_cause = PerfDataManager::create_string_variable(SUN_GC, "cause",
 181                              80, GCCause::to_string(_gc_cause), CHECK);
 182 
 183     _perf_gc_lastcause =
 184                 PerfDataManager::create_string_variable(SUN_GC, "lastCause",
 185                              80, GCCause::to_string(_gc_lastcause), CHECK);
 186   }
 187   _defer_initial_card_mark = false; // strengthened by subclass in pre_initialize() below.
 188   // Create the ring log
 189   if (LogEvents) {
 190     _gc_heap_log = new GCHeapLog();
 191   } else {
 192     _gc_heap_log = NULL;
 193   }
 194 }
 195 
 196 // This interface assumes that it's being called by the
 197 // vm thread. It collects the heap assuming that the
 198 // heap lock is already held and that we are executing in
 199 // the context of the vm thread.
 200 void CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
 201   assert(Thread::current()->is_VM_thread(), "Precondition#1");
 202   assert(Heap_lock->is_locked(), "Precondition#2");
 203   GCCauseSetter gcs(this, cause);
 204   switch (cause) {
 205     case GCCause::_heap_inspection:
 206     case GCCause::_heap_dump:
 207     case GCCause::_metadata_GC_threshold : {
 208       HandleMark hm;
 209       do_full_collection(false);        // don't clear all soft refs
 210       break;
 211     }
 212     case GCCause::_last_ditch_collection: {
 213       HandleMark hm;
 214       do_full_collection(true);         // do clear all soft refs
 215       break;
 216     }
 217     default:
 218       ShouldNotReachHere(); // Unexpected use of this function
 219   }
 220 }
 221 
 222 void CollectedHeap::set_barrier_set(BarrierSet* barrier_set) {
 223   _barrier_set = barrier_set;
 224   oopDesc::set_bs(_barrier_set);
 225 }
 226 
 227 void CollectedHeap::pre_initialize() {
 228   // Used for ReduceInitialCardMarks (when COMPILER2 is used);
 229   // otherwise remains unused.
 230 #ifdef COMPILER2
 231   _defer_initial_card_mark =    ReduceInitialCardMarks && can_elide_tlab_store_barriers()
 232                              && (DeferInitialCardMark || card_mark_must_follow_store());
 233 #else
 234   assert(_defer_initial_card_mark == false, "Who would set it?");
 235 #endif
 236 }
 237 
 238 #ifndef PRODUCT
 239 void CollectedHeap::check_for_bad_heap_word_value(HeapWord* addr, size_t size) {
 240   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 241     for (size_t slot = 0; slot < size; slot += 1) {
 242       assert((*(intptr_t*) (addr + slot)) != ((intptr_t) badHeapWordVal),
 243              "Found badHeapWordValue in post-allocation check");
 244     }
 245   }
 246 }
 247 
 248 void CollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr, size_t size) {
 249   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 250     for (size_t slot = 0; slot < size; slot += 1) {
 251       assert((*(intptr_t*) (addr + slot)) == ((intptr_t) badHeapWordVal),
 252              "Found non badHeapWordValue in pre-allocation check");
 253     }
 254   }
 255 }
 256 #endif // PRODUCT
 257 
 258 #ifdef ASSERT
 259 void CollectedHeap::check_for_valid_allocation_state() {
 260   Thread *thread = Thread::current();
 261   // How to choose between a pending exception and a potential
 262   // OutOfMemoryError?  Don't allow pending exceptions.
 263   // This is a VM policy failure, so how do we exhaustively test it?
 264   assert(!thread->has_pending_exception(),
 265          "shouldn't be allocating with pending exception");
 266   if (StrictSafepointChecks) {
 267     assert(thread->allow_allocation(),
 268            "Allocation done by thread for which allocation is blocked "
 269            "by No_Allocation_Verifier!");
 270     // Allocation of an oop can always invoke a safepoint,
 271     // hence, the true argument
 272     thread->check_for_valid_safepoint_state(true);
 273   }
 274 }
 275 #endif
 276 
 277 HeapWord* CollectedHeap::allocate_from_tlab_slow(KlassHandle klass, Thread* thread, size_t size) {
 278 
 279   // Retain tlab and allocate object in shared space if
 280   // the amount free in the tlab is too large to discard.
 281   if (thread->tlab().free() > thread->tlab().refill_waste_limit()) {
 282     thread->tlab().record_slow_allocation(size);
 283     return NULL;
 284   }
 285 
 286   // Discard tlab and allocate a new one.
 287   // To minimize fragmentation, the last TLAB may be smaller than the rest.
 288   size_t new_tlab_size = thread->tlab().compute_size(size);
 289 
 290   thread->tlab().clear_before_allocation();
 291 
 292   if (new_tlab_size == 0) {
 293     return NULL;
 294   }
 295 
 296   // Allocate a new TLAB...
 297   HeapWord* obj = Universe::heap()->allocate_new_tlab(new_tlab_size);
 298   if (obj == NULL) {
 299     return NULL;
 300   }
 301 
 302   AllocTracer::send_allocation_in_new_tlab_event(klass, new_tlab_size * HeapWordSize, size * HeapWordSize);
 303 
 304   if (ZeroTLAB) {
 305     // ..and clear it.
 306     Copy::zero_to_words(obj, new_tlab_size);
 307   } else {
 308     // ...and zap just allocated object.
 309 #ifdef ASSERT
 310     // Skip mangling the space corresponding to the object header to
 311     // ensure that the returned space is not considered parsable by
 312     // any concurrent GC thread.
 313     size_t hdr_size = oopDesc::header_size();
 314     Copy::fill_to_words(obj + hdr_size, new_tlab_size - hdr_size, badHeapWordVal);
 315 #endif // ASSERT
 316   }
 317   thread->tlab().fill(obj, obj + size, new_tlab_size);
 318   return obj;
 319 }
 320 
 321 void CollectedHeap::flush_deferred_store_barrier(JavaThread* thread) {
 322   MemRegion deferred = thread->deferred_card_mark();
 323   if (!deferred.is_empty()) {
 324     assert(_defer_initial_card_mark, "Otherwise should be empty");
 325     {
 326       // Verify that the storage points to a parsable object in heap
 327       DEBUG_ONLY(oop old_obj = oop(deferred.start());)
 328       assert(is_in(old_obj), "Not in allocated heap");
 329       assert(!can_elide_initializing_store_barrier(old_obj),
 330              "Else should have been filtered in new_store_pre_barrier()");
 331       assert(old_obj->is_oop(true), "Not an oop");
 332       assert(deferred.word_size() == (size_t)(old_obj->size()),
 333              "Mismatch: multiple objects?");
 334     }
 335     BarrierSet* bs = barrier_set();
 336     assert(bs->has_write_region_opt(), "No write_region() on BarrierSet");
 337     bs->write_region(deferred);
 338     // "Clear" the deferred_card_mark field
 339     thread->set_deferred_card_mark(MemRegion());
 340   }
 341   assert(thread->deferred_card_mark().is_empty(), "invariant");
 342 }
 343 
 344 size_t CollectedHeap::max_tlab_size() const {
 345   // TLABs can't be bigger than we can fill with a int[Integer.MAX_VALUE].
 346   // This restriction could be removed by enabling filling with multiple arrays.
 347   // If we compute that the reasonable way as
 348   //    header_size + ((sizeof(jint) * max_jint) / HeapWordSize)
 349   // we'll overflow on the multiply, so we do the divide first.
 350   // We actually lose a little by dividing first,
 351   // but that just makes the TLAB  somewhat smaller than the biggest array,
 352   // which is fine, since we'll be able to fill that.
 353   size_t max_int_size = typeArrayOopDesc::header_size(T_INT) +
 354               sizeof(jint) *
 355               ((juint) max_jint / (size_t) HeapWordSize);
 356   return align_size_down(max_int_size, MinObjAlignment);
 357 }
 358 
 359 // Helper for ReduceInitialCardMarks. For performance,
 360 // compiled code may elide card-marks for initializing stores
 361 // to a newly allocated object along the fast-path. We
 362 // compensate for such elided card-marks as follows:
 363 // (a) Generational, non-concurrent collectors, such as
 364 //     GenCollectedHeap(ParNew,DefNew,Tenured) and
 365 //     ParallelScavengeHeap(ParallelGC, ParallelOldGC)
 366 //     need the card-mark if and only if the region is
 367 //     in the old gen, and do not care if the card-mark
 368 //     succeeds or precedes the initializing stores themselves,
 369 //     so long as the card-mark is completed before the next
 370 //     scavenge. For all these cases, we can do a card mark
 371 //     at the point at which we do a slow path allocation
 372 //     in the old gen, i.e. in this call.
 373 // (b) GenCollectedHeap(ConcurrentMarkSweepGeneration) requires
 374 //     in addition that the card-mark for an old gen allocated
 375 //     object strictly follow any associated initializing stores.
 376 //     In these cases, the memRegion remembered below is
 377 //     used to card-mark the entire region either just before the next
 378 //     slow-path allocation by this thread or just before the next scavenge or
 379 //     CMS-associated safepoint, whichever of these events happens first.
 380 //     (The implicit assumption is that the object has been fully
 381 //     initialized by this point, a fact that we assert when doing the
 382 //     card-mark.)
 383 // (c) G1CollectedHeap(G1) uses two kinds of write barriers. When a
 384 //     G1 concurrent marking is in progress an SATB (pre-write-)barrier is
 385 //     is used to remember the pre-value of any store. Initializing
 386 //     stores will not need this barrier, so we need not worry about
 387 //     compensating for the missing pre-barrier here. Turning now
 388 //     to the post-barrier, we note that G1 needs a RS update barrier
 389 //     which simply enqueues a (sequence of) dirty cards which may
 390 //     optionally be refined by the concurrent update threads. Note
 391 //     that this barrier need only be applied to a non-young write,
 392 //     but, like in CMS, because of the presence of concurrent refinement
 393 //     (much like CMS' precleaning), must strictly follow the oop-store.
 394 //     Thus, using the same protocol for maintaining the intended
 395 //     invariants turns out, serendepitously, to be the same for both
 396 //     G1 and CMS.
 397 //
 398 // For any future collector, this code should be reexamined with
 399 // that specific collector in mind, and the documentation above suitably
 400 // extended and updated.
 401 oop CollectedHeap::new_store_pre_barrier(JavaThread* thread, oop new_obj) {
 402   // If a previous card-mark was deferred, flush it now.
 403   flush_deferred_store_barrier(thread);
 404   if (can_elide_initializing_store_barrier(new_obj)) {
 405     // The deferred_card_mark region should be empty
 406     // following the flush above.
 407     assert(thread->deferred_card_mark().is_empty(), "Error");
 408   } else {
 409     MemRegion mr((HeapWord*)new_obj, new_obj->size());
 410     assert(!mr.is_empty(), "Error");
 411     if (_defer_initial_card_mark) {
 412       // Defer the card mark
 413       thread->set_deferred_card_mark(mr);
 414     } else {
 415       // Do the card mark
 416       BarrierSet* bs = barrier_set();
 417       assert(bs->has_write_region_opt(), "No write_region() on BarrierSet");
 418       bs->write_region(mr);
 419     }
 420   }
 421   return new_obj;
 422 }
 423 
 424 size_t CollectedHeap::filler_array_hdr_size() {
 425   return size_t(align_object_offset(arrayOopDesc::header_size(T_INT))); // align to Long
 426 }
 427 
 428 size_t CollectedHeap::filler_array_min_size() {
 429   return align_object_size(filler_array_hdr_size()); // align to MinObjAlignment
 430 }
 431 
 432 #ifdef ASSERT
 433 void CollectedHeap::fill_args_check(HeapWord* start, size_t words)
 434 {
 435   assert(words >= min_fill_size(), "too small to fill");
 436   assert(words % MinObjAlignment == 0, "unaligned size");
 437   assert(Universe::heap()->is_in_reserved(start), "not in heap");
 438   assert(Universe::heap()->is_in_reserved(start + words - 1), "not in heap");
 439 }
 440 
 441 void CollectedHeap::zap_filler_array(HeapWord* start, size_t words, bool zap)
 442 {
 443   if (ZapFillerObjects && zap) {
 444     Copy::fill_to_words(start + filler_array_hdr_size(),
 445                         words - filler_array_hdr_size(), 0XDEAFBABE);
 446   }
 447 }
 448 #endif // ASSERT
 449 
 450 void
 451 CollectedHeap::fill_with_array(HeapWord* start, size_t words, bool zap)
 452 {
 453   assert(words >= filler_array_min_size(), "too small for an array");
 454   assert(words <= filler_array_max_size(), "too big for a single object");
 455 
 456   const size_t payload_size = words - filler_array_hdr_size();
 457   const size_t len = payload_size * HeapWordSize / sizeof(jint);
 458   assert((int)len >= 0, err_msg("size too large " SIZE_FORMAT " becomes %d", words, (int)len));
 459 
 460   // Set the length first for concurrent GC.
 461   ((arrayOop)start)->set_length((int)len);
 462   post_allocation_setup_common(Universe::intArrayKlassObj(), start);
 463   DEBUG_ONLY(zap_filler_array(start, words, zap);)
 464 }
 465 
 466 void
 467 CollectedHeap::fill_with_object_impl(HeapWord* start, size_t words, bool zap)
 468 {
 469   assert(words <= filler_array_max_size(), "too big for a single object");
 470 
 471   if (words >= filler_array_min_size()) {
 472     fill_with_array(start, words, zap);
 473   } else if (words > 0) {
 474     assert(words == min_fill_size(), "unaligned size");
 475     post_allocation_setup_common(SystemDictionary::Object_klass(), start);
 476   }
 477 }
 478 
 479 void CollectedHeap::fill_with_object(HeapWord* start, size_t words, bool zap)
 480 {
 481   DEBUG_ONLY(fill_args_check(start, words);)
 482   HandleMark hm;  // Free handles before leaving.
 483   fill_with_object_impl(start, words, zap);
 484 }
 485 
 486 void CollectedHeap::fill_with_objects(HeapWord* start, size_t words, bool zap)
 487 {
 488   DEBUG_ONLY(fill_args_check(start, words);)
 489   HandleMark hm;  // Free handles before leaving.
 490 
 491   // Multiple objects may be required depending on the filler array maximum size. Fill
 492   // the range up to that with objects that are filler_array_max_size sized. The
 493   // remainder is filled with a single object.
 494   const size_t min = min_fill_size();
 495   const size_t max = filler_array_max_size();
 496   while (words > max) {
 497     const size_t cur = (words - max) >= min ? max : max - min;
 498     fill_with_array(start, cur, zap);
 499     start += cur;
 500     words -= cur;
 501   }
 502 
 503   fill_with_object_impl(start, words, zap);
 504 }
 505 
 506 void CollectedHeap::post_initialize() {
 507   collector_policy()->post_heap_initialize();
 508 }
 509 
 510 HeapWord* CollectedHeap::allocate_new_tlab(size_t size) {
 511   guarantee(false, "thread-local allocation buffers not supported");
 512   return NULL;
 513 }
 514 
 515 void CollectedHeap::ensure_parsability(bool retire_tlabs) {
 516   // The second disjunct in the assertion below makes a concession
 517   // for the start-up verification done while the VM is being
 518   // created. Callers be careful that you know that mutators
 519   // aren't going to interfere -- for instance, this is permissible
 520   // if we are still single-threaded and have either not yet
 521   // started allocating (nothing much to verify) or we have
 522   // started allocating but are now a full-fledged JavaThread
 523   // (and have thus made our TLAB's) available for filling.
 524   assert(SafepointSynchronize::is_at_safepoint() ||
 525          !is_init_completed(),
 526          "Should only be called at a safepoint or at start-up"
 527          " otherwise concurrent mutator activity may make heap "
 528          " unparsable again");
 529   const bool use_tlab = UseTLAB;
 530   const bool deferred = _defer_initial_card_mark;
 531   // The main thread starts allocating via a TLAB even before it
 532   // has added itself to the threads list at vm boot-up.
 533   assert(!use_tlab || Threads::first() != NULL,
 534          "Attempt to fill tlabs before main thread has been added"
 535          " to threads list is doomed to failure!");
 536   for (JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
 537      if (use_tlab) thread->tlab().make_parsable(retire_tlabs);
 538 #ifdef COMPILER2
 539      // The deferred store barriers must all have been flushed to the
 540      // card-table (or other remembered set structure) before GC starts
 541      // processing the card-table (or other remembered set).
 542      if (deferred) flush_deferred_store_barrier(thread);
 543 #else
 544      assert(!deferred, "Should be false");
 545      assert(thread->deferred_card_mark().is_empty(), "Should be empty");
 546 #endif
 547   }
 548 }
 549 
 550 void CollectedHeap::accumulate_statistics_all_tlabs() {
 551   if (UseTLAB) {
 552     assert(SafepointSynchronize::is_at_safepoint() ||
 553          !is_init_completed(),
 554          "should only accumulate statistics on tlabs at safepoint");
 555 
 556     ThreadLocalAllocBuffer::accumulate_statistics_before_gc();
 557   }
 558 }
 559 
 560 void CollectedHeap::resize_all_tlabs() {
 561   if (UseTLAB) {
 562     assert(SafepointSynchronize::is_at_safepoint() ||
 563          !is_init_completed(),
 564          "should only resize tlabs at safepoint");
 565 
 566     ThreadLocalAllocBuffer::resize_all_tlabs();
 567   }
 568 }
 569 
 570 void CollectedHeap::pre_full_gc_dump(GCTimer* timer) {
 571   if (HeapDumpBeforeFullGC) {
 572     GCTraceTime tt("Heap Dump (before full gc): ", PrintGCDetails, false, timer, GCId::create());
 573     // We are doing a "major" collection and a heap dump before
 574     // major collection has been requested.
 575     HeapDumper::dump_heap();
 576   }
 577   if (PrintClassHistogramBeforeFullGC) {
 578     GCTraceTime tt("Class Histogram (before full gc): ", PrintGCDetails, true, timer, GCId::create());
 579     VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */);
 580     inspector.doit();
 581   }
 582 }
 583 
 584 void CollectedHeap::post_full_gc_dump(GCTimer* timer) {
 585   if (HeapDumpAfterFullGC) {
 586     GCTraceTime tt("Heap Dump (after full gc): ", PrintGCDetails, false, timer, GCId::create());
 587     HeapDumper::dump_heap();
 588   }
 589   if (PrintClassHistogramAfterFullGC) {
 590     GCTraceTime tt("Class Histogram (after full gc): ", PrintGCDetails, true, timer, GCId::create());
 591     VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */);
 592     inspector.doit();
 593   }
 594 }
 595 
 596 void CollectedHeap::initialize_reserved_region(HeapWord *start, HeapWord *end) {
 597   // It is important to do this in a way such that concurrent readers can't
 598   // temporarily think something is in the heap.  (Seen this happen in asserts.)
 599   _reserved.set_word_size(0);
 600   _reserved.set_start(start);
 601   _reserved.set_end(end);
 602 }
 603 
 604 /////////////// Unit tests ///////////////
 605 
 606 #ifndef PRODUCT
 607 void CollectedHeap::test_is_in() {
 608   CollectedHeap* heap = Universe::heap();
 609 
 610   uintptr_t epsilon    = (uintptr_t) MinObjAlignment;
 611   uintptr_t heap_start = (uintptr_t) heap->_reserved.start();
 612   uintptr_t heap_end   = (uintptr_t) heap->_reserved.end();
 613 
 614   // Test that NULL is not in the heap.
 615   assert(!heap->is_in(NULL), "NULL is unexpectedly in the heap");
 616 
 617   // Test that a pointer to before the heap start is reported as outside the heap.
 618   assert(heap_start >= ((uintptr_t)NULL + epsilon), "sanity");
 619   void* before_heap = (void*)(heap_start - epsilon);
 620   assert(!heap->is_in(before_heap),
 621       err_msg("before_heap: " PTR_FORMAT " is unexpectedly in the heap", p2i(before_heap)));
 622 
 623   // Test that a pointer to after the heap end is reported as outside the heap.
 624   assert(heap_end <= ((uintptr_t)-1 - epsilon), "sanity");
 625   void* after_heap = (void*)(heap_end + epsilon);
 626   assert(!heap->is_in(after_heap),
 627       err_msg("after_heap: " PTR_FORMAT " is unexpectedly in the heap", p2i(after_heap)));
 628 }
 629 #endif