collectedHeap.cpp 19.6 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30
#include "precompiled.hpp"
#include "classfile/systemDictionary.hpp"
#include "gc_implementation/shared/vmGCOperations.hpp"
#include "gc_interface/collectedHeap.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "oops/oop.inline.hpp"
31
#include "oops/instanceMirrorKlass.hpp"
32 33 34 35 36 37 38 39 40 41 42
#include "runtime/init.hpp"
#include "services/heapDumper.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "thread_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "thread_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "thread_windows.inline.hpp"
#endif
N
never 已提交
43 44 45
#ifdef TARGET_OS_FAMILY_bsd
# include "thread_bsd.inline.hpp"
#endif
D
duke 已提交
46 47 48 49 50 51


#ifdef ASSERT
int CollectedHeap::_fire_out_of_memory_count = 0;
#endif

52 53
size_t CollectedHeap::_filler_array_max_size = 0;

54 55 56 57 58 59 60 61 62 63 64
template <>
void EventLogBase<GCMessage>::print(outputStream* st, GCMessage& m) {
  st->print_cr("GC heap %s", m.is_before ? "before" : "after");
  st->print_raw(m);
}

void GCHeapLog::log_heap(bool before) {
  if (!should_log()) {
    return;
  }

N
never 已提交
65
  double timestamp = fetch_timestamp();
66 67 68 69 70 71 72
  MutexLockerEx ml(&_mutex, Mutex::_no_safepoint_check_flag);
  int index = compute_log_index();
  _records[index].thread = NULL; // Its the GC thread so it's not that interesting.
  _records[index].timestamp = timestamp;
  _records[index].data.is_before = before;
  stringStream st(_records[index].data.buffer(), _records[index].data.size());
  if (before) {
N
never 已提交
73
    Universe::print_heap_before_gc(&st, true);
74
  } else {
N
never 已提交
75
    Universe::print_heap_after_gc(&st, true);
76 77 78
  }
}

D
duke 已提交
79 80
// Memory state functions.

81 82 83

CollectedHeap::CollectedHeap() : _n_par_threads(0)

84 85 86 87
{
  const size_t max_len = size_t(arrayOopDesc::max_array_length(T_INT));
  const size_t elements_per_word = HeapWordSize / sizeof(jint);
  _filler_array_max_size = align_object_size(filler_array_hdr_size() +
88
                                             max_len / elements_per_word);
89 90 91 92 93

  _barrier_set = NULL;
  _is_gc_active = false;
  _total_collections = _total_full_collections = 0;
  _gc_cause = _gc_lastcause = GCCause::_no_gc;
D
duke 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107
  NOT_PRODUCT(_promotion_failure_alot_count = 0;)
  NOT_PRODUCT(_promotion_failure_alot_gc_number = 0;)

  if (UsePerfData) {
    EXCEPTION_MARK;

    // create the gc cause jvmstat counters
    _perf_gc_cause = PerfDataManager::create_string_variable(SUN_GC, "cause",
                             80, GCCause::to_string(_gc_cause), CHECK);

    _perf_gc_lastcause =
                PerfDataManager::create_string_variable(SUN_GC, "lastCause",
                             80, GCCause::to_string(_gc_lastcause), CHECK);
  }
108
  _defer_initial_card_mark = false; // strengthened by subclass in pre_initialize() below.
109 110 111 112 113 114
  // Create the ring log
  if (LogEvents) {
    _gc_heap_log = new GCHeapLog();
  } else {
    _gc_heap_log = NULL;
  }
D
duke 已提交
115 116
}

117 118 119
void CollectedHeap::pre_initialize() {
  // Used for ReduceInitialCardMarks (when COMPILER2 is used);
  // otherwise remains unused.
120
#ifdef COMPILER2
121 122
  _defer_initial_card_mark =    ReduceInitialCardMarks && can_elide_tlab_store_barriers()
                             && (DeferInitialCardMark || card_mark_must_follow_store());
123 124 125 126
#else
  assert(_defer_initial_card_mark == false, "Who would set it?");
#endif
}
D
duke 已提交
127 128 129 130 131 132 133 134 135 136 137

#ifndef PRODUCT
void CollectedHeap::check_for_bad_heap_word_value(HeapWord* addr, size_t size) {
  if (CheckMemoryInitialization && ZapUnusedHeapArea) {
    for (size_t slot = 0; slot < size; slot += 1) {
      assert((*(intptr_t*) (addr + slot)) != ((intptr_t) badHeapWordVal),
             "Found badHeapWordValue in post-allocation check");
    }
  }
}

