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 "gc/parallel/objectStartArray.inline.hpp"
  27 #include "gc/parallel/parallelScavengeHeap.hpp"
  28 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
  29 #include "gc/parallel/psCardTable.hpp"
  30 #include "gc/parallel/psMarkSweepDecorator.hpp"
  31 #include "gc/parallel/psOldGen.hpp"
  32 #include "gc/shared/cardTableBarrierSet.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "gc/shared/spaceDecorator.hpp"
  35 #include "logging/log.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "runtime/java.hpp"
  38 #include "utilities/align.hpp"
  39 
  40 inline const char* PSOldGen::select_name() {
  41   return UseParallelOldGC ? "ParOldGen" : "PSOldGen";
  42 }
  43 
  44 PSOldGen::PSOldGen(ReservedSpace rs, size_t alignment,
  45                    size_t initial_size, size_t min_size, size_t max_size,
  46                    const char* perf_data_name, int level):
  47   _name(select_name()), _init_gen_size(initial_size), _min_gen_size(min_size),
  48   _max_gen_size(max_size)
  49 {
  50   initialize(rs, alignment, perf_data_name, level);
  51 }
  52 
  53 PSOldGen::PSOldGen(size_t initial_size,
  54                    size_t min_size, size_t max_size,
  55                    const char* perf_data_name, int level):
  56   _name(select_name()), _init_gen_size(initial_size), _min_gen_size(min_size),
  57   _max_gen_size(max_size)
  58 {}
  59 
  60 void PSOldGen::initialize(ReservedSpace rs, size_t alignment,
  61                           const char* perf_data_name, int level) {
  62   initialize_virtual_space(rs, alignment);
  63   initialize_work(perf_data_name, level);
  64 
  65   // The old gen can grow to gen_size_limit().  _reserve reflects only
  66   // the current maximum that can be committed.
  67   assert(_reserved.byte_size() <= gen_size_limit(), "Consistency check");
  68 
  69   initialize_performance_counters(perf_data_name, level);
  70 }
  71 
  72 void PSOldGen::initialize_virtual_space(ReservedSpace rs, size_t alignment) {
  73 
  74   _virtual_space = new PSVirtualSpace(rs, alignment);
  75   if (!_virtual_space->expand_by(_init_gen_size)) {
  76     vm_exit_during_initialization("Could not reserve enough space for "
  77                                   "object heap");
  78   }
  79 }
  80 
  81 void PSOldGen::initialize_work(const char* perf_data_name, int level) {
  82   //
  83   // Basic memory initialization
  84   //
  85 
  86   MemRegion limit_reserved((HeapWord*)virtual_space()->low_boundary(),
  87     heap_word_size(_max_gen_size));
  88   assert(limit_reserved.byte_size() == _max_gen_size,
  89     "word vs bytes confusion");
  90   //
  91   // Object start stuff
  92   //
  93 
  94   start_array()->initialize(limit_reserved);
  95 
  96   _reserved = MemRegion((HeapWord*)virtual_space()->low_boundary(),
  97                         (HeapWord*)virtual_space()->high_boundary());
  98 
  99   //
 100   // Card table stuff
 101   //
 102 
 103   MemRegion cmr((HeapWord*)virtual_space()->low(),
 104                 (HeapWord*)virtual_space()->high());
 105   if (ZapUnusedHeapArea) {
 106     // Mangle newly committed space immediately rather than
 107     // waiting for the initialization of the space even though
 108     // mangling is related to spaces.  Doing it here eliminates
 109     // the need to carry along information that a complete mangling
 110     // (bottom to end) needs to be done.
 111     SpaceMangler::mangle_region(cmr);
 112   }
 113 
 114   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 115   PSCardTable* ct = heap->card_table();
 116   ct->resize_covered_region(cmr);
 117 
 118   // Verify that the start and end of this generation is the start of a card.
 119   // If this wasn't true, a single card could span more than one generation,
 120   // which would cause problems when we commit/uncommit memory, and when we
 121   // clear and dirty cards.
 122   guarantee(ct->is_card_aligned(_reserved.start()), "generation must be card aligned");
 123   if (_reserved.end() != heap->reserved_region().end()) {
 124     // Don't check at the very end of the heap as we'll assert that we're probing off
 125     // the end if we try.
 126     guarantee(ct->is_card_aligned(_reserved.end()), "generation must be card aligned");
 127   }
 128 
 129   //
 130   // ObjectSpace stuff
 131   //
 132 
 133   _object_space = new MutableSpace(virtual_space()->alignment());
 134 
 135   if (_object_space == NULL)
 136     vm_exit_during_initialization("Could not allocate an old gen space");
 137 
 138   object_space()->initialize(cmr,
 139                              SpaceDecorator::Clear,
 140                              SpaceDecorator::Mangle);
 141 
 142 #if INCLUDE_SERIALGC
 143   _object_mark_sweep = new PSMarkSweepDecorator(_object_space, start_array(), MarkSweepDeadRatio);
 144 
 145   if (_object_mark_sweep == NULL) {
 146     vm_exit_during_initialization("Could not complete allocation of old generation");
 147   }
 148 #endif // INCLUDE_SERIALGC
 149 
 150   // Update the start_array
 151   start_array()->set_covered_region(cmr);
 152 }
 153 
 154 void PSOldGen::initialize_performance_counters(const char* perf_data_name, int level) {
 155   // Generation Counters, generation 'level', 1 subspace
 156   _gen_counters = new PSGenerationCounters(perf_data_name, level, 1, _min_gen_size,
 157                                            _max_gen_size, virtual_space());
 158   _space_counters = new SpaceCounters(perf_data_name, 0,
 159                                       virtual_space()->reserved_size(),
 160                                       _object_space, _gen_counters);
 161 }
 162 
 163 // Assume that the generation has been allocated if its
 164 // reserved size is not 0.
 165 bool  PSOldGen::is_allocated() {
 166   return virtual_space()->reserved_size() != 0;
 167 }
 168 
 169 #if INCLUDE_SERIALGC
 170 
 171 void PSOldGen::precompact() {
 172   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 173 
 174   // Reset start array first.
 175   start_array()->reset();
 176 
 177   object_mark_sweep()->precompact();
 178 
 179   // Now compact the young gen
 180   heap->young_gen()->precompact();
 181 }
 182 
 183 void PSOldGen::adjust_pointers() {
 184   object_mark_sweep()->adjust_pointers();
 185 }
 186 
 187 void PSOldGen::compact() {
 188   object_mark_sweep()->compact(ZapUnusedHeapArea);
 189 }
 190 
 191 #endif // INCLUDE_SERIALGC
 192 
 193 size_t PSOldGen::contiguous_available() const {
 194   return object_space()->free_in_bytes() + virtual_space()->uncommitted_size();
 195 }
 196 
 197 // Allocation. We report all successful allocations to the size policy
 198 // Note that the perm gen does not use this method, and should not!
 199 HeapWord* PSOldGen::allocate(size_t word_size) {
 200   assert_locked_or_safepoint(Heap_lock);
 201   HeapWord* res = allocate_noexpand(word_size);
 202 
 203   if (res == NULL) {
 204     res = expand_and_allocate(word_size);
 205   }
 206 
 207   // Allocations in the old generation need to be reported
 208   if (res != NULL) {
 209     ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 210     heap->size_policy()->tenured_allocation(word_size * HeapWordSize);
 211   }
 212 
 213   return res;
 214 }
 215 
 216 HeapWord* PSOldGen::expand_and_allocate(size_t word_size) {
 217   expand(word_size*HeapWordSize);
 218   if (GCExpandToAllocateDelayMillis > 0) {
 219     os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
 220   }
 221   return allocate_noexpand(word_size);
 222 }
 223 
 224 HeapWord* PSOldGen::expand_and_cas_allocate(size_t word_size) {
 225   expand(word_size*HeapWordSize);
 226   if (GCExpandToAllocateDelayMillis > 0) {
 227     os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
 228   }
 229   return cas_allocate_noexpand(word_size);
 230 }
 231 
 232 void PSOldGen::expand(size_t bytes) {
 233   if (bytes == 0) {
 234     return;
 235   }
 236   MutexLocker x(ExpandHeap_lock);
 237   const size_t alignment = virtual_space()->alignment();
 238   size_t aligned_bytes  = align_up(bytes, alignment);
 239   size_t aligned_expand_bytes = align_up(MinHeapDeltaBytes, alignment);
 240 
 241   if (UseNUMA) {
 242     // With NUMA we use round-robin page allocation for the old gen. Expand by at least
 243     // providing a page per lgroup. Alignment is larger or equal to the page size.
 244     aligned_expand_bytes = MAX2(aligned_expand_bytes, alignment * os::numa_get_groups_num());
 245   }
 246   if (aligned_bytes == 0){
 247     // The alignment caused the number of bytes to wrap.  An expand_by(0) will
 248     // return true with the implication that and expansion was done when it
 249     // was not.  A call to expand implies a best effort to expand by "bytes"
 250     // but not a guarantee.  Align down to give a best effort.  This is likely
 251     // the most that the generation can expand since it has some capacity to
 252     // start with.
 253     aligned_bytes = align_down(bytes, alignment);
 254   }
 255 
 256   bool success = false;
 257   if (aligned_expand_bytes > aligned_bytes) {
 258     success = expand_by(aligned_expand_bytes);
 259   }
 260   if (!success) {
 261     success = expand_by(aligned_bytes);
 262   }
 263   if (!success) {
 264     success = expand_to_reserved();
 265   }
 266 
 267   if (success && GCLocker::is_active_and_needs_gc()) {
 268     log_debug(gc)("Garbage collection disabled, expanded heap instead");
 269   }
 270 }
 271 
 272 bool PSOldGen::expand_by(size_t bytes) {
 273   assert_lock_strong(ExpandHeap_lock);
 274   assert_locked_or_safepoint(Heap_lock);
 275   if (bytes == 0) {
 276     return true;  // That's what virtual_space()->expand_by(0) would return
 277   }
 278   bool result = virtual_space()->expand_by(bytes);
 279   if (result) {
 280     if (ZapUnusedHeapArea) {
 281       // We need to mangle the newly expanded area. The memregion spans
 282       // end -> new_end, we assume that top -> end is already mangled.
 283       // Do the mangling before post_resize() is called because
 284       // the space is available for allocation after post_resize();
 285       HeapWord* const virtual_space_high = (HeapWord*) virtual_space()->high();
 286       assert(object_space()->end() < virtual_space_high,
 287         "Should be true before post_resize()");
 288       MemRegion mangle_region(object_space()->end(), virtual_space_high);
 289       // Note that the object space has not yet been updated to
 290       // coincide with the new underlying virtual space.
 291       SpaceMangler::mangle_region(mangle_region);
 292     }
 293     post_resize();
 294     if (UsePerfData) {
 295       _space_counters->update_capacity();
 296       _gen_counters->update_all();
 297     }
 298   }
 299 
 300   if (result) {
 301     size_t new_mem_size = virtual_space()->committed_size();
 302     size_t old_mem_size = new_mem_size - bytes;
 303     log_debug(gc)("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
 304                   name(), old_mem_size/K, bytes/K, new_mem_size/K);
 305   }
 306 
 307   return result;
 308 }
 309 
 310 bool PSOldGen::expand_to_reserved() {
 311   assert_lock_strong(ExpandHeap_lock);
 312   assert_locked_or_safepoint(Heap_lock);
 313 
 314   bool result = true;
 315   const size_t remaining_bytes = virtual_space()->uncommitted_size();
 316   if (remaining_bytes > 0) {
 317     result = expand_by(remaining_bytes);
 318     DEBUG_ONLY(if (!result) log_warning(gc)("grow to reserve failed"));
 319   }
 320   return result;
 321 }
 322 
 323 void PSOldGen::shrink(size_t bytes) {
 324   assert_lock_strong(ExpandHeap_lock);
 325   assert_locked_or_safepoint(Heap_lock);
 326 
 327   size_t size = align_down(bytes, virtual_space()->alignment());
 328   if (size > 0) {
 329     assert_lock_strong(ExpandHeap_lock);
 330     virtual_space()->shrink_by(bytes);
 331     post_resize();
 332 
 333     size_t new_mem_size = virtual_space()->committed_size();
 334     size_t old_mem_size = new_mem_size + bytes;
 335     log_debug(gc)("Shrinking %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
 336                   name(), old_mem_size/K, bytes/K, new_mem_size/K);
 337   }
 338 }
 339 
 340 void PSOldGen::resize(size_t desired_free_space) {
 341   const size_t alignment = virtual_space()->alignment();
 342   const size_t size_before = virtual_space()->committed_size();
 343   size_t new_size = used_in_bytes() + desired_free_space;
 344   if (new_size < used_in_bytes()) {
 345     // Overflowed the addition.
 346     new_size = gen_size_limit();
 347   }
 348   // Adjust according to our min and max
 349   new_size = MAX2(MIN2(new_size, gen_size_limit()), min_gen_size());
 350 
 351   assert(gen_size_limit() >= reserved().byte_size(), "max new size problem?");
 352   new_size = align_up(new_size, alignment);
 353 
 354   const size_t current_size = capacity_in_bytes();
 355 
 356   log_trace(gc, ergo)("AdaptiveSizePolicy::old generation size: "
 357     "desired free: " SIZE_FORMAT " used: " SIZE_FORMAT
 358     " new size: " SIZE_FORMAT " current size " SIZE_FORMAT
 359     " gen limits: " SIZE_FORMAT " / " SIZE_FORMAT,
 360     desired_free_space, used_in_bytes(), new_size, current_size,
 361     gen_size_limit(), min_gen_size());
 362 
 363   if (new_size == current_size) {
 364     // No change requested
 365     return;
 366   }
 367   if (new_size > current_size) {
 368     size_t change_bytes = new_size - current_size;
 369     expand(change_bytes);
 370   } else {
 371     size_t change_bytes = current_size - new_size;
 372     // shrink doesn't grab this lock, expand does. Is that right?
 373     MutexLocker x(ExpandHeap_lock);
 374     shrink(change_bytes);
 375   }
 376 
 377   log_trace(gc, ergo)("AdaptiveSizePolicy::old generation size: collection: %d (" SIZE_FORMAT ") -> (" SIZE_FORMAT ") ",
 378                       ParallelScavengeHeap::heap()->total_collections(),
 379                       size_before,
 380                       virtual_space()->committed_size());
 381 }
 382 
 383 // NOTE! We need to be careful about resizing. During a GC, multiple
 384 // allocators may be active during heap expansion. If we allow the
 385 // heap resizing to become visible before we have correctly resized
 386 // all heap related data structures, we may cause program failures.
 387 void PSOldGen::post_resize() {
 388   // First construct a memregion representing the new size
 389   MemRegion new_memregion((HeapWord*)virtual_space()->low(),
 390     (HeapWord*)virtual_space()->high());
 391   size_t new_word_size = new_memregion.word_size();
 392 
 393   start_array()->set_covered_region(new_memregion);
 394   ParallelScavengeHeap::heap()->card_table()->resize_covered_region(new_memregion);
 395 
 396   // ALWAYS do this last!!
 397   object_space()->initialize(new_memregion,
 398                              SpaceDecorator::DontClear,
 399                              SpaceDecorator::DontMangle);
 400 
 401   assert(new_word_size == heap_word_size(object_space()->capacity_in_bytes()),
 402     "Sanity");
 403 }
 404 
 405 size_t PSOldGen::gen_size_limit() {
 406   return _max_gen_size;
 407 }
 408 
 409 void PSOldGen::reset_after_change() {
 410   ShouldNotReachHere();
 411   return;
 412 }
 413 
 414 size_t PSOldGen::available_for_expansion() {
 415   ShouldNotReachHere();
 416   return 0;
 417 }
 418 
 419 size_t PSOldGen::available_for_contraction() {
 420   ShouldNotReachHere();
 421   return 0;
 422 }
 423 
 424 void PSOldGen::print() const { print_on(tty);}
 425 void PSOldGen::print_on(outputStream* st) const {
 426   st->print(" %-15s", name());
 427   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
 428               capacity_in_bytes()/K, used_in_bytes()/K);
 429   st->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
 430                 p2i(virtual_space()->low_boundary()),
 431                 p2i(virtual_space()->high()),
 432                 p2i(virtual_space()->high_boundary()));
 433 
 434   st->print("  object"); object_space()->print_on(st);
 435 }
 436 
 437 void PSOldGen::print_used_change(size_t prev_used) const {
 438   log_info(gc, heap)("%s: "  SIZE_FORMAT "K->" SIZE_FORMAT "K("  SIZE_FORMAT "K)",
 439       name(), prev_used / K, used_in_bytes() / K, capacity_in_bytes() / K);
 440 }
 441 
 442 void PSOldGen::update_counters() {
 443   if (UsePerfData) {
 444     _space_counters->update_all();
 445     _gen_counters->update_all();
 446   }
 447 }
 448 
 449 #ifndef PRODUCT
 450 
 451 void PSOldGen::space_invariants() {
 452   assert(object_space()->end() == (HeapWord*) virtual_space()->high(),
 453     "Space invariant");
 454   assert(object_space()->bottom() == (HeapWord*) virtual_space()->low(),
 455     "Space invariant");
 456   assert(virtual_space()->low_boundary() <= virtual_space()->low(),
 457     "Space invariant");
 458   assert(virtual_space()->high_boundary() >= virtual_space()->high(),
 459     "Space invariant");
 460   assert(virtual_space()->low_boundary() == (char*) _reserved.start(),
 461     "Space invariant");
 462   assert(virtual_space()->high_boundary() == (char*) _reserved.end(),
 463     "Space invariant");
 464   assert(virtual_space()->committed_size() <= virtual_space()->reserved_size(),
 465     "Space invariant");
 466 }
 467 #endif
 468 
 469 void PSOldGen::verify() {
 470   object_space()->verify();
 471 }
 472 class VerifyObjectStartArrayClosure : public ObjectClosure {
 473   PSOldGen* _old_gen;
 474   ObjectStartArray* _start_array;
 475 
 476  public:
 477   VerifyObjectStartArrayClosure(PSOldGen* old_gen, ObjectStartArray* start_array) :
 478     _old_gen(old_gen), _start_array(start_array) { }
 479 
 480   virtual void do_object(oop obj) {
 481     HeapWord* test_addr = (HeapWord*)obj + 1;
 482     guarantee(_start_array->object_start(test_addr) == (HeapWord*)obj, "ObjectStartArray cannot find start of object");
 483     guarantee(_start_array->is_block_allocated((HeapWord*)obj), "ObjectStartArray missing block allocation");
 484   }
 485 };
 486 
 487 void PSOldGen::verify_object_start_array() {
 488   VerifyObjectStartArrayClosure check( this, &_start_array );
 489   object_iterate(&check);
 490 }
 491 
 492 #ifndef PRODUCT
 493 void PSOldGen::record_spaces_top() {
 494   assert(ZapUnusedHeapArea, "Not mangling unused space");
 495   object_space()->set_top_for_allocations();
 496 }
 497 #endif