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