138
void CollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr, size_t size) {
D
duke 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  if (CheckMemoryInitialization && ZapUnusedHeapArea) {
    for (size_t slot = 0; slot < size; slot += 1) {
      assert((*(intptr_t*) (addr + slot)) == ((intptr_t) badHeapWordVal),
             "Found non badHeapWordValue in pre-allocation check");
    }
  }
}
#endif // PRODUCT

#ifdef ASSERT
void CollectedHeap::check_for_valid_allocation_state() {
  Thread *thread = Thread::current();
  // How to choose between a pending exception and a potential
  // OutOfMemoryError?  Don't allow pending exceptions.
  // This is a VM policy failure, so how do we exhaustively test it?
  assert(!thread->has_pending_exception(),
         "shouldn't be allocating with pending exception");
  if (StrictSafepointChecks) {
    assert(thread->allow_allocation(),
           "Allocation done by thread for which allocation is blocked "
           "by No_Allocation_Verifier!");
    // Allocation of an oop can always invoke a safepoint,
    // hence, the true argument
    thread->check_for_valid_safepoint_state(true);
  }
}
#endif

HeapWord* CollectedHeap::allocate_from_tlab_slow(Thread* thread, size_t size) {

  // Retain tlab and allocate object in shared space if
  // the amount free in the tlab is too large to discard.
  if (thread->tlab().free() > thread->tlab().refill_waste_limit()) {
    thread->tlab().record_slow_allocation(size);
    return NULL;
  }

  // Discard tlab and allocate a new one.
  // To minimize fragmentation, the last TLAB may be smaller than the rest.
  size_t new_tlab_size = thread->tlab().compute_size(size);

  thread->tlab().clear_before_allocation();

  if (new_tlab_size == 0) {
    return NULL;
  }

  // Allocate a new TLAB...
  HeapWord* obj = Universe::heap()->allocate_new_tlab(new_tlab_size);
  if (obj == NULL) {
    return NULL;
  }
  if (ZeroTLAB) {
    // ..and clear it.
    Copy::zero_to_words(obj, new_tlab_size);
  } else {
K
kvn 已提交
195 196 197 198 199 200 201 202
    // ...and zap just allocated object.
#ifdef ASSERT
    // Skip mangling the space corresponding to the object header to
    // ensure that the returned space is not considered parsable by
    // any concurrent GC thread.
    size_t hdr_size = oopDesc::header_size();
    Copy::fill_to_words(obj + hdr_size, new_tlab_size - hdr_size, badHeapWordVal);
#endif // ASSERT
D
duke 已提交
203 204 205 206 207
  }
  thread->tlab().fill(obj, obj + size, new_tlab_size);
  return obj;
}

208 209 210
void CollectedHeap::flush_deferred_store_barrier(JavaThread* thread) {
  MemRegion deferred = thread->deferred_card_mark();
  if (!deferred.is_empty()) {
211
    assert(_defer_initial_card_mark, "Otherwise should be empty");
212 213 214 215 216
    {
      // Verify that the storage points to a parsable object in heap
      DEBUG_ONLY(oop old_obj = oop(deferred.start());)
      assert(is_in(old_obj), "Not in allocated heap");
      assert(!can_elide_initializing_store_barrier(old_obj),
217
             "Else should have been filtered in new_store_pre_barrier()");
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
      assert(!is_in_permanent(old_obj), "Sanity: not expected");
      assert(old_obj->is_oop(true), "Not an oop");
      assert(old_obj->is_parsable(), "Will not be concurrently parsable");
      assert(deferred.word_size() == (size_t)(old_obj->size()),
             "Mismatch: multiple objects?");
    }
    BarrierSet* bs = barrier_set();
    assert(bs->has_write_region_opt(), "No write_region() on BarrierSet");
    bs->write_region(deferred);
    // "Clear" the deferred_card_mark field
    thread->set_deferred_card_mark(MemRegion());
  }
  assert(thread->deferred_card_mark().is_empty(), "invariant");
}

