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