1 /*
   2  * Copyright (c) 2014, 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/g1/g1Allocator.inline.hpp"
  27 #include "gc/g1/g1AllocRegion.inline.hpp"
  28 #include "gc/g1/g1EvacStats.inline.hpp"
  29 #include "gc/g1/g1CollectedHeap.inline.hpp"
  30 #include "gc/g1/g1Policy.hpp"
  31 #include "gc/g1/heapRegion.inline.hpp"
  32 #include "gc/g1/heapRegionSet.inline.hpp"
  33 #include "gc/g1/heapRegionType.hpp"
  34 #include "utilities/align.hpp"
  35 
  36 G1Allocator::G1Allocator(G1CollectedHeap* heap) :
  37   _g1h(heap),
  38   _survivor_is_full(false),
  39   _old_is_full(false),
  40   _mutator_alloc_region(),
  41   _survivor_gc_alloc_region(heap->alloc_buffer_stats(InCSetState::Young)),
  42   _old_gc_alloc_region(heap->alloc_buffer_stats(InCSetState::Old)),
  43   _retained_old_gc_alloc_region(NULL) {
  44 }
  45 
  46 void G1Allocator::init_mutator_alloc_region() {
  47   assert(_mutator_alloc_region.get() == NULL, "pre-condition");
  48   _mutator_alloc_region.init();
  49 }
  50 
  51 void G1Allocator::release_mutator_alloc_region() {
  52   _mutator_alloc_region.release();
  53   assert(_mutator_alloc_region.get() == NULL, "post-condition");
  54 }
  55 
  56 bool G1Allocator::is_retained_old_region(HeapRegion* hr) {
  57   return _retained_old_gc_alloc_region == hr;
  58 }
  59 
  60 void G1Allocator::reuse_retained_old_region(EvacuationInfo& evacuation_info,
  61                                             OldGCAllocRegion* old,
  62                                             HeapRegion** retained_old) {
  63   HeapRegion* retained_region = *retained_old;
  64   *retained_old = NULL;
  65   assert(retained_region == NULL || !retained_region->is_archive(),
  66          "Archive region should not be alloc region (index %u)", retained_region->hrm_index());
  67 
  68   // We will discard the current GC alloc region if:
  69   // a) it's in the collection set (it can happen!),
  70   // b) it's already full (no point in using it),
  71   // c) it's empty (this means that it was emptied during
  72   // a cleanup and it should be on the free list now), or
  73   // d) it's humongous (this means that it was emptied
  74   // during a cleanup and was added to the free list, but
  75   // has been subsequently used to allocate a humongous
  76   // object that may be less than the region size).
  77   if (retained_region != NULL &&
  78       !retained_region->in_collection_set() &&
  79       !(retained_region->top() == retained_region->end()) &&
  80       !retained_region->is_empty() &&
  81       !retained_region->is_humongous()) {
  82     // The retained region was added to the old region set when it was
  83     // retired. We have to remove it now, since we don't allow regions
  84     // we allocate to in the region sets. We'll re-add it later, when
  85     // it's retired again.
  86     _g1h->old_set_remove(retained_region);
  87     bool during_im = _g1h->collector_state()->in_initial_mark_gc();
  88     retained_region->note_start_of_copying(during_im);
  89     old->set(retained_region);
  90     _g1h->hr_printer()->reuse(retained_region);
  91     evacuation_info.set_alloc_regions_used_before(retained_region->used());
  92   }
  93 }
  94 
  95 void G1Allocator::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
  96   assert_at_safepoint_on_vm_thread();
  97 
  98   _survivor_is_full = false;
  99   _old_is_full = false;
 100 
 101   _survivor_gc_alloc_region.init();
 102   _old_gc_alloc_region.init();
 103   reuse_retained_old_region(evacuation_info,
 104                             &_old_gc_alloc_region,
 105                             &_retained_old_gc_alloc_region);
 106 }
 107 
 108 void G1Allocator::release_gc_alloc_regions(EvacuationInfo& evacuation_info) {
 109   evacuation_info.set_allocation_regions(survivor_gc_alloc_region()->count() +
 110                                          old_gc_alloc_region()->count());
 111   survivor_gc_alloc_region()->release();
 112   // If we have an old GC alloc region to release, we'll save it in
 113   // _retained_old_gc_alloc_region. If we don't
 114   // _retained_old_gc_alloc_region will become NULL. This is what we
 115   // want either way so no reason to check explicitly for either
 116   // condition.
 117   _retained_old_gc_alloc_region = old_gc_alloc_region()->release();
 118 }
 119 
 120 void G1Allocator::abandon_gc_alloc_regions() {
 121   assert(survivor_gc_alloc_region()->get() == NULL, "pre-condition");
 122   assert(old_gc_alloc_region()->get() == NULL, "pre-condition");
 123   _retained_old_gc_alloc_region = NULL;
 124 }
 125 
 126 bool G1Allocator::survivor_is_full() const {
 127   return _survivor_is_full;
 128 }
 129 
 130 bool G1Allocator::old_is_full() const {
 131   return _old_is_full;
 132 }
 133 
 134 void G1Allocator::set_survivor_full() {
 135   _survivor_is_full = true;
 136 }
 137 
 138 void G1Allocator::set_old_full() {
 139   _old_is_full = true;
 140 }
 141 
 142 size_t G1Allocator::unsafe_max_tlab_alloc() {
 143   // Return the remaining space in the cur alloc region, but not less than
 144   // the min TLAB size.
 145 
 146   // Also, this value can be at most the humongous object threshold,
 147   // since we can't allow tlabs to grow big enough to accommodate
 148   // humongous objects.
 149 
 150   HeapRegion* hr = mutator_alloc_region()->get();
 151   size_t max_tlab = _g1h->max_tlab_size() * wordSize;
 152   if (hr == NULL) {
 153     return max_tlab;
 154   } else {
 155     return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab);
 156   }
 157 }
 158 
 159 size_t G1Allocator::used_in_alloc_regions() {
 160   assert(Heap_lock->owner() != NULL, "Should be owned on this thread's behalf.");
 161   return mutator_alloc_region()->used_in_alloc_regions();
 162 }
 163 
 164 
 165 HeapWord* G1Allocator::par_allocate_during_gc(InCSetState dest,
 166                                               size_t word_size) {
 167   size_t temp = 0;
 168   HeapWord* result = par_allocate_during_gc(dest, word_size, word_size, &temp);
 169   assert(result == NULL || temp == word_size,
 170          "Requested " SIZE_FORMAT " words, but got " SIZE_FORMAT " at " PTR_FORMAT,
 171          word_size, temp, p2i(result));
 172   return result;
 173 }
 174 
 175 HeapWord* G1Allocator::par_allocate_during_gc(InCSetState dest,
 176                                               size_t min_word_size,
 177                                               size_t desired_word_size,
 178                                               size_t* actual_word_size) {
 179   switch (dest.value()) {
 180     case InCSetState::Young:
 181       return survivor_attempt_allocation(min_word_size, desired_word_size, actual_word_size);
 182     case InCSetState::Old:
 183       return old_attempt_allocation(min_word_size, desired_word_size, actual_word_size);
 184     default:
 185       ShouldNotReachHere();
 186       return NULL; // Keep some compilers happy
 187   }
 188 }
 189 
 190 HeapWord* G1Allocator::survivor_attempt_allocation(size_t min_word_size,
 191                                                    size_t desired_word_size,
 192                                                    size_t* actual_word_size) {
 193   assert(!_g1h->is_humongous(desired_word_size),
 194          "we should not be seeing humongous-size allocations in this path");
 195 
 196   HeapWord* result = survivor_gc_alloc_region()->attempt_allocation(min_word_size,
 197                                                                     desired_word_size,
 198                                                                     actual_word_size);
 199   if (result == NULL && !survivor_is_full()) {
 200     MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
 201     result = survivor_gc_alloc_region()->attempt_allocation_locked(min_word_size,
 202                                                                    desired_word_size,
 203                                                                    actual_word_size);
 204     if (result == NULL) {
 205       set_survivor_full();
 206     }
 207   }
 208   if (result != NULL) {
 209     _g1h->dirty_young_block(result, *actual_word_size);
 210   }
 211   return result;
 212 }
 213 
 214 HeapWord* G1Allocator::old_attempt_allocation(size_t min_word_size,
 215                                               size_t desired_word_size,
 216                                               size_t* actual_word_size) {
 217   assert(!_g1h->is_humongous(desired_word_size),
 218          "we should not be seeing humongous-size allocations in this path");
 219 
 220   HeapWord* result = old_gc_alloc_region()->attempt_allocation(min_word_size,
 221                                                                desired_word_size,
 222                                                                actual_word_size);
 223   if (result == NULL && !old_is_full()) {
 224     MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
 225     result = old_gc_alloc_region()->attempt_allocation_locked(min_word_size,
 226                                                               desired_word_size,
 227                                                               actual_word_size);
 228     if (result == NULL) {
 229       set_old_full();
 230     }
 231   }
 232   return result;
 233 }
 234 
 235 uint G1PLABAllocator::calc_survivor_alignment_bytes() {
 236   assert(SurvivorAlignmentInBytes >= ObjectAlignmentInBytes, "sanity");
 237   if (SurvivorAlignmentInBytes == ObjectAlignmentInBytes) {
 238     // No need to align objects in the survivors differently, return 0
 239     // which means "survivor alignment is not used".
 240     return 0;
 241   } else {
 242     assert(SurvivorAlignmentInBytes > 0, "sanity");
 243     return SurvivorAlignmentInBytes;
 244   }
 245 }
 246 
 247 G1PLABAllocator::G1PLABAllocator(G1Allocator* allocator) :
 248   _g1h(G1CollectedHeap::heap()),
 249   _allocator(allocator),
 250   _surviving_alloc_buffer(_g1h->desired_plab_sz(InCSetState::Young)),
 251   _tenured_alloc_buffer(_g1h->desired_plab_sz(InCSetState::Old)),
 252   _survivor_alignment_bytes(calc_survivor_alignment_bytes()) {
 253   for (uint state = 0; state < InCSetState::Num; state++) {
 254     _direct_allocated[state] = 0;
 255     _alloc_buffers[state] = NULL;
 256   }
 257   _alloc_buffers[InCSetState::Young] = &_surviving_alloc_buffer;
 258   _alloc_buffers[InCSetState::Old]  = &_tenured_alloc_buffer;
 259 }
 260 
 261 bool G1PLABAllocator::may_throw_away_buffer(size_t const allocation_word_sz, size_t const buffer_size) const {
 262   return (allocation_word_sz * 100 < buffer_size * ParallelGCBufferWastePct);
 263 }
 264 
 265 HeapWord* G1PLABAllocator::allocate_direct_or_new_plab(InCSetState dest,
 266                                                        size_t word_sz,
 267                                                        bool* plab_refill_failed) {
 268   size_t plab_word_size = _g1h->desired_plab_sz(dest);
 269   size_t required_in_plab = PLAB::size_required_for_allocation(word_sz);
 270 
 271   // Only get a new PLAB if the allocation fits and it would not waste more than
 272   // ParallelGCBufferWastePct in the existing buffer.
 273   if ((required_in_plab <= plab_word_size) &&
 274     may_throw_away_buffer(required_in_plab, plab_word_size)) {
 275 
 276     PLAB* alloc_buf = alloc_buffer(dest);
 277     alloc_buf->retire();
 278 
 279     size_t actual_plab_size = 0;
 280     HeapWord* buf = _allocator->par_allocate_during_gc(dest,
 281                                                        required_in_plab,
 282                                                        plab_word_size,
 283                                                        &actual_plab_size);
 284 
 285     assert(buf == NULL || ((actual_plab_size >= required_in_plab) && (actual_plab_size <= plab_word_size)),
 286            "Requested at minimum " SIZE_FORMAT ", desired " SIZE_FORMAT " words, but got " SIZE_FORMAT " at " PTR_FORMAT,
 287            required_in_plab, plab_word_size, actual_plab_size, p2i(buf));
 288 
 289     if (buf != NULL) {
 290       alloc_buf->set_buf(buf, actual_plab_size);
 291 
 292       HeapWord* const obj = alloc_buf->allocate(word_sz);
 293       assert(obj != NULL, "PLAB should have been big enough, tried to allocate "
 294                           SIZE_FORMAT " requiring " SIZE_FORMAT " PLAB size " SIZE_FORMAT,
 295                           word_sz, required_in_plab, plab_word_size);
 296       return obj;
 297     }
 298     // Otherwise.
 299     *plab_refill_failed = true;
 300   }
 301   // Try direct allocation.
 302   HeapWord* result = _allocator->par_allocate_during_gc(dest, word_sz);
 303   if (result != NULL) {
 304     _direct_allocated[dest.value()] += word_sz;
 305   }
 306   return result;
 307 }
 308 
 309 void G1PLABAllocator::undo_allocation(InCSetState dest, HeapWord* obj, size_t word_sz) {
 310   alloc_buffer(dest)->undo_allocation(obj, word_sz);
 311 }
 312 
 313 void G1PLABAllocator::flush_and_retire_stats() {
 314   for (uint state = 0; state < InCSetState::Num; state++) {
 315     PLAB* const buf = _alloc_buffers[state];
 316     if (buf != NULL) {
 317       G1EvacStats* stats = _g1h->alloc_buffer_stats(state);
 318       buf->flush_and_retire_stats(stats);
 319       stats->add_direct_allocated(_direct_allocated[state]);
 320       _direct_allocated[state] = 0;
 321     }
 322   }
 323 }
 324 
 325 void G1PLABAllocator::waste(size_t& wasted, size_t& undo_wasted) {
 326   wasted = 0;
 327   undo_wasted = 0;
 328   for (uint state = 0; state < InCSetState::Num; state++) {
 329     PLAB * const buf = _alloc_buffers[state];
 330     if (buf != NULL) {
 331       wasted += buf->waste();
 332       undo_wasted += buf->undo_waste();
 333     }
 334   }
 335 }
 336 
 337 bool G1ArchiveAllocator::_archive_check_enabled = false;
 338 G1ArchiveRegionMap G1ArchiveAllocator::_closed_archive_region_map;
 339 G1ArchiveRegionMap G1ArchiveAllocator::_open_archive_region_map;
 340 
 341 G1ArchiveAllocator* G1ArchiveAllocator::create_allocator(G1CollectedHeap* g1h, bool open) {
 342   // Create the archive allocator, and also enable archive object checking
 343   // in mark-sweep, since we will be creating archive regions.
 344   G1ArchiveAllocator* result =  new G1ArchiveAllocator(g1h, open);
 345   enable_archive_object_check();
 346   return result;
 347 }
 348 
 349 bool G1ArchiveAllocator::alloc_new_region() {
 350   // Allocate the highest free region in the reserved heap,
 351   // and add it to our list of allocated regions. It is marked
 352   // archive and added to the old set.
 353   HeapRegion* hr = _g1h->alloc_highest_free_region();
 354   if (hr == NULL) {
 355     return false;
 356   }
 357   assert(hr->is_empty(), "expected empty region (index %u)", hr->hrm_index());
 358   if (_open) {
 359     hr->set_open_archive();
 360   } else {
 361     hr->set_closed_archive();
 362   }
 363   _g1h->g1_policy()->remset_tracker()->update_at_allocate(hr);
 364   _g1h->archive_set_add(hr);
 365   _g1h->hr_printer()->alloc(hr);
 366   _allocated_regions.append(hr);
 367   _allocation_region = hr;
 368 
 369   // Set up _bottom and _max to begin allocating in the lowest
 370   // min_region_size'd chunk of the allocated G1 region.
 371   _bottom = hr->bottom();
 372   _max = _bottom + HeapRegion::min_region_size_in_words();
 373 
 374   // Tell mark-sweep that objects in this region are not to be marked.
 375   set_range_archive(MemRegion(_bottom, HeapRegion::GrainWords), _open);
 376 
 377   // Since we've modified the old set, call update_sizes.
 378   _g1h->g1mm()->update_sizes();
 379   return true;
 380 }
 381 
 382 HeapWord* G1ArchiveAllocator::archive_mem_allocate(size_t word_size) {
 383   assert(word_size != 0, "size must not be zero");
 384   if (_allocation_region == NULL) {
 385     if (!alloc_new_region()) {
 386       return NULL;
 387     }
 388   }
 389   HeapWord* old_top = _allocation_region->top();
 390   assert(_bottom >= _allocation_region->bottom(),
 391          "inconsistent allocation state: " PTR_FORMAT " < " PTR_FORMAT,
 392          p2i(_bottom), p2i(_allocation_region->bottom()));
 393   assert(_max <= _allocation_region->end(),
 394          "inconsistent allocation state: " PTR_FORMAT " > " PTR_FORMAT,
 395          p2i(_max), p2i(_allocation_region->end()));
 396   assert(_bottom <= old_top && old_top <= _max,
 397          "inconsistent allocation state: expected "
 398          PTR_FORMAT " <= " PTR_FORMAT " <= " PTR_FORMAT,
 399          p2i(_bottom), p2i(old_top), p2i(_max));
 400 
 401   // Allocate the next word_size words in the current allocation chunk.
 402   // If allocation would cross the _max boundary, insert a filler and begin
 403   // at the base of the next min_region_size'd chunk. Also advance to the next
 404   // chunk if we don't yet cross the boundary, but the remainder would be too
 405   // small to fill.
 406   HeapWord* new_top = old_top + word_size;
 407   size_t remainder = pointer_delta(_max, new_top);
 408   if ((new_top > _max) ||
 409       ((new_top < _max) && (remainder < CollectedHeap::min_fill_size()))) {
 410     if (old_top != _max) {
 411       size_t fill_size = pointer_delta(_max, old_top);
 412       CollectedHeap::fill_with_object(old_top, fill_size);
 413       _summary_bytes_used += fill_size * HeapWordSize;
 414     }
 415     _allocation_region->set_top(_max);
 416     old_top = _bottom = _max;
 417 
 418     // Check if we've just used up the last min_region_size'd chunk
 419     // in the current region, and if so, allocate a new one.
 420     if (_bottom != _allocation_region->end()) {
 421       _max = _bottom + HeapRegion::min_region_size_in_words();
 422     } else {
 423       if (!alloc_new_region()) {
 424         return NULL;
 425       }
 426       old_top = _allocation_region->bottom();
 427     }
 428   }
 429   _allocation_region->set_top(old_top + word_size);
 430   _summary_bytes_used += word_size * HeapWordSize;
 431 
 432   return old_top;
 433 }
 434 
 435 void G1ArchiveAllocator::complete_archive(GrowableArray<MemRegion>* ranges,
 436                                           size_t end_alignment_in_bytes) {
 437   assert((end_alignment_in_bytes >> LogHeapWordSize) < HeapRegion::min_region_size_in_words(),
 438          "alignment " SIZE_FORMAT " too large", end_alignment_in_bytes);
 439   assert(is_aligned(end_alignment_in_bytes, HeapWordSize),
 440          "alignment " SIZE_FORMAT " is not HeapWord (%u) aligned", end_alignment_in_bytes, HeapWordSize);
 441 
 442   // If we've allocated nothing, simply return.
 443   if (_allocation_region == NULL) {
 444     return;
 445   }
 446 
 447   // If an end alignment was requested, insert filler objects.
 448   if (end_alignment_in_bytes != 0) {
 449     HeapWord* currtop = _allocation_region->top();
 450     HeapWord* newtop = align_up(currtop, end_alignment_in_bytes);
 451     size_t fill_size = pointer_delta(newtop, currtop);
 452     if (fill_size != 0) {
 453       if (fill_size < CollectedHeap::min_fill_size()) {
 454         // If the required fill is smaller than we can represent,
 455         // bump up to the next aligned address. We know we won't exceed the current
 456         // region boundary because the max supported alignment is smaller than the min
 457         // region size, and because the allocation code never leaves space smaller than
 458         // the min_fill_size at the top of the current allocation region.
 459         newtop = align_up(currtop + CollectedHeap::min_fill_size(),
 460                           end_alignment_in_bytes);
 461         fill_size = pointer_delta(newtop, currtop);
 462       }
 463       HeapWord* fill = archive_mem_allocate(fill_size);
 464       CollectedHeap::fill_with_objects(fill, fill_size);
 465     }
 466   }
 467 
 468   // Loop through the allocated regions, and create MemRegions summarizing
 469   // the allocated address range, combining contiguous ranges. Add the
 470   // MemRegions to the GrowableArray provided by the caller.
 471   int index = _allocated_regions.length() - 1;
 472   assert(_allocated_regions.at(index) == _allocation_region,
 473          "expected region %u at end of array, found %u",
 474          _allocation_region->hrm_index(), _allocated_regions.at(index)->hrm_index());
 475   HeapWord* base_address = _allocation_region->bottom();
 476   HeapWord* top = base_address;
 477 
 478   while (index >= 0) {
 479     HeapRegion* next = _allocated_regions.at(index);
 480     HeapWord* new_base = next->bottom();
 481     HeapWord* new_top = next->top();
 482     if (new_base != top) {
 483       ranges->append(MemRegion(base_address, pointer_delta(top, base_address)));
 484       base_address = new_base;
 485     }
 486     top = new_top;
 487     index = index - 1;
 488   }
 489 
 490   assert(top != base_address, "zero-sized range, address " PTR_FORMAT, p2i(base_address));
 491   ranges->append(MemRegion(base_address, pointer_delta(top, base_address)));
 492   _allocated_regions.clear();
 493   _allocation_region = NULL;
 494 };