// Helper for ReduceInitialCardMarks. For performance,
// compiled code may elide card-marks for initializing stores
// to a newly allocated object along the fast-path. We
// compensate for such elided card-marks as follows:
// (a) Generational, non-concurrent collectors, such as
//     GenCollectedHeap(ParNew,DefNew,Tenured) and
//     ParallelScavengeHeap(ParallelGC, ParallelOldGC)
//     need the card-mark if and only if the region is
//     in the old gen, and do not care if the card-mark
//     succeeds or precedes the initializing stores themselves,
//     so long as the card-mark is completed before the next
//     scavenge. For all these cases, we can do a card mark
//     at the point at which we do a slow path allocation
246
//     in the old gen, i.e. in this call.
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
// (b) GenCollectedHeap(ConcurrentMarkSweepGeneration) requires
//     in addition that the card-mark for an old gen allocated
//     object strictly follow any associated initializing stores.
//     In these cases, the memRegion remembered below is
//     used to card-mark the entire region either just before the next
//     slow-path allocation by this thread or just before the next scavenge or
//     CMS-associated safepoint, whichever of these events happens first.
//     (The implicit assumption is that the object has been fully
//     initialized by this point, a fact that we assert when doing the
//     card-mark.)
// (c) G1CollectedHeap(G1) uses two kinds of write barriers. When a
//     G1 concurrent marking is in progress an SATB (pre-write-)barrier is
//     is used to remember the pre-value of any store. Initializing
//     stores will not need this barrier, so we need not worry about
//     compensating for the missing pre-barrier here. Turning now
//     to the post-barrier, we note that G1 needs a RS update barrier
//     which simply enqueues a (sequence of) dirty cards which may
//     optionally be refined by the concurrent update threads. Note
//     that this barrier need only be applied to a non-young write,
//     but, like in CMS, because of the presence of concurrent refinement
//     (much like CMS' precleaning), must strictly follow the oop-store.
//     Thus, using the same protocol for maintaining the intended
269 270
//     invariants turns out, serendepitously, to be the same for both
//     G1 and CMS.
271
//
272 273 274 275
// For any future collector, this code should be reexamined with
// that specific collector in mind, and the documentation above suitably
// extended and updated.
oop CollectedHeap::new_store_pre_barrier(JavaThread* thread, oop new_obj) {
276 277 278 279 280 281 282
  // If a previous card-mark was deferred, flush it now.
  flush_deferred_store_barrier(thread);
  if (can_elide_initializing_store_barrier(new_obj)) {
    // The deferred_card_mark region should be empty
    // following the flush above.
    assert(thread->deferred_card_mark().is_empty(), "Error");
  } else {
283 284 285 286 287 288 289 290 291 292 293
    MemRegion mr((HeapWord*)new_obj, new_obj->size());
    assert(!mr.is_empty(), "Error");
    if (_defer_initial_card_mark) {
      // Defer the card mark
      thread->set_deferred_card_mark(mr);
    } else {
      // Do the card mark
      BarrierSet* bs = barrier_set();
      assert(bs->has_write_region_opt(), "No write_region() on BarrierSet");
      bs->write_region(mr);
    }
294 295 296 297
  }
  return new_obj;
}

298
size_t CollectedHeap::filler_array_hdr_size() {
299
  return size_t(align_object_offset(arrayOopDesc::header_size(T_INT))); // align to Long
300 301 302
}

size_t CollectedHeap::filler_array_min_size() {
303
  return align_object_size(filler_array_hdr_size()); // align to MinObjAlignment
304 305 306 307 308 309 310 311 312 313 314
}

#ifdef ASSERT
void CollectedHeap::fill_args_check(HeapWord* start, size_t words)
{
  assert(words >= min_fill_size(), "too small to fill");
  assert(words % MinObjAlignment == 0, "unaligned size");
  assert(Universe::heap()->is_in_reserved(start), "not in heap");
  assert(Universe::heap()->is_in_reserved(start + words - 1), "not in heap");
}

J
johnc 已提交
315
void CollectedHeap::zap_filler_array(HeapWord* start, size_t words, bool zap)
316
{
J
johnc 已提交
317
  if (ZapFillerObjects && zap) {
318 319 320 321 322 323 324
    Copy::fill_to_words(start + filler_array_hdr_size(),
                        words - filler_array_hdr_size(), 0XDEAFBABE);
  }
}
#endif // ASSERT

void
J
johnc 已提交
325
CollectedHeap::fill_with_array(HeapWord* start, size_t words, bool zap)
326 327 328 329 330 331
{
  assert(words >= filler_array_min_size(), "too small for an array");
  assert(words <= filler_array_max_size(), "too big for a single object");

  const size_t payload_size = words - filler_array_hdr_size();
  const size_t len = payload_size * HeapWordSize / sizeof(jint);
332
  assert((int)len >= 0, err_msg("size too large " SIZE_FORMAT " becomes %d", words, (int)len));
333 334 335

  // Set the length first for concurrent GC.
  ((arrayOop)start)->set_length((int)len);
336
  post_allocation_setup_common(Universe::intArrayKlassObj(), start);
J
johnc 已提交
337
  DEBUG_ONLY(zap_filler_array(start, words, zap);)
338 339 340
}

void
J
johnc 已提交
341
CollectedHeap::fill_with_object_impl(HeapWord* start, size_t words, bool zap)
342 343 344 345
{
  assert(words <= filler_array_max_size(), "too big for a single object");

  if (words >= filler_array_min_size()) {
J
johnc 已提交
346
    fill_with_array(start, words, zap);
347 348
  } else if (words > 0) {
    assert(words == min_fill_size(), "unaligned size");
349
    post_allocation_setup_common(SystemDictionary::Object_klass(), start);
350 351 352
  }
}

J
johnc 已提交
353
void CollectedHeap::fill_with_object(HeapWord* start, size_t words, bool zap)
354 355 356
{
  DEBUG_ONLY(fill_args_check(start, words);)
  HandleMark hm;  // Free handles before leaving.
J
johnc 已提交
357
  fill_with_object_impl(start, words, zap);
358 359
}

J
johnc 已提交
360
void CollectedHeap::fill_with_objects(HeapWord* start, size_t words, bool zap)
361 362 363 364
{
  DEBUG_ONLY(fill_args_check(start, words);)
  HandleMark hm;  // Free handles before leaving.

365
#ifdef _LP64
366 367 368 369 370 371 372
  // A single array can fill ~8G, so multiple objects are needed only in 64-bit.
  // First fill with arrays, ensuring that any remaining space is big enough to
  // fill.  The remainder is filled with a single object.
  const size_t min = min_fill_size();
  const size_t max = filler_array_max_size();
  while (words > max) {
    const size_t cur = words - max >= min ? max : max - min;
J
johnc 已提交
373
    fill_with_array(start, cur, zap);
374 375 376 377 378
    start += cur;
    words -= cur;
  }
#endif

J
johnc 已提交
379
  fill_with_object_impl(start, words, zap);
380 381
}

D
duke 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
HeapWord* CollectedHeap::allocate_new_tlab(size_t size) {
  guarantee(false, "thread-local allocation buffers not supported");
  return NULL;
}

void CollectedHeap::ensure_parsability(bool retire_tlabs) {
  // The second disjunct in the assertion below makes a concession
  // for the start-up verification done while the VM is being
  // created. Callers be careful that you know that mutators
  // aren't going to interfere -- for instance, this is permissible
  // if we are still single-threaded and have either not yet
  // started allocating (nothing much to verify) or we have
  // started allocating but are now a full-fledged JavaThread
  // (and have thus made our TLAB's) available for filling.
  assert(SafepointSynchronize::is_at_safepoint() ||
         !is_init_completed(),
         "Should only be called at a safepoint or at start-up"
         " otherwise concurrent mutator activity may make heap "
         " unparsable again");
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
  const bool use_tlab = UseTLAB;
  const bool deferred = _defer_initial_card_mark;
  // The main thread starts allocating via a TLAB even before it
  // has added itself to the threads list at vm boot-up.
  assert(!use_tlab || Threads::first() != NULL,
         "Attempt to fill tlabs before main thread has been added"
         " to threads list is doomed to failure!");
  for (JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
     if (use_tlab) thread->tlab().make_parsable(retire_tlabs);
#ifdef COMPILER2
     // The deferred store barriers must all have been flushed to the
     // card-table (or other remembered set structure) before GC starts
     // processing the card-table (or other remembered set).
     if (deferred) flush_deferred_store_barrier(thread);
#else
     assert(!deferred, "Should be false");
     assert(thread->deferred_card_mark().is_empty(), "Should be empty");
#endif
D
duke 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  }
}

void CollectedHeap::accumulate_statistics_all_tlabs() {
  if (UseTLAB) {
    assert(SafepointSynchronize::is_at_safepoint() ||
         !is_init_completed(),
         "should only accumulate statistics on tlabs at safepoint");

    ThreadLocalAllocBuffer::accumulate_statistics_before_gc();
  }
}

void CollectedHeap::resize_all_tlabs() {
  if (UseTLAB) {
    assert(SafepointSynchronize::is_at_safepoint() ||
         !is_init_completed(),
         "should only resize tlabs at safepoint");

    ThreadLocalAllocBuffer::resize_all_tlabs();
  }
}
441 442 443

void CollectedHeap::pre_full_gc_dump() {
  if (HeapDumpBeforeFullGC) {
444
    TraceTime tt("Heap Dump (before full gc): ", PrintGCDetails, false, gclog_or_tty);
445 446 447 448 449
    // We are doing a "major" collection and a heap dump before
    // major collection has been requested.
    HeapDumper::dump_heap();
  }
  if (PrintClassHistogramBeforeFullGC) {
450
    TraceTime tt("Class Histogram (before full gc): ", PrintGCDetails, true, gclog_or_tty);
451 452 453 454 455 456 457
    VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */, false /* ! prologue */);
    inspector.doit();
  }
}

void CollectedHeap::post_full_gc_dump() {
  if (HeapDumpAfterFullGC) {
458
    TraceTime tt("Heap Dump (after full gc): ", PrintGCDetails, false, gclog_or_tty);
459 460 461
    HeapDumper::dump_heap();
  }
  if (PrintClassHistogramAfterFullGC) {
462
    TraceTime tt("Class Histogram (after full gc): ", PrintGCDetails, true, gclog_or_tty);
463 464 465 466
    VM_GC_HeapInspection inspector(gclog_or_tty, false /* ! full gc */, false /* ! prologue */);
    inspector.doit();
  }
}
467 468 469 470 471 472 473 474 475 476 477 478

oop CollectedHeap::Class_obj_allocate(KlassHandle klass, int size, KlassHandle real_klass, TRAPS) {
  debug_only(check_for_valid_allocation_state());
  assert(!Universe::heap()->is_gc_active(), "Allocation during gc not allowed");
  assert(size >= 0, "int won't convert to size_t");
  HeapWord* obj;
  if (JavaObjectsInPerm) {
    obj = common_permanent_mem_allocate_init(size, CHECK_NULL);
  } else {
    assert(ScavengeRootsInCode > 0, "must be");
    obj = common_mem_allocate_init(size, CHECK_NULL);
  }
479
  post_allocation_setup_common(klass, obj);
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
  assert(Universe::is_bootstrapping() ||
         !((oop)obj)->blueprint()->oop_is_array(), "must not be an array");
  NOT_PRODUCT(Universe::heap()->check_for_bad_heap_word_value(obj, size));
  oop mirror = (oop)obj;

  java_lang_Class::set_oop_size(mirror, size);

  // Setup indirections
  if (!real_klass.is_null()) {
    java_lang_Class::set_klass(mirror, real_klass());
    real_klass->set_java_mirror(mirror);
  }

  instanceMirrorKlass* mk = instanceMirrorKlass::cast(mirror->klass());
  assert(size == mk->instance_size(real_klass), "should have been set");

  // notify jvmti and dtrace
  post_allocation_notify(klass, (oop)obj);

  return mirror;
}
S
stefank 已提交
501 502 503 504 505 506 507

/////////////// Unit tests ///////////////

#ifndef PRODUCT
void CollectedHeap::test_is_in() {
  CollectedHeap* heap = Universe::heap();

508 509 510 511
  uintptr_t epsilon    = (uintptr_t) MinObjAlignment;
  uintptr_t heap_start = (uintptr_t) heap->_reserved.start();
  uintptr_t heap_end   = (uintptr_t) heap->_reserved.end();

S
stefank 已提交
512 513 514 515
  // Test that NULL is not in the heap.
  assert(!heap->is_in(NULL), "NULL is unexpectedly in the heap");

  // Test that a pointer to before the heap start is reported as outside the heap.
516 517
  assert(heap_start >= ((uintptr_t)NULL + epsilon), "sanity");
  void* before_heap = (void*)(heap_start - epsilon);
S
stefank 已提交
518 519 520 521
  assert(!heap->is_in(before_heap),
      err_msg("before_heap: " PTR_FORMAT " is unexpectedly in the heap", before_heap));

  // Test that a pointer to after the heap end is reported as outside the heap.
522 523
  assert(heap_end <= ((uintptr_t)-1 - epsilon), "sanity");
  void* after_heap = (void*)(heap_end + epsilon);
S
stefank 已提交
524 525 526 527
  assert(!heap->is_in(after_heap),
      err_msg("after_heap: " PTR_FORMAT " is unexpectedly in the heap", after_heap));
}
#endif