1 /*
   2  * Copyright (c) 2001, 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 "classfile/metadataOnStackMark.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "gc/g1/bufferingOopClosure.hpp"
  31 #include "gc/g1/concurrentG1Refine.hpp"
  32 #include "gc/g1/concurrentG1RefineThread.hpp"
  33 #include "gc/g1/concurrentMarkThread.inline.hpp"
  34 #include "gc/g1/g1AllocRegion.inline.hpp"
  35 #include "gc/g1/g1CollectedHeap.inline.hpp"
  36 #include "gc/g1/g1CollectorPolicy.hpp"
  37 #include "gc/g1/g1CollectorState.hpp"
  38 #include "gc/g1/g1ErgoVerbose.hpp"
  39 #include "gc/g1/g1EvacFailure.hpp"
  40 #include "gc/g1/g1GCPhaseTimes.hpp"
  41 #include "gc/g1/g1Log.hpp"
  42 #include "gc/g1/g1MarkSweep.hpp"
  43 #include "gc/g1/g1OopClosures.inline.hpp"
  44 #include "gc/g1/g1ParScanThreadState.inline.hpp"
  45 #include "gc/g1/g1RegionToSpaceMapper.hpp"
  46 #include "gc/g1/g1RemSet.inline.hpp"
  47 #include "gc/g1/g1RootProcessor.hpp"
  48 #include "gc/g1/g1StringDedup.hpp"
  49 #include "gc/g1/g1YCTypes.hpp"
  50 #include "gc/g1/heapRegion.inline.hpp"
  51 #include "gc/g1/heapRegionRemSet.hpp"
  52 #include "gc/g1/heapRegionSet.inline.hpp"
  53 #include "gc/g1/suspendibleThreadSet.hpp"
  54 #include "gc/g1/vm_operations_g1.hpp"
  55 #include "gc/shared/gcHeapSummary.hpp"
  56 #include "gc/shared/gcLocker.inline.hpp"
  57 #include "gc/shared/gcTimer.hpp"
  58 #include "gc/shared/gcTrace.hpp"
  59 #include "gc/shared/gcTraceTime.hpp"
  60 #include "gc/shared/generationSpec.hpp"
  61 #include "gc/shared/isGCActiveMark.hpp"
  62 #include "gc/shared/referenceProcessor.hpp"
  63 #include "gc/shared/taskqueue.inline.hpp"
  64 #include "memory/allocation.hpp"
  65 #include "memory/iterator.hpp"
  66 #include "oops/oop.inline.hpp"
  67 #include "runtime/atomic.inline.hpp"
  68 #include "runtime/globalSynchronizer.hpp"
  69 #include "runtime/orderAccess.inline.hpp"
  70 #include "runtime/vmThread.hpp"
  71 #include "utilities/globalDefinitions.hpp"
  72 #include "utilities/stack.inline.hpp"
  73 
  74 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
  75 
  76 // turn it on so that the contents of the young list (scan-only /
  77 // to-be-collected) are printed at "strategic" points before / during
  78 // / after the collection --- this is useful for debugging
  79 #define YOUNG_LIST_VERBOSE 0
  80 // CURRENT STATUS
  81 // This file is under construction.  Search for "FIXME".
  82 
  83 // INVARIANTS/NOTES
  84 //
  85 // All allocation activity covered by the G1CollectedHeap interface is
  86 // serialized by acquiring the HeapLock.  This happens in mem_allocate
  87 // and allocate_new_tlab, which are the "entry" points to the
  88 // allocation code from the rest of the JVM.  (Note that this does not
  89 // apply to TLAB allocation, which is not part of this interface: it
  90 // is done by clients of this interface.)
  91 
  92 // Local to this file.
  93 bool RefineCardTableEntryClosure::do_card_ptr(jbyte* card_ptr, uint worker_i) {
  94   bool oops_into_cset = G1CollectedHeap::heap()->g1_rem_set()->refine_card(card_ptr, worker_i, false);
  95   // This path is executed by the concurrent refine or mutator threads,
  96   // concurrently, and so we do not care if card_ptr contains references
  97   // that point into the collection set.
  98   assert(!oops_into_cset, "should be");
  99 
 100   // return false if caller should yield
 101   return !(G1CollectedHeap::heap()->refine_cte_cl_concurrency() && SuspendibleThreadSet::should_yield());
 102 }
 103 
 104 CardBuffer::CardBuffer()
 105   : _next(NULL) {
 106   int size = BufferedRefineCardTableEntryClosure::buffer_size();
 107   _card_buffer = NEW_C_HEAP_ARRAY(jbyte*, size, mtGC);
 108   _mr_buffer = NEW_C_HEAP_ARRAY(MemRegion, size, mtGC);
 109   _gs = new SynchronizerObj<mtGC>();
 110   _misses = 0;
 111 }
 112 
 113 CardBuffer::~CardBuffer() {
 114   FREE_C_HEAP_ARRAY(jbyte*, _card_buffer);
 115   FREE_C_HEAP_ARRAY(MemRegion, _mr_buffer);
 116   delete _gs;
 117 }
 118 
 119 BufferedRefineCardTableEntryClosure::BufferedRefineCardTableEntryClosure()
 120   : _index(0), _g1h(G1CollectedHeap::heap()), _head_buffer(NULL), _tail_buffer(NULL),
 121     _current_buffer(NULL), _async_buffers(0) {
 122 }
 123 
 124 BufferedRefineCardTableEntryClosure::~BufferedRefineCardTableEntryClosure() {
 125   assert(_index == 0, "must flush refine card buffer");
 126   assert(_head_buffer == NULL && _tail_buffer == NULL, "must flush all async cards first");
 127   assert(_async_buffers == 0, "must flush all async cards first");
 128   if (_current_buffer) delete _current_buffer;
 129 }
 130 
 131 bool BufferedRefineCardTableEntryClosure::do_card_ptr(jbyte *card_ptr, uint worker_i) {
 132   _worker_i = worker_i;
 133   if (_index == buffer_size()) soft_flush();
 134   if (_current_buffer == NULL) _current_buffer = new CardBuffer();
 135   _current_buffer->_card_buffer[_index++] = card_ptr;
 136 
 137   bool should_yield = _g1h->refine_cte_cl_concurrency() && SuspendibleThreadSet::should_yield();
 138   if (should_yield) flush_buffer();
 139 
 140   // return false if caller should yield
 141   return !should_yield;
 142 }
 143 
 144 void BufferedRefineCardTableEntryClosure::soft_flush() {
 145   general_flush(false);
 146 }
 147 
 148 // Procedures used to sort and join G1 cards during refinement
 149 static void quick_sort(jbyte **card_array, MemRegion *region_array, int left, int right);
 150 static int partition(jbyte **card_array, MemRegion *region_array, int left, int right);
 151 static int join_cards(jbyte **card_array, MemRegion *region_array, int length);
 152 
 153 static void quick_sort(jbyte **card_array, MemRegion *region_array, int left, int right) {
 154   int middle;
 155   if (left < right)
 156   {
 157     middle = partition(card_array, region_array, left, right);
 158     quick_sort(card_array, region_array, left, middle);
 159     quick_sort(card_array, region_array, middle + 1, right);
 160   }
 161 }
 162 
 163 static int partition(jbyte **card_array, MemRegion *region_array, int left, int right) {
 164   jbyte *card = card_array[left];
 165   int i = left;
 166   int j;
 167 
 168   for (j = left + 1; j < right; j++)
 169   {
 170     if (card_array[j] <= card)
 171     {
 172       i = i + 1;
 173       swap(card_array[i], card_array[j]);
 174       swap(region_array[i], region_array[j]);
 175     }
 176   }
 177 
 178   swap(card_array[i], card_array[left]);
 179   swap(region_array[i], region_array[left]);
 180   return i;
 181 }
 182 
 183 static int join_cards(jbyte **card_array, MemRegion *region_array, int length) {
 184   G1CollectedHeap *g1h = G1CollectedHeap::heap();
 185   jbyte *prev_card = NULL;
 186   HeapRegion *prev_hr = NULL;
 187   int insert_head = 0;
 188   for (int i = 0; i < length; i++) {
 189     jbyte *card = card_array[i];
 190 
 191     if (*card == CardTableModRefBS::clean_card_val()) {
 192       HeapRegion *hr = g1h->heap_region_containing_raw(region_array[i].start());
 193       if (card == prev_card + 1 && hr == prev_hr) {
 194         MemRegion insert_region = region_array[insert_head - 1];
 195         region_array[insert_head - 1] = MemRegion(insert_region.start(), region_array[i].end());
 196       } else {
 197         card_array[insert_head] = card;
 198         region_array[insert_head] = region_array[i];
 199         insert_head++;
 200       }
 201       prev_hr = hr;
 202     }
 203 
 204     prev_card = card;
 205   }
 206 
 207   return insert_head;
 208 }
 209 
 210 int BufferedRefineCardTableEntryClosure::buffer_size() {
 211   return (int)G1UpdateBufferSize;
 212 }
 213 
 214 void BufferedRefineCardTableEntryClosure::flush_buffer() {
 215   general_flush(true);
 216 }
 217 
 218 // Returns true if it needs post sync
 219 bool BufferedRefineCardTableEntryClosure::pre_sync(CardBuffer *buffer, bool hard) {
 220   // 1. Clean all cards in the batch.
 221   G1RemSet *g1rs = G1CollectedHeap::heap()->g1_rem_set();
 222   int needs_processing = 0;
 223 
 224   jbyte    **const card_buffer = buffer->_card_buffer;
 225   MemRegion *const mr_buffer   = buffer->_mr_buffer;
 226   const int length = buffer->_length;
 227 
 228   for (int i = 0; i < length; i++) {
 229     if (g1rs->clean_card(card_buffer[i], _worker_i, mr_buffer[i])) {
 230       card_buffer[needs_processing] = card_buffer[i];
 231       mr_buffer[needs_processing] = mr_buffer[i];
 232       needs_processing++;
 233     }
 234   }
 235   buffer->_length = needs_processing;
 236 
 237   if (needs_processing == 0) {
 238     if (hard) {
 239       // If we are forced to finish scanning, we must serialize stores anyway.
 240       OrderAccess::storeload();
 241       if (G1ElideMembar) {
 242         buffer->_gs->start_synchronizing();
 243       }
 244     }
 245     return false;
 246   }
 247 
 248   OrderAccess::storeload();
 249   if (G1ElideMembar) {
 250     buffer->_gs->start_synchronizing();
 251   }
 252 
 253   // 2. Sort the cards
 254   quick_sort(buffer->_card_buffer, buffer->_mr_buffer, 0, buffer->_length);
 255 
 256   return true;
 257 }
 258 
 259 bool BufferedRefineCardTableEntryClosure::sync(CardBuffer *buffer, bool hard) {
 260   if (!G1ElideMembar) return true;
 261 
 262   bool success = buffer->_gs->try_synchronize();
 263   if (hard) {
 264     if (!success) {
 265       buffer->_gs->maximize_urgency();
 266       buffer->_gs->synchronize();
 267     }
 268     return true;
 269   } else {
 270     return success;
 271   }
 272 }
 273 
 274 void BufferedRefineCardTableEntryClosure::post_sync(CardBuffer *buffer) {
 275   const int length = buffer->_length;
 276 
 277   const int card_batch_size = 16;
 278   jbyte **current_card = buffer->_card_buffer;
 279   MemRegion *current_region = buffer->_mr_buffer;
 280 
 281   const uintx interval = PrefetchScanIntervalInBytes * 2;
 282 
 283   G1RemSet *g1rs = G1CollectedHeap::heap()->g1_rem_set();
 284 
 285   // 3. Batch 16 cards at a time
 286 
 287   for (int j = 0; j < length; j += card_batch_size) {
 288     // 4. Join consecutive cards together and prefetch next card
 289     int batch = MIN2((length - j), card_batch_size);
 290     batch = join_cards(current_card, current_region, batch);
 291 
 292     jbyte dirty_card_val = CardTableModRefBS::dirty_card_val();
 293     jbyte *end_card;
 294     HeapWord *end_prefetch;
 295 
 296     if (j + card_batch_size < length) {
 297       end_prefetch = current_region[card_batch_size].start();
 298       end_card = current_card[card_batch_size];
 299     } else {
 300       end_card = &dirty_card_val;
 301     }
 302 
 303     MemRegion *region_end = current_region + batch;
 304     jbyte** batch_card;
 305     MemRegion* batch_region;
 306 
 307     for (batch_card = current_card, batch_region = current_region; batch_region != region_end; batch_card++) {
 308       jbyte *card = *batch_card;
 309       MemRegion mr = *batch_region;
 310       MemRegion *next_region = batch_region + 1;
 311 
 312       if (next_region != region_end) {
 313         MemRegion next_region_val = *next_region;
 314         // Prefetch interval in batch
 315         Prefetch::read(next_region_val.start(), next_region_val.byte_size());
 316       } else if (*end_card == CardTableModRefBS::clean_card_val()) {
 317         // Prefetch broken interval to next batch
 318         Prefetch::read(end_prefetch, interval);
 319       }
 320 
 321       g1rs->refine_card_buffered(card, _worker_i, /*check_for_cset_refs*/ false, mr);
 322 
 323       batch_region = next_region;
 324     }
 325 
 326     current_region += card_batch_size;
 327     current_card += card_batch_size;
 328   }
 329 }
 330 
 331 void BufferedRefineCardTableEntryClosure::general_flush(bool hard) {
 332   if (_index == 0) {
 333     assert(hard, "invariant");
 334     if (_async_buffers == 0) return;
 335   }
 336 
 337   // 1. Start asynchronous synchronization for the current buffer
 338   if (_current_buffer == NULL) _current_buffer = new CardBuffer();
 339   _current_buffer->_length = _index;
 340   if (pre_sync(_current_buffer, hard) || hard) {
 341     // append async buffer
 342     CardBuffer *tail = _tail_buffer;
 343     if (tail != NULL) tail->_next = _current_buffer;
 344     _tail_buffer = _current_buffer;
 345     if (_head_buffer == NULL) _head_buffer = _current_buffer;
 346     if (hard) sync(_current_buffer, hard);
 347     _current_buffer = NULL;
 348     _async_buffers++;
 349   }
 350 
 351   _index = 0;
 352 
 353   // 2. Process old batches that have been cleaned but couldn't synchronize (async completion)
 354   CardBuffer *current = _head_buffer;
 355   bool check_sync = true;
 356   while (current != NULL) {
 357     if (hard || sync(current, hard)) {
 358       post_sync(current);
 359       CardBuffer *next = current->_next;
 360       _head_buffer = next;
 361       if (next == NULL) _tail_buffer = NULL;
 362       delete current;
 363       current = next;
 364       _async_buffers--;
 365     } else {
 366       current->_misses++;
 367       if (_async_buffers > 4 && current->_misses > 2
 368           || _async_buffers > 8 && current->_misses > 4
 369           || _async_buffers > 16 && current->_misses > 6) {
 370         current->_gs->increase_urgency();
 371       }
 372       break;
 373     }
 374   }
 375 }
 376 
 377 
 378 class RedirtyLoggedCardTableEntryClosure : public CardTableEntryClosure {
 379  private:
 380   size_t _num_processed;
 381 
 382  public:
 383   RedirtyLoggedCardTableEntryClosure() : CardTableEntryClosure(), _num_processed(0) { }
 384 
 385   bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
 386     *card_ptr = CardTableModRefBS::dirty_card_val();
 387     _num_processed++;
 388     return true;
 389   }
 390 
 391   size_t num_processed() const { return _num_processed; }
 392 };
 393 
 394 YoungList::YoungList(G1CollectedHeap* g1h) :
 395     _g1h(g1h), _head(NULL), _length(0), _last_sampled_rs_lengths(0),
 396     _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0) {
 397   guarantee(check_list_empty(false), "just making sure...");
 398 }
 399 
 400 void YoungList::push_region(HeapRegion *hr) {
 401   assert(!hr->is_young(), "should not already be young");
 402   assert(hr->get_next_young_region() == NULL, "cause it should!");
 403 
 404   hr->set_next_young_region(_head);
 405   _head = hr;
 406 
 407   _g1h->g1_policy()->set_region_eden(hr, (int) _length);
 408   ++_length;
 409 }
 410 
 411 void YoungList::add_survivor_region(HeapRegion* hr) {
 412   assert(hr->is_survivor(), "should be flagged as survivor region");
 413   assert(hr->get_next_young_region() == NULL, "cause it should!");
 414 
 415   hr->set_next_young_region(_survivor_head);
 416   if (_survivor_head == NULL) {
 417     _survivor_tail = hr;
 418   }
 419   _survivor_head = hr;
 420   ++_survivor_length;
 421 }
 422 
 423 void YoungList::empty_list(HeapRegion* list) {
 424   while (list != NULL) {
 425     HeapRegion* next = list->get_next_young_region();
 426     list->set_next_young_region(NULL);
 427     list->uninstall_surv_rate_group();
 428     // This is called before a Full GC and all the non-empty /
 429     // non-humongous regions at the end of the Full GC will end up as
 430     // old anyway.
 431     list->set_old();
 432     list = next;
 433   }
 434 }
 435 
 436 void YoungList::empty_list() {
 437   assert(check_list_well_formed(), "young list should be well formed");
 438 
 439   empty_list(_head);
 440   _head = NULL;
 441   _length = 0;
 442 
 443   empty_list(_survivor_head);
 444   _survivor_head = NULL;
 445   _survivor_tail = NULL;
 446   _survivor_length = 0;
 447 
 448   _last_sampled_rs_lengths = 0;
 449 
 450   assert(check_list_empty(false), "just making sure...");
 451 }
 452 
 453 bool YoungList::check_list_well_formed() {
 454   bool ret = true;
 455 
 456   uint length = 0;
 457   HeapRegion* curr = _head;
 458   HeapRegion* last = NULL;
 459   while (curr != NULL) {
 460     if (!curr->is_young()) {
 461       gclog_or_tty->print_cr("### YOUNG REGION " PTR_FORMAT "-" PTR_FORMAT " "
 462                              "incorrectly tagged (y: %d, surv: %d)",
 463                              p2i(curr->bottom()), p2i(curr->end()),
 464                              curr->is_young(), curr->is_survivor());
 465       ret = false;
 466     }
 467     ++length;
 468     last = curr;
 469     curr = curr->get_next_young_region();
 470   }
 471   ret = ret && (length == _length);
 472 
 473   if (!ret) {
 474     gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
 475     gclog_or_tty->print_cr("###   list has %u entries, _length is %u",
 476                            length, _length);
 477   }
 478 
 479   return ret;
 480 }
 481 
 482 bool YoungList::check_list_empty(bool check_sample) {
 483   bool ret = true;
 484 
 485   if (_length != 0) {
 486     gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %u",
 487                   _length);
 488     ret = false;
 489   }
 490   if (check_sample && _last_sampled_rs_lengths != 0) {
 491     gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
 492     ret = false;
 493   }
 494   if (_head != NULL) {
 495     gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
 496     ret = false;
 497   }
 498   if (!ret) {
 499     gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
 500   }
 501 
 502   return ret;
 503 }
 504 
 505 void
 506 YoungList::rs_length_sampling_init() {
 507   _sampled_rs_lengths = 0;
 508   _curr               = _head;
 509 }
 510 
 511 bool
 512 YoungList::rs_length_sampling_more() {
 513   return _curr != NULL;
 514 }
 515 
 516 void
 517 YoungList::rs_length_sampling_next() {
 518   assert( _curr != NULL, "invariant" );
 519   size_t rs_length = _curr->rem_set()->occupied();
 520 
 521   _sampled_rs_lengths += rs_length;
 522 
 523   // The current region may not yet have been added to the
 524   // incremental collection set (it gets added when it is
 525   // retired as the current allocation region).
 526   if (_curr->in_collection_set()) {
 527     // Update the collection set policy information for this region
 528     _g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);
 529   }
 530 
 531   _curr = _curr->get_next_young_region();
 532   if (_curr == NULL) {
 533     _last_sampled_rs_lengths = _sampled_rs_lengths;
 534     // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
 535   }
 536 }
 537 
 538 void
 539 YoungList::reset_auxilary_lists() {
 540   guarantee( is_empty(), "young list should be empty" );
 541   assert(check_list_well_formed(), "young list should be well formed");
 542 
 543   // Add survivor regions to SurvRateGroup.
 544   _g1h->g1_policy()->note_start_adding_survivor_regions();
 545   _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
 546 
 547   int young_index_in_cset = 0;
 548   for (HeapRegion* curr = _survivor_head;
 549        curr != NULL;
 550        curr = curr->get_next_young_region()) {
 551     _g1h->g1_policy()->set_region_survivor(curr, young_index_in_cset);
 552 
 553     // The region is a non-empty survivor so let's add it to
 554     // the incremental collection set for the next evacuation
 555     // pause.
 556     _g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);
 557     young_index_in_cset += 1;
 558   }
 559   assert((uint) young_index_in_cset == _survivor_length, "post-condition");
 560   _g1h->g1_policy()->note_stop_adding_survivor_regions();
 561 
 562   _head   = _survivor_head;
 563   _length = _survivor_length;
 564   if (_survivor_head != NULL) {
 565     assert(_survivor_tail != NULL, "cause it shouldn't be");
 566     assert(_survivor_length > 0, "invariant");
 567     _survivor_tail->set_next_young_region(NULL);
 568   }
 569 
 570   // Don't clear the survivor list handles until the start of
 571   // the next evacuation pause - we need it in order to re-tag
 572   // the survivor regions from this evacuation pause as 'young'
 573   // at the start of the next.
 574 
 575   _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
 576 
 577   assert(check_list_well_formed(), "young list should be well formed");
 578 }
 579 
 580 void YoungList::print() {
 581   HeapRegion* lists[] = {_head,   _survivor_head};
 582   const char* names[] = {"YOUNG", "SURVIVOR"};
 583 
 584   for (uint list = 0; list < ARRAY_SIZE(lists); ++list) {
 585     gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
 586     HeapRegion *curr = lists[list];
 587     if (curr == NULL)
 588       gclog_or_tty->print_cr("  empty");
 589     while (curr != NULL) {
 590       gclog_or_tty->print_cr("  " HR_FORMAT ", P: " PTR_FORMAT ", N: " PTR_FORMAT ", age: %4d",
 591                              HR_FORMAT_PARAMS(curr),
 592                              p2i(curr->prev_top_at_mark_start()),
 593                              p2i(curr->next_top_at_mark_start()),
 594                              curr->age_in_surv_rate_group_cond());
 595       curr = curr->get_next_young_region();
 596     }
 597   }
 598 
 599   gclog_or_tty->cr();
 600 }
 601 
 602 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
 603   HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);
 604 }
 605 
 606 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {
 607   // The from card cache is not the memory that is actually committed. So we cannot
 608   // take advantage of the zero_filled parameter.
 609   reset_from_card_cache(start_idx, num_regions);
 610 }
 611 
 612 void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)
 613 {
 614   // Claim the right to put the region on the dirty cards region list
 615   // by installing a self pointer.
 616   HeapRegion* next = hr->get_next_dirty_cards_region();
 617   if (next == NULL) {
 618     HeapRegion* res = (HeapRegion*)
 619       Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),
 620                           NULL);
 621     if (res == NULL) {
 622       HeapRegion* head;
 623       do {
 624         // Put the region to the dirty cards region list.
 625         head = _dirty_cards_region_list;
 626         next = (HeapRegion*)
 627           Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);
 628         if (next == head) {
 629           assert(hr->get_next_dirty_cards_region() == hr,
 630                  "hr->get_next_dirty_cards_region() != hr");
 631           if (next == NULL) {
 632             // The last region in the list points to itself.
 633             hr->set_next_dirty_cards_region(hr);
 634           } else {
 635             hr->set_next_dirty_cards_region(next);
 636           }
 637         }
 638       } while (next != head);
 639     }
 640   }
 641 }
 642 
 643 HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
 644 {
 645   HeapRegion* head;
 646   HeapRegion* hr;
 647   do {
 648     head = _dirty_cards_region_list;
 649     if (head == NULL) {
 650       return NULL;
 651     }
 652     HeapRegion* new_head = head->get_next_dirty_cards_region();
 653     if (head == new_head) {
 654       // The last region.
 655       new_head = NULL;
 656     }
 657     hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,
 658                                           head);
 659   } while (hr != head);
 660   assert(hr != NULL, "invariant");
 661   hr->set_next_dirty_cards_region(NULL);
 662   return hr;
 663 }
 664 
 665 // Returns true if the reference points to an object that
 666 // can move in an incremental collection.
 667 bool G1CollectedHeap::is_scavengable(const void* p) {
 668   HeapRegion* hr = heap_region_containing(p);
 669   return !hr->is_pinned();
 670 }
 671 
 672 // Private methods.
 673 
 674 HeapRegion*
 675 G1CollectedHeap::new_region_try_secondary_free_list(bool is_old) {
 676   MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
 677   while (!_secondary_free_list.is_empty() || free_regions_coming()) {
 678     if (!_secondary_free_list.is_empty()) {
 679       if (G1ConcRegionFreeingVerbose) {
 680         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 681                                "secondary_free_list has %u entries",
 682                                _secondary_free_list.length());
 683       }
 684       // It looks as if there are free regions available on the
 685       // secondary_free_list. Let's move them to the free_list and try
 686       // again to allocate from it.
 687       append_secondary_free_list();
 688 
 689       assert(_hrm.num_free_regions() > 0, "if the secondary_free_list was not "
 690              "empty we should have moved at least one entry to the free_list");
 691       HeapRegion* res = _hrm.allocate_free_region(is_old);
 692       if (G1ConcRegionFreeingVerbose) {
 693         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 694                                "allocated " HR_FORMAT " from secondary_free_list",
 695                                HR_FORMAT_PARAMS(res));
 696       }
 697       return res;
 698     }
 699 
 700     // Wait here until we get notified either when (a) there are no
 701     // more free regions coming or (b) some regions have been moved on
 702     // the secondary_free_list.
 703     SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
 704   }
 705 
 706   if (G1ConcRegionFreeingVerbose) {
 707     gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 708                            "could not allocate from secondary_free_list");
 709   }
 710   return NULL;
 711 }
 712 
 713 HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool is_old, bool do_expand) {
 714   assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords,
 715          "the only time we use this to allocate a humongous region is "
 716          "when we are allocating a single humongous region");
 717 
 718   HeapRegion* res;
 719   if (G1StressConcRegionFreeing) {
 720     if (!_secondary_free_list.is_empty()) {
 721       if (G1ConcRegionFreeingVerbose) {
 722         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 723                                "forced to look at the secondary_free_list");
 724       }
 725       res = new_region_try_secondary_free_list(is_old);
 726       if (res != NULL) {
 727         return res;
 728       }
 729     }
 730   }
 731 
 732   res = _hrm.allocate_free_region(is_old);
 733 
 734   if (res == NULL) {
 735     if (G1ConcRegionFreeingVerbose) {
 736       gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
 737                              "res == NULL, trying the secondary_free_list");
 738     }
 739     res = new_region_try_secondary_free_list(is_old);
 740   }
 741   if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
 742     // Currently, only attempts to allocate GC alloc regions set
 743     // do_expand to true. So, we should only reach here during a
 744     // safepoint. If this assumption changes we might have to
 745     // reconsider the use of _expand_heap_after_alloc_failure.
 746     assert(SafepointSynchronize::is_at_safepoint(), "invariant");
 747 
 748     ergo_verbose1(ErgoHeapSizing,
 749                   "attempt heap expansion",
 750                   ergo_format_reason("region allocation request failed")
 751                   ergo_format_byte("allocation request"),
 752                   word_size * HeapWordSize);
 753     if (expand(word_size * HeapWordSize)) {
 754       // Given that expand() succeeded in expanding the heap, and we
 755       // always expand the heap by an amount aligned to the heap
 756       // region size, the free list should in theory not be empty.
 757       // In either case allocate_free_region() will check for NULL.
 758       res = _hrm.allocate_free_region(is_old);
 759     } else {
 760       _expand_heap_after_alloc_failure = false;
 761     }
 762   }
 763   return res;
 764 }
 765 
 766 HeapWord*
 767 G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first,
 768                                                            uint num_regions,
 769                                                            size_t word_size,
 770                                                            AllocationContext_t context) {
 771   assert(first != G1_NO_HRM_INDEX, "pre-condition");
 772   assert(is_humongous(word_size), "word_size should be humongous");
 773   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
 774 
 775   // Index of last region in the series + 1.
 776   uint last = first + num_regions;
 777 
 778   // We need to initialize the region(s) we just discovered. This is
 779   // a bit tricky given that it can happen concurrently with
 780   // refinement threads refining cards on these regions and
 781   // potentially wanting to refine the BOT as they are scanning
 782   // those cards (this can happen shortly after a cleanup; see CR
 783   // 6991377). So we have to set up the region(s) carefully and in
 784   // a specific order.
 785 
 786   // The word size sum of all the regions we will allocate.
 787   size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
 788   assert(word_size <= word_size_sum, "sanity");
 789 
 790   // This will be the "starts humongous" region.
 791   HeapRegion* first_hr = region_at(first);
 792   // The header of the new object will be placed at the bottom of
 793   // the first region.
 794   HeapWord* new_obj = first_hr->bottom();
 795   // This will be the new end of the first region in the series that
 796   // should also match the end of the last region in the series.
 797   HeapWord* new_end = new_obj + word_size_sum;
 798   // This will be the new top of the first region that will reflect
 799   // this allocation.
 800   HeapWord* new_top = new_obj + word_size;
 801 
 802   // First, we need to zero the header of the space that we will be
 803   // allocating. When we update top further down, some refinement
 804   // threads might try to scan the region. By zeroing the header we
 805   // ensure that any thread that will try to scan the region will
 806   // come across the zero klass word and bail out.
 807   //
 808   // NOTE: It would not have been correct to have used
 809   // CollectedHeap::fill_with_object() and make the space look like
 810   // an int array. The thread that is doing the allocation will
 811   // later update the object header to a potentially different array
 812   // type and, for a very short period of time, the klass and length
 813   // fields will be inconsistent. This could cause a refinement
 814   // thread to calculate the object size incorrectly.
 815   Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
 816 
 817   // We will set up the first region as "starts humongous". This
 818   // will also update the BOT covering all the regions to reflect
 819   // that there is a single object that starts at the bottom of the
 820   // first region.
 821   first_hr->set_starts_humongous(new_top, new_end);
 822   first_hr->set_allocation_context(context);
 823   // Then, if there are any, we will set up the "continues
 824   // humongous" regions.
 825   HeapRegion* hr = NULL;
 826   for (uint i = first + 1; i < last; ++i) {
 827     hr = region_at(i);
 828     hr->set_continues_humongous(first_hr);
 829     hr->set_allocation_context(context);
 830   }
 831   // If we have "continues humongous" regions (hr != NULL), then the
 832   // end of the last one should match new_end.
 833   assert(hr == NULL || hr->end() == new_end, "sanity");
 834 
 835   // Up to this point no concurrent thread would have been able to
 836   // do any scanning on any region in this series. All the top
 837   // fields still point to bottom, so the intersection between
 838   // [bottom,top] and [card_start,card_end] will be empty. Before we
 839   // update the top fields, we'll do a storestore to make sure that
 840   // no thread sees the update to top before the zeroing of the
 841   // object header and the BOT initialization.
 842   OrderAccess::storestore();
 843 
 844   // Now that the BOT and the object header have been initialized,
 845   // we can update top of the "starts humongous" region.
 846   assert(first_hr->bottom() < new_top && new_top <= first_hr->end(),
 847          "new_top should be in this region");
 848   first_hr->set_top(new_top);
 849   if (_hr_printer.is_active()) {
 850     HeapWord* bottom = first_hr->bottom();
 851     HeapWord* end = first_hr->orig_end();
 852     if ((first + 1) == last) {
 853       // the series has a single humongous region
 854       _hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top);
 855     } else {
 856       // the series has more than one humongous regions
 857       _hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end);
 858     }
 859   }
 860 
 861   // Now, we will update the top fields of the "continues humongous"
 862   // regions. The reason we need to do this is that, otherwise,
 863   // these regions would look empty and this will confuse parts of
 864   // G1. For example, the code that looks for a consecutive number
 865   // of empty regions will consider them empty and try to
 866   // re-allocate them. We can extend is_empty() to also include
 867   // !is_continues_humongous(), but it is easier to just update the top
 868   // fields here. The way we set top for all regions (i.e., top ==
 869   // end for all regions but the last one, top == new_top for the
 870   // last one) is actually used when we will free up the humongous
 871   // region in free_humongous_region().
 872   hr = NULL;
 873   for (uint i = first + 1; i < last; ++i) {
 874     hr = region_at(i);
 875     if ((i + 1) == last) {
 876       // last continues humongous region
 877       assert(hr->bottom() < new_top && new_top <= hr->end(),
 878              "new_top should fall on this region");
 879       hr->set_top(new_top);
 880       _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top);
 881     } else {
 882       // not last one
 883       assert(new_top > hr->end(), "new_top should be above this region");
 884       hr->set_top(hr->end());
 885       _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end());
 886     }
 887   }
 888   // If we have continues humongous regions (hr != NULL), then the
 889   // end of the last one should match new_end and its top should
 890   // match new_top.
 891   assert(hr == NULL ||
 892          (hr->end() == new_end && hr->top() == new_top), "sanity");
 893   check_bitmaps("Humongous Region Allocation", first_hr);
 894 
 895   assert(first_hr->used() == word_size * HeapWordSize, "invariant");
 896   increase_used(first_hr->used());
 897   _humongous_set.add(first_hr);
 898 
 899   return new_obj;
 900 }
 901 
 902 // If could fit into free regions w/o expansion, try.
 903 // Otherwise, if can expand, do so.
 904 // Otherwise, if using ex regions might help, try with ex given back.
 905 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size, AllocationContext_t context) {
 906   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
 907 
 908   verify_region_sets_optional();
 909 
 910   uint first = G1_NO_HRM_INDEX;
 911   uint obj_regions = (uint)(align_size_up_(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords);
 912 
 913   if (obj_regions == 1) {
 914     // Only one region to allocate, try to use a fast path by directly allocating
 915     // from the free lists. Do not try to expand here, we will potentially do that
 916     // later.
 917     HeapRegion* hr = new_region(word_size, true /* is_old */, false /* do_expand */);
 918     if (hr != NULL) {
 919       first = hr->hrm_index();
 920     }
 921   } else {
 922     // We can't allocate humongous regions spanning more than one region while
 923     // cleanupComplete() is running, since some of the regions we find to be
 924     // empty might not yet be added to the free list. It is not straightforward
 925     // to know in which list they are on so that we can remove them. We only
 926     // need to do this if we need to allocate more than one region to satisfy the
 927     // current humongous allocation request. If we are only allocating one region
 928     // we use the one-region region allocation code (see above), that already
 929     // potentially waits for regions from the secondary free list.
 930     wait_while_free_regions_coming();
 931     append_secondary_free_list_if_not_empty_with_lock();
 932 
 933     // Policy: Try only empty regions (i.e. already committed first). Maybe we
 934     // are lucky enough to find some.
 935     first = _hrm.find_contiguous_only_empty(obj_regions);
 936     if (first != G1_NO_HRM_INDEX) {
 937       _hrm.allocate_free_regions_starting_at(first, obj_regions);
 938     }
 939   }
 940 
 941   if (first == G1_NO_HRM_INDEX) {
 942     // Policy: We could not find enough regions for the humongous object in the
 943     // free list. Look through the heap to find a mix of free and uncommitted regions.
 944     // If so, try expansion.
 945     first = _hrm.find_contiguous_empty_or_unavailable(obj_regions);
 946     if (first != G1_NO_HRM_INDEX) {
 947       // We found something. Make sure these regions are committed, i.e. expand
 948       // the heap. Alternatively we could do a defragmentation GC.
 949       ergo_verbose1(ErgoHeapSizing,
 950                     "attempt heap expansion",
 951                     ergo_format_reason("humongous allocation request failed")
 952                     ergo_format_byte("allocation request"),
 953                     word_size * HeapWordSize);
 954 
 955       _hrm.expand_at(first, obj_regions);
 956       g1_policy()->record_new_heap_size(num_regions());
 957 
 958 #ifdef ASSERT
 959       for (uint i = first; i < first + obj_regions; ++i) {
 960         HeapRegion* hr = region_at(i);
 961         assert(hr->is_free(), "sanity");
 962         assert(hr->is_empty(), "sanity");
 963         assert(is_on_master_free_list(hr), "sanity");
 964       }
 965 #endif
 966       _hrm.allocate_free_regions_starting_at(first, obj_regions);
 967     } else {
 968       // Policy: Potentially trigger a defragmentation GC.
 969     }
 970   }
 971 
 972   HeapWord* result = NULL;
 973   if (first != G1_NO_HRM_INDEX) {
 974     result = humongous_obj_allocate_initialize_regions(first, obj_regions,
 975                                                        word_size, context);
 976     assert(result != NULL, "it should always return a valid result");
 977 
 978     // A successful humongous object allocation changes the used space
 979     // information of the old generation so we need to recalculate the
 980     // sizes and update the jstat counters here.
 981     g1mm()->update_sizes();
 982   }
 983 
 984   verify_region_sets_optional();
 985 
 986   return result;
 987 }
 988 
 989 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {
 990   assert_heap_not_locked_and_not_at_safepoint();
 991   assert(!is_humongous(word_size), "we do not allow humongous TLABs");
 992 
 993   uint dummy_gc_count_before;
 994   uint dummy_gclocker_retry_count = 0;
 995   return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);
 996 }
 997 
 998 HeapWord*
 999 G1CollectedHeap::mem_allocate(size_t word_size,
1000                               bool*  gc_overhead_limit_was_exceeded) {
1001   assert_heap_not_locked_and_not_at_safepoint();
1002 
1003   // Loop until the allocation is satisfied, or unsatisfied after GC.
1004   for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
1005     uint gc_count_before;
1006 
1007     HeapWord* result = NULL;
1008     if (!is_humongous(word_size)) {
1009       result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);
1010     } else {
1011       result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);
1012     }
1013     if (result != NULL) {
1014       return result;
1015     }
1016 
1017     // Create the garbage collection operation...
1018     VM_G1CollectForAllocation op(gc_count_before, word_size);
1019     op.set_allocation_context(AllocationContext::current());
1020 
1021     // ...and get the VM thread to execute it.
1022     VMThread::execute(&op);
1023 
1024     if (op.prologue_succeeded() && op.pause_succeeded()) {
1025       // If the operation was successful we'll return the result even
1026       // if it is NULL. If the allocation attempt failed immediately
1027       // after a Full GC, it's unlikely we'll be able to allocate now.
1028       HeapWord* result = op.result();
1029       if (result != NULL && !is_humongous(word_size)) {
1030         // Allocations that take place on VM operations do not do any
1031         // card dirtying and we have to do it here. We only have to do
1032         // this for non-humongous allocations, though.
1033         dirty_young_block(result, word_size);
1034       }
1035       return result;
1036     } else {
1037       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
1038         return NULL;
1039       }
1040       assert(op.result() == NULL,
1041              "the result should be NULL if the VM op did not succeed");
1042     }
1043 
1044     // Give a warning if we seem to be looping forever.
1045     if ((QueuedAllocationWarningCount > 0) &&
1046         (try_count % QueuedAllocationWarningCount == 0)) {
1047       warning("G1CollectedHeap::mem_allocate retries %d times", try_count);
1048     }
1049   }
1050 
1051   ShouldNotReachHere();
1052   return NULL;
1053 }
1054 
1055 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
1056                                                    AllocationContext_t context,
1057                                                    uint* gc_count_before_ret,
1058                                                    uint* gclocker_retry_count_ret) {
1059   // Make sure you read the note in attempt_allocation_humongous().
1060 
1061   assert_heap_not_locked_and_not_at_safepoint();
1062   assert(!is_humongous(word_size), "attempt_allocation_slow() should not "
1063          "be called for humongous allocation requests");
1064 
1065   // We should only get here after the first-level allocation attempt
1066   // (attempt_allocation()) failed to allocate.
1067 
1068   // We will loop until a) we manage to successfully perform the
1069   // allocation or b) we successfully schedule a collection which
1070   // fails to perform the allocation. b) is the only case when we'll
1071   // return NULL.
1072   HeapWord* result = NULL;
1073   for (int try_count = 1; /* we'll return */; try_count += 1) {
1074     bool should_try_gc;
1075     uint gc_count_before;
1076 
1077     {
1078       MutexLockerEx x(Heap_lock);
1079       result = _allocator->mutator_alloc_region(context)->attempt_allocation_locked(word_size,
1080                                                                                     false /* bot_updates */);
1081       if (result != NULL) {
1082         return result;
1083       }
1084 
1085       // If we reach here, attempt_allocation_locked() above failed to
1086       // allocate a new region. So the mutator alloc region should be NULL.
1087       assert(_allocator->mutator_alloc_region(context)->get() == NULL, "only way to get here");
1088 
1089       if (GC_locker::is_active_and_needs_gc()) {
1090         if (g1_policy()->can_expand_young_list()) {
1091           // No need for an ergo verbose message here,
1092           // can_expand_young_list() does this when it returns true.
1093           result = _allocator->mutator_alloc_region(context)->attempt_allocation_force(word_size,
1094                                                                                        false /* bot_updates */);
1095           if (result != NULL) {
1096             return result;
1097           }
1098         }
1099         should_try_gc = false;
1100       } else {
1101         // The GCLocker may not be active but the GCLocker initiated
1102         // GC may not yet have been performed (GCLocker::needs_gc()
1103         // returns true). In this case we do not try this GC and
1104         // wait until the GCLocker initiated GC is performed, and
1105         // then retry the allocation.
1106         if (GC_locker::needs_gc()) {
1107           should_try_gc = false;
1108         } else {
1109           // Read the GC count while still holding the Heap_lock.
1110           gc_count_before = total_collections();
1111           should_try_gc = true;
1112         }
1113       }
1114     }
1115 
1116     if (should_try_gc) {
1117       bool succeeded;
1118       result = do_collection_pause(word_size, gc_count_before, &succeeded,
1119                                    GCCause::_g1_inc_collection_pause);
1120       if (result != NULL) {
1121         assert(succeeded, "only way to get back a non-NULL result");
1122         return result;
1123       }
1124 
1125       if (succeeded) {
1126         // If we get here we successfully scheduled a collection which
1127         // failed to allocate. No point in trying to allocate
1128         // further. We'll just return NULL.
1129         MutexLockerEx x(Heap_lock);
1130         *gc_count_before_ret = total_collections();
1131         return NULL;
1132       }
1133     } else {
1134       if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
1135         MutexLockerEx x(Heap_lock);
1136         *gc_count_before_ret = total_collections();
1137         return NULL;
1138       }
1139       // The GCLocker is either active or the GCLocker initiated
1140       // GC has not yet been performed. Stall until it is and
1141       // then retry the allocation.
1142       GC_locker::stall_until_clear();
1143       (*gclocker_retry_count_ret) += 1;
1144     }
1145 
1146     // We can reach here if we were unsuccessful in scheduling a
1147     // collection (because another thread beat us to it) or if we were
1148     // stalled due to the GC locker. In either can we should retry the
1149     // allocation attempt in case another thread successfully
1150     // performed a collection and reclaimed enough space. We do the
1151     // first attempt (without holding the Heap_lock) here and the
1152     // follow-on attempt will be at the start of the next loop
1153     // iteration (after taking the Heap_lock).
1154     result = _allocator->mutator_alloc_region(context)->attempt_allocation(word_size,
1155                                                                            false /* bot_updates */);
1156     if (result != NULL) {
1157       return result;
1158     }
1159 
1160     // Give a warning if we seem to be looping forever.
1161     if ((QueuedAllocationWarningCount > 0) &&
1162         (try_count % QueuedAllocationWarningCount == 0)) {
1163       warning("G1CollectedHeap::attempt_allocation_slow() "
1164               "retries %d times", try_count);
1165     }
1166   }
1167 
1168   ShouldNotReachHere();
1169   return NULL;
1170 }
1171 
1172 void G1CollectedHeap::begin_archive_alloc_range() {
1173   assert_at_safepoint(true /* should_be_vm_thread */);
1174   if (_archive_allocator == NULL) {
1175     _archive_allocator = G1ArchiveAllocator::create_allocator(this);
1176   }
1177 }
1178 
1179 bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {
1180   // Allocations in archive regions cannot be of a size that would be considered
1181   // humongous even for a minimum-sized region, because G1 region sizes/boundaries
1182   // may be different at archive-restore time.
1183   return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());
1184 }
1185 
1186 HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {
1187   assert_at_safepoint(true /* should_be_vm_thread */);
1188   assert(_archive_allocator != NULL, "_archive_allocator not initialized");
1189   if (is_archive_alloc_too_large(word_size)) {
1190     return NULL;
1191   }
1192   return _archive_allocator->archive_mem_allocate(word_size);
1193 }
1194 
1195 void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,
1196                                               size_t end_alignment_in_bytes) {
1197   assert_at_safepoint(true /* should_be_vm_thread */);
1198   assert(_archive_allocator != NULL, "_archive_allocator not initialized");
1199 
1200   // Call complete_archive to do the real work, filling in the MemRegion
1201   // array with the archive regions.
1202   _archive_allocator->complete_archive(ranges, end_alignment_in_bytes);
1203   delete _archive_allocator;
1204   _archive_allocator = NULL;
1205 }
1206 
1207 bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {
1208   assert(ranges != NULL, "MemRegion array NULL");
1209   assert(count != 0, "No MemRegions provided");
1210   MemRegion reserved = _hrm.reserved();
1211   for (size_t i = 0; i < count; i++) {
1212     if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {
1213       return false;
1214     }
1215   }
1216   return true;
1217 }
1218 
1219 bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges, size_t count) {
1220   assert(ranges != NULL, "MemRegion array NULL");
1221   assert(count != 0, "No MemRegions provided");
1222   MutexLockerEx x(Heap_lock);
1223 
1224   MemRegion reserved = _hrm.reserved();
1225   HeapWord* prev_last_addr = NULL;
1226   HeapRegion* prev_last_region = NULL;
1227 
1228   // Temporarily disable pretouching of heap pages. This interface is used
1229   // when mmap'ing archived heap data in, so pre-touching is wasted.
1230   FlagSetting fs(AlwaysPreTouch, false);
1231 
1232   // Enable archive object checking in G1MarkSweep. We have to let it know
1233   // about each archive range, so that objects in those ranges aren't marked.
1234   G1MarkSweep::enable_archive_object_check();
1235 
1236   // For each specified MemRegion range, allocate the corresponding G1
1237   // regions and mark them as archive regions. We expect the ranges in
1238   // ascending starting address order, without overlap.
1239   for (size_t i = 0; i < count; i++) {
1240     MemRegion curr_range = ranges[i];
1241     HeapWord* start_address = curr_range.start();
1242     size_t word_size = curr_range.word_size();
1243     HeapWord* last_address = curr_range.last();
1244     size_t commits = 0;
1245 
1246     guarantee(reserved.contains(start_address) && reserved.contains(last_address),
1247               err_msg("MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
1248               p2i(start_address), p2i(last_address)));
1249     guarantee(start_address > prev_last_addr,
1250               err_msg("Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
1251               p2i(start_address), p2i(prev_last_addr)));
1252     prev_last_addr = last_address;
1253 
1254     // Check for ranges that start in the same G1 region in which the previous
1255     // range ended, and adjust the start address so we don't try to allocate
1256     // the same region again. If the current range is entirely within that
1257     // region, skip it, just adjusting the recorded top.
1258     HeapRegion* start_region = _hrm.addr_to_region(start_address);
1259     if ((prev_last_region != NULL) && (start_region == prev_last_region)) {
1260       start_address = start_region->end();
1261       if (start_address > last_address) {
1262         increase_used(word_size * HeapWordSize);
1263         start_region->set_top(last_address + 1);
1264         continue;
1265       }
1266       start_region->set_top(start_address);
1267       curr_range = MemRegion(start_address, last_address + 1);
1268       start_region = _hrm.addr_to_region(start_address);
1269     }
1270 
1271     // Perform the actual region allocation, exiting if it fails.
1272     // Then note how much new space we have allocated.
1273     if (!_hrm.allocate_containing_regions(curr_range, &commits)) {
1274       return false;
1275     }
1276     increase_used(word_size * HeapWordSize);
1277     if (commits != 0) {
1278       ergo_verbose1(ErgoHeapSizing,
1279                     "attempt heap expansion",
1280                     ergo_format_reason("allocate archive regions")
1281                     ergo_format_byte("total size"),
1282                     HeapRegion::GrainWords * HeapWordSize * commits);
1283     }
1284 
1285     // Mark each G1 region touched by the range as archive, add it to the old set,
1286     // and set the allocation context and top.
1287     HeapRegion* curr_region = _hrm.addr_to_region(start_address);
1288     HeapRegion* last_region = _hrm.addr_to_region(last_address);
1289     prev_last_region = last_region;
1290 
1291     while (curr_region != NULL) {
1292       assert(curr_region->is_empty() && !curr_region->is_pinned(),
1293              err_msg("Region already in use (index %u)", curr_region->hrm_index()));
1294       _hr_printer.alloc(curr_region, G1HRPrinter::Archive);
1295       curr_region->set_allocation_context(AllocationContext::system());
1296       curr_region->set_archive();
1297       _old_set.add(curr_region);
1298       if (curr_region != last_region) {
1299         curr_region->set_top(curr_region->end());
1300         curr_region = _hrm.next_region_in_heap(curr_region);
1301       } else {
1302         curr_region->set_top(last_address + 1);
1303         curr_region = NULL;
1304       }
1305     }
1306 
1307     // Notify mark-sweep of the archive range.
1308     G1MarkSweep::mark_range_archive(curr_range);
1309   }
1310   return true;
1311 }
1312 
1313 void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {
1314   assert(ranges != NULL, "MemRegion array NULL");
1315   assert(count != 0, "No MemRegions provided");
1316   MemRegion reserved = _hrm.reserved();
1317   HeapWord *prev_last_addr = NULL;
1318   HeapRegion* prev_last_region = NULL;
1319 
1320   // For each MemRegion, create filler objects, if needed, in the G1 regions
1321   // that contain the address range. The address range actually within the
1322   // MemRegion will not be modified. That is assumed to have been initialized
1323   // elsewhere, probably via an mmap of archived heap data.
1324   MutexLockerEx x(Heap_lock);
1325   for (size_t i = 0; i < count; i++) {
1326     HeapWord* start_address = ranges[i].start();
1327     HeapWord* last_address = ranges[i].last();
1328 
1329     assert(reserved.contains(start_address) && reserved.contains(last_address),
1330            err_msg("MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
1331                    p2i(start_address), p2i(last_address)));
1332     assert(start_address > prev_last_addr,
1333            err_msg("Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
1334                    p2i(start_address), p2i(prev_last_addr)));
1335 
1336     HeapRegion* start_region = _hrm.addr_to_region(start_address);
1337     HeapRegion* last_region = _hrm.addr_to_region(last_address);
1338     HeapWord* bottom_address = start_region->bottom();
1339 
1340     // Check for a range beginning in the same region in which the
1341     // previous one ended.
1342     if (start_region == prev_last_region) {
1343       bottom_address = prev_last_addr + 1;
1344     }
1345 
1346     // Verify that the regions were all marked as archive regions by
1347     // alloc_archive_regions.
1348     HeapRegion* curr_region = start_region;
1349     while (curr_region != NULL) {
1350       guarantee(curr_region->is_archive(),
1351                 err_msg("Expected archive region at index %u", curr_region->hrm_index()));
1352       if (curr_region != last_region) {
1353         curr_region = _hrm.next_region_in_heap(curr_region);
1354       } else {
1355         curr_region = NULL;
1356       }
1357     }
1358 
1359     prev_last_addr = last_address;
1360     prev_last_region = last_region;
1361 
1362     // Fill the memory below the allocated range with dummy object(s),
1363     // if the region bottom does not match the range start, or if the previous
1364     // range ended within the same G1 region, and there is a gap.
1365     if (start_address != bottom_address) {
1366       size_t fill_size = pointer_delta(start_address, bottom_address);
1367       G1CollectedHeap::fill_with_objects(bottom_address, fill_size);
1368       increase_used(fill_size * HeapWordSize);
1369     }
1370   }
1371 }
1372 
1373 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
1374                                                         uint* gc_count_before_ret,
1375                                                         uint* gclocker_retry_count_ret) {
1376   // The structure of this method has a lot of similarities to
1377   // attempt_allocation_slow(). The reason these two were not merged
1378   // into a single one is that such a method would require several "if
1379   // allocation is not humongous do this, otherwise do that"
1380   // conditional paths which would obscure its flow. In fact, an early
1381   // version of this code did use a unified method which was harder to
1382   // follow and, as a result, it had subtle bugs that were hard to
1383   // track down. So keeping these two methods separate allows each to
1384   // be more readable. It will be good to keep these two in sync as
1385   // much as possible.
1386 
1387   assert_heap_not_locked_and_not_at_safepoint();
1388   assert(is_humongous(word_size), "attempt_allocation_humongous() "
1389          "should only be called for humongous allocations");
1390 
1391   // Humongous objects can exhaust the heap quickly, so we should check if we
1392   // need to start a marking cycle at each humongous object allocation. We do
1393   // the check before we do the actual allocation. The reason for doing it
1394   // before the allocation is that we avoid having to keep track of the newly
1395   // allocated memory while we do a GC.
1396   if (g1_policy()->need_to_start_conc_mark("concurrent humongous allocation",
1397                                            word_size)) {
1398     collect(GCCause::_g1_humongous_allocation);
1399   }
1400 
1401   // We will loop until a) we manage to successfully perform the
1402   // allocation or b) we successfully schedule a collection which
1403   // fails to perform the allocation. b) is the only case when we'll
1404   // return NULL.
1405   HeapWord* result = NULL;
1406   for (int try_count = 1; /* we'll return */; try_count += 1) {
1407     bool should_try_gc;
1408     uint gc_count_before;
1409 
1410     {
1411       MutexLockerEx x(Heap_lock);
1412 
1413       // Given that humongous objects are not allocated in young
1414       // regions, we'll first try to do the allocation without doing a
1415       // collection hoping that there's enough space in the heap.
1416       result = humongous_obj_allocate(word_size, AllocationContext::current());
1417       if (result != NULL) {
1418         return result;
1419       }
1420 
1421       if (GC_locker::is_active_and_needs_gc()) {
1422         should_try_gc = false;
1423       } else {
1424          // The GCLocker may not be active but the GCLocker initiated
1425         // GC may not yet have been performed (GCLocker::needs_gc()
1426         // returns true). In this case we do not try this GC and
1427         // wait until the GCLocker initiated GC is performed, and
1428         // then retry the allocation.
1429         if (GC_locker::needs_gc()) {
1430           should_try_gc = false;
1431         } else {
1432           // Read the GC count while still holding the Heap_lock.
1433           gc_count_before = total_collections();
1434           should_try_gc = true;
1435         }
1436       }
1437     }
1438 
1439     if (should_try_gc) {
1440       // If we failed to allocate the humongous object, we should try to
1441       // do a collection pause (if we're allowed) in case it reclaims
1442       // enough space for the allocation to succeed after the pause.
1443 
1444       bool succeeded;
1445       result = do_collection_pause(word_size, gc_count_before, &succeeded,
1446                                    GCCause::_g1_humongous_allocation);
1447       if (result != NULL) {
1448         assert(succeeded, "only way to get back a non-NULL result");
1449         return result;
1450       }
1451 
1452       if (succeeded) {
1453         // If we get here we successfully scheduled a collection which
1454         // failed to allocate. No point in trying to allocate
1455         // further. We'll just return NULL.
1456         MutexLockerEx x(Heap_lock);
1457         *gc_count_before_ret = total_collections();
1458         return NULL;
1459       }
1460     } else {
1461       if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
1462         MutexLockerEx x(Heap_lock);
1463         *gc_count_before_ret = total_collections();
1464         return NULL;
1465       }
1466       // The GCLocker is either active or the GCLocker initiated
1467       // GC has not yet been performed. Stall until it is and
1468       // then retry the allocation.
1469       GC_locker::stall_until_clear();
1470       (*gclocker_retry_count_ret) += 1;
1471     }
1472 
1473     // We can reach here if we were unsuccessful in scheduling a
1474     // collection (because another thread beat us to it) or if we were
1475     // stalled due to the GC locker. In either can we should retry the
1476     // allocation attempt in case another thread successfully
1477     // performed a collection and reclaimed enough space.  Give a
1478     // warning if we seem to be looping forever.
1479 
1480     if ((QueuedAllocationWarningCount > 0) &&
1481         (try_count % QueuedAllocationWarningCount == 0)) {
1482       warning("G1CollectedHeap::attempt_allocation_humongous() "
1483               "retries %d times", try_count);
1484     }
1485   }
1486 
1487   ShouldNotReachHere();
1488   return NULL;
1489 }
1490 
1491 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
1492                                                            AllocationContext_t context,
1493                                                            bool expect_null_mutator_alloc_region) {
1494   assert_at_safepoint(true /* should_be_vm_thread */);
1495   assert(_allocator->mutator_alloc_region(context)->get() == NULL ||
1496                                              !expect_null_mutator_alloc_region,
1497          "the current alloc region was unexpectedly found to be non-NULL");
1498 
1499   if (!is_humongous(word_size)) {
1500     return _allocator->mutator_alloc_region(context)->attempt_allocation_locked(word_size,
1501                                                       false /* bot_updates */);
1502   } else {
1503     HeapWord* result = humongous_obj_allocate(word_size, context);
1504     if (result != NULL && g1_policy()->need_to_start_conc_mark("STW humongous allocation")) {
1505       collector_state()->set_initiate_conc_mark_if_possible(true);
1506     }
1507     return result;
1508   }
1509 
1510   ShouldNotReachHere();
1511 }
1512 
1513 class PostMCRemSetClearClosure: public HeapRegionClosure {
1514   G1CollectedHeap* _g1h;
1515   ModRefBarrierSet* _mr_bs;
1516 public:
1517   PostMCRemSetClearClosure(G1CollectedHeap* g1h, ModRefBarrierSet* mr_bs) :
1518     _g1h(g1h), _mr_bs(mr_bs) {}
1519 
1520   bool doHeapRegion(HeapRegion* r) {
1521     HeapRegionRemSet* hrrs = r->rem_set();
1522 
1523     if (r->is_continues_humongous()) {
1524       // We'll assert that the strong code root list and RSet is empty
1525       assert(hrrs->strong_code_roots_list_length() == 0, "sanity");
1526       assert(hrrs->occupied() == 0, "RSet should be empty");
1527       return false;
1528     }
1529 
1530     _g1h->reset_gc_time_stamps(r);
1531     hrrs->clear();
1532     // You might think here that we could clear just the cards
1533     // corresponding to the used region.  But no: if we leave a dirty card
1534     // in a region we might allocate into, then it would prevent that card
1535     // from being enqueued, and cause it to be missed.
1536     // Re: the performance cost: we shouldn't be doing full GC anyway!
1537     _mr_bs->clear(MemRegion(r->bottom(), r->end()));
1538 
1539     return false;
1540   }
1541 };
1542 
1543 void G1CollectedHeap::clear_rsets_post_compaction() {
1544   PostMCRemSetClearClosure rs_clear(this, g1_barrier_set());
1545   heap_region_iterate(&rs_clear);
1546 }
1547 
1548 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
1549   G1CollectedHeap*   _g1h;
1550   UpdateRSOopClosure _cl;
1551 public:
1552   RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, uint worker_i = 0) :
1553     _cl(g1->g1_rem_set(), worker_i),
1554     _g1h(g1)
1555   { }
1556 
1557   bool doHeapRegion(HeapRegion* r) {
1558     if (!r->is_continues_humongous()) {
1559       _cl.set_from(r);
1560       r->oop_iterate(&_cl);
1561     }
1562     return false;
1563   }
1564 };
1565 
1566 class ParRebuildRSTask: public AbstractGangTask {
1567   G1CollectedHeap* _g1;
1568   HeapRegionClaimer _hrclaimer;
1569 
1570 public:
1571   ParRebuildRSTask(G1CollectedHeap* g1) :
1572       AbstractGangTask("ParRebuildRSTask"), _g1(g1), _hrclaimer(g1->workers()->active_workers()) {}
1573 
1574   void work(uint worker_id) {
1575     RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);
1576     _g1->heap_region_par_iterate(&rebuild_rs, worker_id, &_hrclaimer);
1577   }
1578 };
1579 
1580 class PostCompactionPrinterClosure: public HeapRegionClosure {
1581 private:
1582   G1HRPrinter* _hr_printer;
1583 public:
1584   bool doHeapRegion(HeapRegion* hr) {
1585     assert(!hr->is_young(), "not expecting to find young regions");
1586     if (hr->is_free()) {
1587       // We only generate output for non-empty regions.
1588     } else if (hr->is_starts_humongous()) {
1589       if (hr->region_num() == 1) {
1590         // single humongous region
1591         _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
1592       } else {
1593         _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
1594       }
1595     } else if (hr->is_continues_humongous()) {
1596       _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
1597     } else if (hr->is_archive()) {
1598       _hr_printer->post_compaction(hr, G1HRPrinter::Archive);
1599     } else if (hr->is_old()) {
1600       _hr_printer->post_compaction(hr, G1HRPrinter::Old);
1601     } else {
1602       ShouldNotReachHere();
1603     }
1604     return false;
1605   }
1606 
1607   PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
1608     : _hr_printer(hr_printer) { }
1609 };
1610 
1611 void G1CollectedHeap::print_hrm_post_compaction() {
1612   PostCompactionPrinterClosure cl(hr_printer());
1613   heap_region_iterate(&cl);
1614 }
1615 
1616 bool G1CollectedHeap::do_collection(bool explicit_gc,
1617                                     bool clear_all_soft_refs,
1618                                     size_t word_size) {
1619   assert_at_safepoint(true /* should_be_vm_thread */);
1620 
1621   if (GC_locker::check_active_before_gc()) {
1622     return false;
1623   }
1624 
1625   STWGCTimer* gc_timer = G1MarkSweep::gc_timer();
1626   gc_timer->register_gc_start();
1627 
1628   SerialOldTracer* gc_tracer = G1MarkSweep::gc_tracer();
1629   gc_tracer->report_gc_start(gc_cause(), gc_timer->gc_start());
1630 
1631   SvcGCMarker sgcm(SvcGCMarker::FULL);
1632   ResourceMark rm;
1633 
1634   G1Log::update_level();
1635   print_heap_before_gc();
1636   trace_heap_before_gc(gc_tracer);
1637 
1638   size_t metadata_prev_used = MetaspaceAux::used_bytes();
1639 
1640   verify_region_sets_optional();
1641 
1642   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1643                            collector_policy()->should_clear_all_soft_refs();
1644 
1645   ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
1646 
1647   {
1648     IsGCActiveMark x;
1649 
1650     // Timing
1651     assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");
1652     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
1653 
1654     {
1655       GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL, gc_tracer->gc_id());
1656       TraceCollectorStats tcs(g1mm()->full_collection_counters());
1657       TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
1658 
1659       g1_policy()->record_full_collection_start();
1660 
1661       // Note: When we have a more flexible GC logging framework that
1662       // allows us to add optional attributes to a GC log record we
1663       // could consider timing and reporting how long we wait in the
1664       // following two methods.
1665       wait_while_free_regions_coming();
1666       // If we start the compaction before the CM threads finish
1667       // scanning the root regions we might trip them over as we'll
1668       // be moving objects / updating references. So let's wait until
1669       // they are done. By telling them to abort, they should complete
1670       // early.
1671       _cm->root_regions()->abort();
1672       _cm->root_regions()->wait_until_scan_finished();
1673       append_secondary_free_list_if_not_empty_with_lock();
1674 
1675       gc_prologue(true);
1676       increment_total_collections(true /* full gc */);
1677       increment_old_marking_cycles_started();
1678 
1679       assert(used() == recalculate_used(), "Should be equal");
1680 
1681       verify_before_gc();
1682 
1683       check_bitmaps("Full GC Start");
1684       pre_full_gc_dump(gc_timer);
1685 
1686       COMPILER2_PRESENT(DerivedPointerTable::clear());
1687 
1688       // Disable discovery and empty the discovered lists
1689       // for the CM ref processor.
1690       ref_processor_cm()->disable_discovery();
1691       ref_processor_cm()->abandon_partial_discovery();
1692       ref_processor_cm()->verify_no_references_recorded();
1693 
1694       // Abandon current iterations of concurrent marking and concurrent
1695       // refinement, if any are in progress. We have to do this before
1696       // wait_until_scan_finished() below.
1697       concurrent_mark()->abort();
1698 
1699       // Make sure we'll choose a new allocation region afterwards.
1700       _allocator->release_mutator_alloc_region();
1701       _allocator->abandon_gc_alloc_regions();
1702       g1_rem_set()->cleanupHRRS();
1703 
1704       // We should call this after we retire any currently active alloc
1705       // regions so that all the ALLOC / RETIRE events are generated
1706       // before the start GC event.
1707       _hr_printer.start_gc(true /* full */, (size_t) total_collections());
1708 
1709       // We may have added regions to the current incremental collection
1710       // set between the last GC or pause and now. We need to clear the
1711       // incremental collection set and then start rebuilding it afresh
1712       // after this full GC.
1713       abandon_collection_set(g1_policy()->inc_cset_head());
1714       g1_policy()->clear_incremental_cset();
1715       g1_policy()->stop_incremental_cset_building();
1716 
1717       tear_down_region_sets(false /* free_list_only */);
1718       collector_state()->set_gcs_are_young(true);
1719 
1720       // See the comments in g1CollectedHeap.hpp and
1721       // G1CollectedHeap::ref_processing_init() about
1722       // how reference processing currently works in G1.
1723 
1724       // Temporarily make discovery by the STW ref processor single threaded (non-MT).
1725       ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);
1726 
1727       // Temporarily clear the STW ref processor's _is_alive_non_header field.
1728       ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);
1729 
1730       ref_processor_stw()->enable_discovery();
1731       ref_processor_stw()->setup_policy(do_clear_all_soft_refs);
1732 
1733       // Do collection work
1734       {
1735         HandleMark hm;  // Discard invalid handles created during gc
1736         G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);
1737       }
1738 
1739       assert(num_free_regions() == 0, "we should not have added any free regions");
1740       rebuild_region_sets(false /* free_list_only */);
1741 
1742       // Enqueue any discovered reference objects that have
1743       // not been removed from the discovered lists.
1744       ref_processor_stw()->enqueue_discovered_references();
1745 
1746       COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1747 
1748       MemoryService::track_memory_usage();
1749 
1750       assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
1751       ref_processor_stw()->verify_no_references_recorded();
1752 
1753       // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1754       ClassLoaderDataGraph::purge();
1755       MetaspaceAux::verify_metrics();
1756 
1757       // Note: since we've just done a full GC, concurrent
1758       // marking is no longer active. Therefore we need not
1759       // re-enable reference discovery for the CM ref processor.
1760       // That will be done at the start of the next marking cycle.
1761       assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");
1762       ref_processor_cm()->verify_no_references_recorded();
1763 
1764       reset_gc_time_stamp();
1765       // Since everything potentially moved, we will clear all remembered
1766       // sets, and clear all cards.  Later we will rebuild remembered
1767       // sets. We will also reset the GC time stamps of the regions.
1768       clear_rsets_post_compaction();
1769       check_gc_time_stamps();
1770 
1771       // Resize the heap if necessary.
1772       resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
1773 
1774       if (_hr_printer.is_active()) {
1775         // We should do this after we potentially resize the heap so
1776         // that all the COMMIT / UNCOMMIT events are generated before
1777         // the end GC event.
1778 
1779         print_hrm_post_compaction();
1780         _hr_printer.end_gc(true /* full */, (size_t) total_collections());
1781       }
1782 
1783       G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
1784       if (hot_card_cache->use_cache()) {
1785         hot_card_cache->reset_card_counts();
1786         hot_card_cache->reset_hot_cache();
1787       }
1788 
1789       // Rebuild remembered sets of all regions.
1790       uint n_workers =
1791         AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
1792                                                 workers()->active_workers(),
1793                                                 Threads::number_of_non_daemon_threads());
1794       workers()->set_active_workers(n_workers);
1795 
1796       ParRebuildRSTask rebuild_rs_task(this);
1797       workers()->run_task(&rebuild_rs_task);
1798 
1799       // Rebuild the strong code root lists for each region
1800       rebuild_strong_code_roots();
1801 
1802       if (true) { // FIXME
1803         MetaspaceGC::compute_new_size();
1804       }
1805 
1806 #ifdef TRACESPINNING
1807       ParallelTaskTerminator::print_termination_counts();
1808 #endif
1809 
1810       // Discard all rset updates
1811       JavaThread::dirty_card_queue_set().abandon_logs();
1812       assert(dirty_card_queue_set().completed_buffers_num() == 0, "DCQS should be empty");
1813 
1814       _young_list->reset_sampled_info();
1815       // At this point there should be no regions in the
1816       // entire heap tagged as young.
1817       assert(check_young_list_empty(true /* check_heap */),
1818              "young list should be empty at this point");
1819 
1820       // Update the number of full collections that have been completed.
1821       increment_old_marking_cycles_completed(false /* concurrent */);
1822 
1823       _hrm.verify_optional();
1824       verify_region_sets_optional();
1825 
1826       verify_after_gc();
1827 
1828       // Clear the previous marking bitmap, if needed for bitmap verification.
1829       // Note we cannot do this when we clear the next marking bitmap in
1830       // ConcurrentMark::abort() above since VerifyDuringGC verifies the
1831       // objects marked during a full GC against the previous bitmap.
1832       // But we need to clear it before calling check_bitmaps below since
1833       // the full GC has compacted objects and updated TAMS but not updated
1834       // the prev bitmap.
1835       if (G1VerifyBitmaps) {
1836         ((CMBitMap*) concurrent_mark()->prevMarkBitMap())->clearAll();
1837       }
1838       check_bitmaps("Full GC End");
1839 
1840       // Start a new incremental collection set for the next pause
1841       assert(g1_policy()->collection_set() == NULL, "must be");
1842       g1_policy()->start_incremental_cset_building();
1843 
1844       clear_cset_fast_test();
1845 
1846       _allocator->init_mutator_alloc_region();
1847 
1848       g1_policy()->record_full_collection_end();
1849 
1850       if (G1Log::fine()) {
1851         g1_policy()->print_heap_transition();
1852       }
1853 
1854       // We must call G1MonitoringSupport::update_sizes() in the same scoping level
1855       // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
1856       // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
1857       // before any GC notifications are raised.
1858       g1mm()->update_sizes();
1859 
1860       gc_epilogue(true);
1861     }
1862 
1863     if (G1Log::finer()) {
1864       g1_policy()->print_detailed_heap_transition(true /* full */);
1865     }
1866 
1867     print_heap_after_gc();
1868     trace_heap_after_gc(gc_tracer);
1869 
1870     post_full_gc_dump(gc_timer);
1871 
1872     gc_timer->register_gc_end();
1873     gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
1874   }
1875 
1876   return true;
1877 }
1878 
1879 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1880   // do_collection() will return whether it succeeded in performing
1881   // the GC. Currently, there is no facility on the
1882   // do_full_collection() API to notify the caller than the collection
1883   // did not succeed (e.g., because it was locked out by the GC
1884   // locker). So, right now, we'll ignore the return value.
1885   bool dummy = do_collection(true,                /* explicit_gc */
1886                              clear_all_soft_refs,
1887                              0                    /* word_size */);
1888 }
1889 
1890 // This code is mostly copied from TenuredGeneration.
1891 void
1892 G1CollectedHeap::
1893 resize_if_necessary_after_full_collection(size_t word_size) {
1894   // Include the current allocation, if any, and bytes that will be
1895   // pre-allocated to support collections, as "used".
1896   const size_t used_after_gc = used();
1897   const size_t capacity_after_gc = capacity();
1898   const size_t free_after_gc = capacity_after_gc - used_after_gc;
1899 
1900   // This is enforced in arguments.cpp.
1901   assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
1902          "otherwise the code below doesn't make sense");
1903 
1904   // We don't have floating point command-line arguments
1905   const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
1906   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1907   const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
1908   const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1909 
1910   const size_t min_heap_size = collector_policy()->min_heap_byte_size();
1911   const size_t max_heap_size = collector_policy()->max_heap_byte_size();
1912 
1913   // We have to be careful here as these two calculations can overflow
1914   // 32-bit size_t's.
1915   double used_after_gc_d = (double) used_after_gc;
1916   double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
1917   double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
1918 
1919   // Let's make sure that they are both under the max heap size, which
1920   // by default will make them fit into a size_t.
1921   double desired_capacity_upper_bound = (double) max_heap_size;
1922   minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
1923                                     desired_capacity_upper_bound);
1924   maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
1925                                     desired_capacity_upper_bound);
1926 
1927   // We can now safely turn them into size_t's.
1928   size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
1929   size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
1930 
1931   // This assert only makes sense here, before we adjust them
1932   // with respect to the min and max heap size.
1933   assert(minimum_desired_capacity <= maximum_desired_capacity,
1934          err_msg("minimum_desired_capacity = " SIZE_FORMAT ", "
1935                  "maximum_desired_capacity = " SIZE_FORMAT,
1936                  minimum_desired_capacity, maximum_desired_capacity));
1937 
1938   // Should not be greater than the heap max size. No need to adjust
1939   // it with respect to the heap min size as it's a lower bound (i.e.,
1940   // we'll try to make the capacity larger than it, not smaller).
1941   minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);
1942   // Should not be less than the heap min size. No need to adjust it
1943   // with respect to the heap max size as it's an upper bound (i.e.,
1944   // we'll try to make the capacity smaller than it, not greater).
1945   maximum_desired_capacity =  MAX2(maximum_desired_capacity, min_heap_size);
1946 
1947   if (capacity_after_gc < minimum_desired_capacity) {
1948     // Don't expand unless it's significant
1949     size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1950     ergo_verbose4(ErgoHeapSizing,
1951                   "attempt heap expansion",
1952                   ergo_format_reason("capacity lower than "
1953                                      "min desired capacity after Full GC")
1954                   ergo_format_byte("capacity")
1955                   ergo_format_byte("occupancy")
1956                   ergo_format_byte_perc("min desired capacity"),
1957                   capacity_after_gc, used_after_gc,
1958                   minimum_desired_capacity, (double) MinHeapFreeRatio);
1959     expand(expand_bytes);
1960 
1961     // No expansion, now see if we want to shrink
1962   } else if (capacity_after_gc > maximum_desired_capacity) {
1963     // Capacity too large, compute shrinking size
1964     size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1965     ergo_verbose4(ErgoHeapSizing,
1966                   "attempt heap shrinking",
1967                   ergo_format_reason("capacity higher than "
1968                                      "max desired capacity after Full GC")
1969                   ergo_format_byte("capacity")
1970                   ergo_format_byte("occupancy")
1971                   ergo_format_byte_perc("max desired capacity"),
1972                   capacity_after_gc, used_after_gc,
1973                   maximum_desired_capacity, (double) MaxHeapFreeRatio);
1974     shrink(shrink_bytes);
1975   }
1976 }
1977 
1978 
1979 HeapWord*
1980 G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1981                                            AllocationContext_t context,
1982                                            bool* succeeded) {
1983   assert_at_safepoint(true /* should_be_vm_thread */);
1984 
1985   *succeeded = true;
1986   // Let's attempt the allocation first.
1987   HeapWord* result =
1988     attempt_allocation_at_safepoint(word_size,
1989                                     context,
1990                                     false /* expect_null_mutator_alloc_region */);
1991   if (result != NULL) {
1992     assert(*succeeded, "sanity");
1993     return result;
1994   }
1995 
1996   // In a G1 heap, we're supposed to keep allocation from failing by
1997   // incremental pauses.  Therefore, at least for now, we'll favor
1998   // expansion over collection.  (This might change in the future if we can
1999   // do something smarter than full collection to satisfy a failed alloc.)
2000   result = expand_and_allocate(word_size, context);
2001   if (result != NULL) {
2002     assert(*succeeded, "sanity");
2003     return result;
2004   }
2005 
2006   // Expansion didn't work, we'll try to do a Full GC.
2007   bool gc_succeeded = do_collection(false, /* explicit_gc */
2008                                     false, /* clear_all_soft_refs */
2009                                     word_size);
2010   if (!gc_succeeded) {
2011     *succeeded = false;
2012     return NULL;
2013   }
2014 
2015   // Retry the allocation
2016   result = attempt_allocation_at_safepoint(word_size,
2017                                            context,
2018                                            true /* expect_null_mutator_alloc_region */);
2019   if (result != NULL) {
2020     assert(*succeeded, "sanity");
2021     return result;
2022   }
2023 
2024   // Then, try a Full GC that will collect all soft references.
2025   gc_succeeded = do_collection(false, /* explicit_gc */
2026                                true,  /* clear_all_soft_refs */
2027                                word_size);
2028   if (!gc_succeeded) {
2029     *succeeded = false;
2030     return NULL;
2031   }
2032 
2033   // Retry the allocation once more
2034   result = attempt_allocation_at_safepoint(word_size,
2035                                            context,
2036                                            true /* expect_null_mutator_alloc_region */);
2037   if (result != NULL) {
2038     assert(*succeeded, "sanity");
2039     return result;
2040   }
2041 
2042   assert(!collector_policy()->should_clear_all_soft_refs(),
2043          "Flag should have been handled and cleared prior to this point");
2044 
2045   // What else?  We might try synchronous finalization later.  If the total
2046   // space available is large enough for the allocation, then a more
2047   // complete compaction phase than we've tried so far might be
2048   // appropriate.
2049   assert(*succeeded, "sanity");
2050   return NULL;
2051 }
2052 
2053 // Attempting to expand the heap sufficiently
2054 // to support an allocation of the given "word_size".  If
2055 // successful, perform the allocation and return the address of the
2056 // allocated block, or else "NULL".
2057 
2058 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size, AllocationContext_t context) {
2059   assert_at_safepoint(true /* should_be_vm_thread */);
2060 
2061   verify_region_sets_optional();
2062 
2063   size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
2064   ergo_verbose1(ErgoHeapSizing,
2065                 "attempt heap expansion",
2066                 ergo_format_reason("allocation request failed")
2067                 ergo_format_byte("allocation request"),
2068                 word_size * HeapWordSize);
2069   if (expand(expand_bytes)) {
2070     _hrm.verify_optional();
2071     verify_region_sets_optional();
2072     return attempt_allocation_at_safepoint(word_size,
2073                                            context,
2074                                            false /* expect_null_mutator_alloc_region */);
2075   }
2076   return NULL;
2077 }
2078 
2079 bool G1CollectedHeap::expand(size_t expand_bytes) {
2080   size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
2081   aligned_expand_bytes = align_size_up(aligned_expand_bytes,
2082                                        HeapRegion::GrainBytes);
2083   ergo_verbose2(ErgoHeapSizing,
2084                 "expand the heap",
2085                 ergo_format_byte("requested expansion amount")
2086                 ergo_format_byte("attempted expansion amount"),
2087                 expand_bytes, aligned_expand_bytes);
2088 
2089   if (is_maximal_no_gc()) {
2090     ergo_verbose0(ErgoHeapSizing,
2091                       "did not expand the heap",
2092                       ergo_format_reason("heap already fully expanded"));
2093     return false;
2094   }
2095 
2096   uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);
2097   assert(regions_to_expand > 0, "Must expand by at least one region");
2098 
2099   uint expanded_by = _hrm.expand_by(regions_to_expand);
2100 
2101   if (expanded_by > 0) {
2102     size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;
2103     assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
2104     g1_policy()->record_new_heap_size(num_regions());
2105   } else {
2106     ergo_verbose0(ErgoHeapSizing,
2107                   "did not expand the heap",
2108                   ergo_format_reason("heap expansion operation failed"));
2109     // The expansion of the virtual storage space was unsuccessful.
2110     // Let's see if it was because we ran out of swap.
2111     if (G1ExitOnExpansionFailure &&
2112         _hrm.available() >= regions_to_expand) {
2113       // We had head room...
2114       vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
2115     }
2116   }
2117   return regions_to_expand > 0;
2118 }
2119 
2120 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
2121   size_t aligned_shrink_bytes =
2122     ReservedSpace::page_align_size_down(shrink_bytes);
2123   aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
2124                                          HeapRegion::GrainBytes);
2125   uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
2126 
2127   uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);
2128   size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
2129 
2130   ergo_verbose3(ErgoHeapSizing,
2131                 "shrink the heap",
2132                 ergo_format_byte("requested shrinking amount")
2133                 ergo_format_byte("aligned shrinking amount")
2134                 ergo_format_byte("attempted shrinking amount"),
2135                 shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
2136   if (num_regions_removed > 0) {
2137     g1_policy()->record_new_heap_size(num_regions());
2138   } else {
2139     ergo_verbose0(ErgoHeapSizing,
2140                   "did not shrink the heap",
2141                   ergo_format_reason("heap shrinking operation failed"));
2142   }
2143 }
2144 
2145 void G1CollectedHeap::shrink(size_t shrink_bytes) {
2146   verify_region_sets_optional();
2147 
2148   // We should only reach here at the end of a Full GC which means we
2149   // should not not be holding to any GC alloc regions. The method
2150   // below will make sure of that and do any remaining clean up.
2151   _allocator->abandon_gc_alloc_regions();
2152 
2153   // Instead of tearing down / rebuilding the free lists here, we
2154   // could instead use the remove_all_pending() method on free_list to
2155   // remove only the ones that we need to remove.
2156   tear_down_region_sets(true /* free_list_only */);
2157   shrink_helper(shrink_bytes);
2158   rebuild_region_sets(true /* free_list_only */);
2159 
2160   _hrm.verify_optional();
2161   verify_region_sets_optional();
2162 }
2163 
2164 // Public methods.
2165 
2166 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
2167 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
2168 #endif // _MSC_VER
2169 
2170 
2171 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
2172   CollectedHeap(),
2173   _g1_policy(policy_),
2174   _dirty_card_queue_set(false),
2175   _into_cset_dirty_card_queue_set(false),
2176   _is_alive_closure_cm(this),
2177   _is_alive_closure_stw(this),
2178   _ref_processor_cm(NULL),
2179   _ref_processor_stw(NULL),
2180   _bot_shared(NULL),
2181   _cg1r(NULL),
2182   _g1mm(NULL),
2183   _refine_cte_cl_concurrency(true),
2184   _secondary_free_list("Secondary Free List", new SecondaryFreeRegionListMtSafeChecker()),
2185   _old_set("Old Set", false /* humongous */, new OldRegionSetMtSafeChecker()),
2186   _humongous_set("Master Humongous Set", true /* humongous */, new HumongousRegionSetMtSafeChecker()),
2187   _humongous_reclaim_candidates(),
2188   _has_humongous_reclaim_candidates(false),
2189   _archive_allocator(NULL),
2190   _free_regions_coming(false),
2191   _young_list(new YoungList(this)),
2192   _gc_time_stamp(0),
2193   _summary_bytes_used(0),
2194   _survivor_plab_stats(YoungPLABSize, PLABWeight),
2195   _old_plab_stats(OldPLABSize, PLABWeight),
2196   _expand_heap_after_alloc_failure(true),
2197   _surviving_young_words(NULL),
2198   _old_marking_cycles_started(0),
2199   _old_marking_cycles_completed(0),
2200   _heap_summary_sent(false),
2201   _in_cset_fast_test(),
2202   _dirty_cards_region_list(NULL),
2203   _worker_cset_start_region(NULL),
2204   _worker_cset_start_region_time_stamp(NULL),
2205   _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
2206   _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
2207   _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
2208   _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()) {
2209 
2210   _workers = new FlexibleWorkGang("GC Thread", ParallelGCThreads,
2211                           /* are_GC_task_threads */true,
2212                           /* are_ConcurrentGC_threads */false);
2213   _workers->initialize_workers();
2214 
2215   _allocator = G1Allocator::create_allocator(this);
2216   _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);
2217 
2218   // Override the default _filler_array_max_size so that no humongous filler
2219   // objects are created.
2220   _filler_array_max_size = _humongous_object_threshold_in_words;
2221 
2222   uint n_queues = ParallelGCThreads;
2223   _task_queues = new RefToScanQueueSet(n_queues);
2224 
2225   uint n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
2226   assert(n_rem_sets > 0, "Invariant.");
2227 
2228   _worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC);
2229   _worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(uint, n_queues, mtGC);
2230   _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
2231 
2232   for (uint i = 0; i < n_queues; i++) {
2233     RefToScanQueue* q = new RefToScanQueue();
2234     q->initialize();
2235     _task_queues->register_queue(i, q);
2236     ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
2237   }
2238   clear_cset_start_regions();
2239 
2240   // Initialize the G1EvacuationFailureALot counters and flags.
2241   NOT_PRODUCT(reset_evacuation_should_fail();)
2242 
2243   guarantee(_task_queues != NULL, "task_queues allocation failure.");
2244 }
2245 
2246 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,
2247                                                                  size_t size,
2248                                                                  size_t translation_factor) {
2249   size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);
2250   // Allocate a new reserved space, preferring to use large pages.
2251   ReservedSpace rs(size, preferred_page_size);
2252   G1RegionToSpaceMapper* result  =
2253     G1RegionToSpaceMapper::create_mapper(rs,
2254                                          size,
2255                                          rs.alignment(),
2256                                          HeapRegion::GrainBytes,
2257                                          translation_factor,
2258                                          mtGC);
2259   if (TracePageSizes) {
2260     gclog_or_tty->print_cr("G1 '%s': pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT " size=" SIZE_FORMAT " alignment=" SIZE_FORMAT " reqsize=" SIZE_FORMAT,
2261                            description, preferred_page_size, p2i(rs.base()), rs.size(), rs.alignment(), size);
2262   }
2263   return result;
2264 }
2265 
2266 jint G1CollectedHeap::initialize() {
2267   CollectedHeap::pre_initialize();
2268   os::enable_vtime();
2269 
2270   G1Log::init();
2271 
2272   // Necessary to satisfy locking discipline assertions.
2273 
2274   MutexLocker x(Heap_lock);
2275 
2276   // We have to initialize the printer before committing the heap, as
2277   // it will be used then.
2278   _hr_printer.set_active(G1PrintHeapRegions);
2279 
2280   // While there are no constraints in the GC code that HeapWordSize
2281   // be any particular value, there are multiple other areas in the
2282   // system which believe this to be true (e.g. oop->object_size in some
2283   // cases incorrectly returns the size in wordSize units rather than
2284   // HeapWordSize).
2285   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
2286 
2287   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
2288   size_t max_byte_size = collector_policy()->max_heap_byte_size();
2289   size_t heap_alignment = collector_policy()->heap_alignment();
2290 
2291   // Ensure that the sizes are properly aligned.
2292   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
2293   Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
2294   Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap");
2295 
2296   _cg1r = new ConcurrentG1Refine(this);
2297 
2298   // Reserve the maximum.
2299 
2300   // When compressed oops are enabled, the preferred heap base
2301   // is calculated by subtracting the requested size from the
2302   // 32Gb boundary and using the result as the base address for
2303   // heap reservation. If the requested size is not aligned to
2304   // HeapRegion::GrainBytes (i.e. the alignment that is passed
2305   // into the ReservedHeapSpace constructor) then the actual
2306   // base of the reserved heap may end up differing from the
2307   // address that was requested (i.e. the preferred heap base).
2308   // If this happens then we could end up using a non-optimal
2309   // compressed oops mode.
2310 
2311   ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size,
2312                                                  heap_alignment);
2313 
2314   initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*)(heap_rs.base() + heap_rs.size()));
2315 
2316   // Create the barrier set for the entire reserved region.
2317   G1SATBCardTableLoggingModRefBS* bs
2318     = new G1SATBCardTableLoggingModRefBS(reserved_region());
2319   bs->initialize();
2320   assert(bs->is_a(BarrierSet::G1SATBCTLogging), "sanity");
2321   set_barrier_set(bs);
2322 
2323   // Also create a G1 rem set.
2324   _g1_rem_set = new G1RemSet(this, g1_barrier_set());
2325 
2326   // Carve out the G1 part of the heap.
2327 
2328   ReservedSpace g1_rs = heap_rs.first_part(max_byte_size);
2329   size_t page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
2330   G1RegionToSpaceMapper* heap_storage =
2331     G1RegionToSpaceMapper::create_mapper(g1_rs,
2332                                          g1_rs.size(),
2333                                          page_size,
2334                                          HeapRegion::GrainBytes,
2335                                          1,
2336                                          mtJavaHeap);
2337   os::trace_page_sizes("G1 Heap", collector_policy()->min_heap_byte_size(),
2338                        max_byte_size, page_size,
2339                        heap_rs.base(),
2340                        heap_rs.size());
2341   heap_storage->set_mapping_changed_listener(&_listener);
2342 
2343   // Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.
2344   G1RegionToSpaceMapper* bot_storage =
2345     create_aux_memory_mapper("Block offset table",
2346                              G1BlockOffsetSharedArray::compute_size(g1_rs.size() / HeapWordSize),
2347                              G1BlockOffsetSharedArray::heap_map_factor());
2348 
2349   ReservedSpace cardtable_rs(G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize));
2350   G1RegionToSpaceMapper* cardtable_storage =
2351     create_aux_memory_mapper("Card table",
2352                              G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize),
2353                              G1SATBCardTableLoggingModRefBS::heap_map_factor());
2354 
2355   G1RegionToSpaceMapper* card_counts_storage =
2356     create_aux_memory_mapper("Card counts table",
2357                              G1CardCounts::compute_size(g1_rs.size() / HeapWordSize),
2358                              G1CardCounts::heap_map_factor());
2359 
2360   size_t bitmap_size = CMBitMap::compute_size(g1_rs.size());
2361   G1RegionToSpaceMapper* prev_bitmap_storage =
2362     create_aux_memory_mapper("Prev Bitmap", bitmap_size, CMBitMap::heap_map_factor());
2363   G1RegionToSpaceMapper* next_bitmap_storage =
2364     create_aux_memory_mapper("Next Bitmap", bitmap_size, CMBitMap::heap_map_factor());
2365 
2366   _hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);
2367   g1_barrier_set()->initialize(cardtable_storage);
2368    // Do later initialization work for concurrent refinement.
2369   _cg1r->init(card_counts_storage);
2370 
2371   // 6843694 - ensure that the maximum region index can fit
2372   // in the remembered set structures.
2373   const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
2374   guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
2375 
2376   size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
2377   guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
2378   guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
2379             "too many cards per region");
2380 
2381   FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
2382 
2383   _bot_shared = new G1BlockOffsetSharedArray(reserved_region(), bot_storage);
2384 
2385   {
2386     HeapWord* start = _hrm.reserved().start();
2387     HeapWord* end = _hrm.reserved().end();
2388     size_t granularity = HeapRegion::GrainBytes;
2389 
2390     _in_cset_fast_test.initialize(start, end, granularity);
2391     _humongous_reclaim_candidates.initialize(start, end, granularity);
2392   }
2393 
2394   // Create the ConcurrentMark data structure and thread.
2395   // (Must do this late, so that "max_regions" is defined.)
2396   _cm = new ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);
2397   if (_cm == NULL || !_cm->completed_initialization()) {
2398     vm_shutdown_during_initialization("Could not create/initialize ConcurrentMark");
2399     return JNI_ENOMEM;
2400   }
2401   _cmThread = _cm->cmThread();
2402 
2403   // Initialize the from_card cache structure of HeapRegionRemSet.
2404   HeapRegionRemSet::init_heap(max_regions());
2405 
2406   // Now expand into the initial heap size.
2407   if (!expand(init_byte_size)) {
2408     vm_shutdown_during_initialization("Failed to allocate initial heap.");
2409     return JNI_ENOMEM;
2410   }
2411 
2412   // Perform any initialization actions delegated to the policy.
2413   g1_policy()->init();
2414 
2415   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
2416                                                SATB_Q_FL_lock,
2417                                                G1SATBProcessCompletedThreshold,
2418                                                Shared_SATB_Q_lock);
2419 
2420   JavaThread::dirty_card_queue_set().initialize(true,
2421                                                 DirtyCardQ_CBL_mon,
2422                                                 DirtyCardQ_FL_lock,
2423                                                 concurrent_g1_refine()->yellow_zone(),
2424                                                 concurrent_g1_refine()->red_zone(),
2425                                                 Shared_DirtyCardQ_lock);
2426 
2427   dirty_card_queue_set().initialize(false, // Should never be called by the Java code
2428                                     DirtyCardQ_CBL_mon,
2429                                     DirtyCardQ_FL_lock,
2430                                     -1, // never trigger processing
2431                                     -1, // no limit on length
2432                                     Shared_DirtyCardQ_lock,
2433                                     &JavaThread::dirty_card_queue_set());
2434 
2435   // Initialize the card queue set used to hold cards containing
2436   // references into the collection set.
2437   _into_cset_dirty_card_queue_set.initialize(false, // Should never be called by the Java code
2438                                              DirtyCardQ_CBL_mon,
2439                                              DirtyCardQ_FL_lock,
2440                                              -1, // never trigger processing
2441                                              -1, // no limit on length
2442                                              Shared_DirtyCardQ_lock,
2443                                              &JavaThread::dirty_card_queue_set());
2444 
2445   // Here we allocate the dummy HeapRegion that is required by the
2446   // G1AllocRegion class.
2447   HeapRegion* dummy_region = _hrm.get_dummy_region();
2448 
2449   // We'll re-use the same region whether the alloc region will
2450   // require BOT updates or not and, if it doesn't, then a non-young
2451   // region will complain that it cannot support allocations without
2452   // BOT updates. So we'll tag the dummy region as eden to avoid that.
2453   dummy_region->set_eden();
2454   // Make sure it's full.
2455   dummy_region->set_top(dummy_region->end());
2456   G1AllocRegion::setup(this, dummy_region);
2457 
2458   _allocator->init_mutator_alloc_region();
2459 
2460   // Do create of the monitoring and management support so that
2461   // values in the heap have been properly initialized.
2462   _g1mm = new G1MonitoringSupport(this);
2463 
2464   G1StringDedup::initialize();
2465 
2466   _preserved_objs = NEW_C_HEAP_ARRAY(OopAndMarkOopStack, ParallelGCThreads, mtGC);
2467   for (uint i = 0; i < ParallelGCThreads; i++) {
2468     new (&_preserved_objs[i]) OopAndMarkOopStack();
2469   }
2470 
2471   return JNI_OK;
2472 }
2473 
2474 void G1CollectedHeap::stop() {
2475   // Stop all concurrent threads. We do this to make sure these threads
2476   // do not continue to execute and access resources (e.g. gclog_or_tty)
2477   // that are destroyed during shutdown.
2478   _cg1r->stop();
2479   _cmThread->stop();
2480   if (G1StringDedup::is_enabled()) {
2481     G1StringDedup::stop();
2482   }
2483 }
2484 
2485 size_t G1CollectedHeap::conservative_max_heap_alignment() {
2486   return HeapRegion::max_region_size();
2487 }
2488 
2489 void G1CollectedHeap::post_initialize() {
2490   CollectedHeap::post_initialize();
2491   ref_processing_init();
2492 }
2493 
2494 void G1CollectedHeap::ref_processing_init() {
2495   // Reference processing in G1 currently works as follows:
2496   //
2497   // * There are two reference processor instances. One is
2498   //   used to record and process discovered references
2499   //   during concurrent marking; the other is used to
2500   //   record and process references during STW pauses
2501   //   (both full and incremental).
2502   // * Both ref processors need to 'span' the entire heap as
2503   //   the regions in the collection set may be dotted around.
2504   //
2505   // * For the concurrent marking ref processor:
2506   //   * Reference discovery is enabled at initial marking.
2507   //   * Reference discovery is disabled and the discovered
2508   //     references processed etc during remarking.
2509   //   * Reference discovery is MT (see below).
2510   //   * Reference discovery requires a barrier (see below).
2511   //   * Reference processing may or may not be MT
2512   //     (depending on the value of ParallelRefProcEnabled
2513   //     and ParallelGCThreads).
2514   //   * A full GC disables reference discovery by the CM
2515   //     ref processor and abandons any entries on it's
2516   //     discovered lists.
2517   //
2518   // * For the STW processor:
2519   //   * Non MT discovery is enabled at the start of a full GC.
2520   //   * Processing and enqueueing during a full GC is non-MT.
2521   //   * During a full GC, references are processed after marking.
2522   //
2523   //   * Discovery (may or may not be MT) is enabled at the start
2524   //     of an incremental evacuation pause.
2525   //   * References are processed near the end of a STW evacuation pause.
2526   //   * For both types of GC:
2527   //     * Discovery is atomic - i.e. not concurrent.
2528   //     * Reference discovery will not need a barrier.
2529 
2530   MemRegion mr = reserved_region();
2531 
2532   // Concurrent Mark ref processor
2533   _ref_processor_cm =
2534     new ReferenceProcessor(mr,    // span
2535                            ParallelRefProcEnabled && (ParallelGCThreads > 1),
2536                                 // mt processing
2537                            ParallelGCThreads,
2538                                 // degree of mt processing
2539                            (ParallelGCThreads > 1) || (ConcGCThreads > 1),
2540                                 // mt discovery
2541                            MAX2(ParallelGCThreads, ConcGCThreads),
2542                                 // degree of mt discovery
2543                            false,
2544                                 // Reference discovery is not atomic
2545                            &_is_alive_closure_cm);
2546                                 // is alive closure
2547                                 // (for efficiency/performance)
2548 
2549   // STW ref processor
2550   _ref_processor_stw =
2551     new ReferenceProcessor(mr,    // span
2552                            ParallelRefProcEnabled && (ParallelGCThreads > 1),
2553                                 // mt processing
2554                            ParallelGCThreads,
2555                                 // degree of mt processing
2556                            (ParallelGCThreads > 1),
2557                                 // mt discovery
2558                            ParallelGCThreads,
2559                                 // degree of mt discovery
2560                            true,
2561                                 // Reference discovery is atomic
2562                            &_is_alive_closure_stw);
2563                                 // is alive closure
2564                                 // (for efficiency/performance)
2565 }
2566 
2567 size_t G1CollectedHeap::capacity() const {
2568   return _hrm.length() * HeapRegion::GrainBytes;
2569 }
2570 
2571 void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) {
2572   assert(!hr->is_continues_humongous(), "pre-condition");
2573   hr->reset_gc_time_stamp();
2574   if (hr->is_starts_humongous()) {
2575     uint first_index = hr->hrm_index() + 1;
2576     uint last_index = hr->last_hc_index();
2577     for (uint i = first_index; i < last_index; i += 1) {
2578       HeapRegion* chr = region_at(i);
2579       assert(chr->is_continues_humongous(), "sanity");
2580       chr->reset_gc_time_stamp();
2581     }
2582   }
2583 }
2584 
2585 #ifndef PRODUCT
2586 
2587 class CheckGCTimeStampsHRClosure : public HeapRegionClosure {
2588 private:
2589   unsigned _gc_time_stamp;
2590   bool _failures;
2591 
2592 public:
2593   CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) :
2594     _gc_time_stamp(gc_time_stamp), _failures(false) { }
2595 
2596   virtual bool doHeapRegion(HeapRegion* hr) {
2597     unsigned region_gc_time_stamp = hr->get_gc_time_stamp();
2598     if (_gc_time_stamp != region_gc_time_stamp) {
2599       gclog_or_tty->print_cr("Region " HR_FORMAT " has GC time stamp = %d, "
2600                              "expected %d", HR_FORMAT_PARAMS(hr),
2601                              region_gc_time_stamp, _gc_time_stamp);
2602       _failures = true;
2603     }
2604     return false;
2605   }
2606 
2607   bool failures() { return _failures; }
2608 };
2609 
2610 void G1CollectedHeap::check_gc_time_stamps() {
2611   CheckGCTimeStampsHRClosure cl(_gc_time_stamp);
2612   heap_region_iterate(&cl);
2613   guarantee(!cl.failures(), "all GC time stamps should have been reset");
2614 }
2615 #endif // PRODUCT
2616 
2617 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,
2618                                                  DirtyCardQueue* into_cset_dcq,
2619                                                  bool concurrent,
2620                                                  uint worker_i) {
2621   // Clean cards in the hot card cache
2622   G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
2623   hot_card_cache->drain(worker_i, g1_rem_set(), into_cset_dcq);
2624 
2625   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2626   size_t n_completed_buffers = 0;
2627   while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {
2628     n_completed_buffers++;
2629   }
2630   g1_policy()->phase_times()->record_thread_work_item(G1GCPhaseTimes::UpdateRS, worker_i, n_completed_buffers);
2631   dcqs.clear_n_completed_buffers();
2632   assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
2633 }
2634 
2635 
2636 // Computes the sum of the storage used by the various regions.
2637 size_t G1CollectedHeap::used() const {
2638   size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();
2639   if (_archive_allocator != NULL) {
2640     result += _archive_allocator->used();
2641   }
2642   return result;
2643 }
2644 
2645 size_t G1CollectedHeap::used_unlocked() const {
2646   return _summary_bytes_used;
2647 }
2648 
2649 class SumUsedClosure: public HeapRegionClosure {
2650   size_t _used;
2651 public:
2652   SumUsedClosure() : _used(0) {}
2653   bool doHeapRegion(HeapRegion* r) {
2654     if (!r->is_continues_humongous()) {
2655       _used += r->used();
2656     }
2657     return false;
2658   }
2659   size_t result() { return _used; }
2660 };
2661 
2662 size_t G1CollectedHeap::recalculate_used() const {
2663   double recalculate_used_start = os::elapsedTime();
2664 
2665   SumUsedClosure blk;
2666   heap_region_iterate(&blk);
2667 
2668   g1_policy()->phase_times()->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0);
2669   return blk.result();
2670 }
2671 
2672 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
2673   switch (cause) {
2674     case GCCause::_gc_locker:               return GCLockerInvokesConcurrent;
2675     case GCCause::_java_lang_system_gc:     return ExplicitGCInvokesConcurrent;
2676     case GCCause::_dcmd_gc_run:             return ExplicitGCInvokesConcurrent;
2677     case GCCause::_g1_humongous_allocation: return true;
2678     case GCCause::_update_allocation_context_stats_inc: return true;
2679     case GCCause::_wb_conc_mark:            return true;
2680     default:                                return false;
2681   }
2682 }
2683 
2684 #ifndef PRODUCT
2685 void G1CollectedHeap::allocate_dummy_regions() {
2686   // Let's fill up most of the region
2687   size_t word_size = HeapRegion::GrainWords - 1024;
2688   // And as a result the region we'll allocate will be humongous.
2689   guarantee(is_humongous(word_size), "sanity");
2690 
2691   for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
2692     // Let's use the existing mechanism for the allocation
2693     HeapWord* dummy_obj = humongous_obj_allocate(word_size,
2694                                                  AllocationContext::system());
2695     if (dummy_obj != NULL) {
2696       MemRegion mr(dummy_obj, word_size);
2697       CollectedHeap::fill_with_object(mr);
2698     } else {
2699       // If we can't allocate once, we probably cannot allocate
2700       // again. Let's get out of the loop.
2701       break;
2702     }
2703   }
2704 }
2705 #endif // !PRODUCT
2706 
2707 void G1CollectedHeap::increment_old_marking_cycles_started() {
2708   assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
2709     _old_marking_cycles_started == _old_marking_cycles_completed + 1,
2710     err_msg("Wrong marking cycle count (started: %d, completed: %d)",
2711     _old_marking_cycles_started, _old_marking_cycles_completed));
2712 
2713   _old_marking_cycles_started++;
2714 }
2715 
2716 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) {
2717   MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
2718 
2719   // We assume that if concurrent == true, then the caller is a
2720   // concurrent thread that was joined the Suspendible Thread
2721   // Set. If there's ever a cheap way to check this, we should add an
2722   // assert here.
2723 
2724   // Given that this method is called at the end of a Full GC or of a
2725   // concurrent cycle, and those can be nested (i.e., a Full GC can
2726   // interrupt a concurrent cycle), the number of full collections
2727   // completed should be either one (in the case where there was no
2728   // nesting) or two (when a Full GC interrupted a concurrent cycle)
2729   // behind the number of full collections started.
2730 
2731   // This is the case for the inner caller, i.e. a Full GC.
2732   assert(concurrent ||
2733          (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
2734          (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
2735          err_msg("for inner caller (Full GC): _old_marking_cycles_started = %u "
2736                  "is inconsistent with _old_marking_cycles_completed = %u",
2737                  _old_marking_cycles_started, _old_marking_cycles_completed));
2738 
2739   // This is the case for the outer caller, i.e. the concurrent cycle.
2740   assert(!concurrent ||
2741          (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
2742          err_msg("for outer caller (concurrent cycle): "
2743                  "_old_marking_cycles_started = %u "
2744                  "is inconsistent with _old_marking_cycles_completed = %u",
2745                  _old_marking_cycles_started, _old_marking_cycles_completed));
2746 
2747   _old_marking_cycles_completed += 1;
2748 
2749   // We need to clear the "in_progress" flag in the CM thread before
2750   // we wake up any waiters (especially when ExplicitInvokesConcurrent
2751   // is set) so that if a waiter requests another System.gc() it doesn't
2752   // incorrectly see that a marking cycle is still in progress.
2753   if (concurrent) {
2754     _cmThread->set_idle();
2755   }
2756 
2757   // This notify_all() will ensure that a thread that called
2758   // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
2759   // and it's waiting for a full GC to finish will be woken up. It is
2760   // waiting in VM_G1IncCollectionPause::doit_epilogue().
2761   FullGCCount_lock->notify_all();
2762 }
2763 
2764 void G1CollectedHeap::register_concurrent_cycle_start(const Ticks& start_time) {
2765   collector_state()->set_concurrent_cycle_started(true);
2766   _gc_timer_cm->register_gc_start(start_time);
2767 
2768   _gc_tracer_cm->report_gc_start(gc_cause(), _gc_timer_cm->gc_start());
2769   trace_heap_before_gc(_gc_tracer_cm);
2770 }
2771 
2772 void G1CollectedHeap::register_concurrent_cycle_end() {
2773   if (collector_state()->concurrent_cycle_started()) {
2774     if (_cm->has_aborted()) {
2775       _gc_tracer_cm->report_concurrent_mode_failure();
2776     }
2777 
2778     _gc_timer_cm->register_gc_end();
2779     _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
2780 
2781     // Clear state variables to prepare for the next concurrent cycle.
2782      collector_state()->set_concurrent_cycle_started(false);
2783     _heap_summary_sent = false;
2784   }
2785 }
2786 
2787 void G1CollectedHeap::trace_heap_after_concurrent_cycle() {
2788   if (collector_state()->concurrent_cycle_started()) {
2789     // This function can be called when:
2790     //  the cleanup pause is run
2791     //  the concurrent cycle is aborted before the cleanup pause.
2792     //  the concurrent cycle is aborted after the cleanup pause,
2793     //   but before the concurrent cycle end has been registered.
2794     // Make sure that we only send the heap information once.
2795     if (!_heap_summary_sent) {
2796       trace_heap_after_gc(_gc_tracer_cm);
2797       _heap_summary_sent = true;
2798     }
2799   }
2800 }
2801 
2802 void G1CollectedHeap::collect(GCCause::Cause cause) {
2803   assert_heap_not_locked();
2804 
2805   uint gc_count_before;
2806   uint old_marking_count_before;
2807   uint full_gc_count_before;
2808   bool retry_gc;
2809 
2810   do {
2811     retry_gc = false;
2812 
2813     {
2814       MutexLocker ml(Heap_lock);
2815 
2816       // Read the GC count while holding the Heap_lock
2817       gc_count_before = total_collections();
2818       full_gc_count_before = total_full_collections();
2819       old_marking_count_before = _old_marking_cycles_started;
2820     }
2821 
2822     if (should_do_concurrent_full_gc(cause)) {
2823       // Schedule an initial-mark evacuation pause that will start a
2824       // concurrent cycle. We're setting word_size to 0 which means that
2825       // we are not requesting a post-GC allocation.
2826       VM_G1IncCollectionPause op(gc_count_before,
2827                                  0,     /* word_size */
2828                                  true,  /* should_initiate_conc_mark */
2829                                  g1_policy()->max_pause_time_ms(),
2830                                  cause);
2831       op.set_allocation_context(AllocationContext::current());
2832 
2833       VMThread::execute(&op);
2834       if (!op.pause_succeeded()) {
2835         if (old_marking_count_before == _old_marking_cycles_started) {
2836           retry_gc = op.should_retry_gc();
2837         } else {
2838           // A Full GC happened while we were trying to schedule the
2839           // initial-mark GC. No point in starting a new cycle given
2840           // that the whole heap was collected anyway.
2841         }
2842 
2843         if (retry_gc) {
2844           if (GC_locker::is_active_and_needs_gc()) {
2845             GC_locker::stall_until_clear();
2846           }
2847         }
2848       }
2849     } else {
2850       if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc
2851           DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2852 
2853         // Schedule a standard evacuation pause. We're setting word_size
2854         // to 0 which means that we are not requesting a post-GC allocation.
2855         VM_G1IncCollectionPause op(gc_count_before,
2856                                    0,     /* word_size */
2857                                    false, /* should_initiate_conc_mark */
2858                                    g1_policy()->max_pause_time_ms(),
2859                                    cause);
2860         VMThread::execute(&op);
2861       } else {
2862         // Schedule a Full GC.
2863         VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);
2864         VMThread::execute(&op);
2865       }
2866     }
2867   } while (retry_gc);
2868 }
2869 
2870 bool G1CollectedHeap::is_in(const void* p) const {
2871   if (_hrm.reserved().contains(p)) {
2872     // Given that we know that p is in the reserved space,
2873     // heap_region_containing_raw() should successfully
2874     // return the containing region.
2875     HeapRegion* hr = heap_region_containing_raw(p);
2876     return hr->is_in(p);
2877   } else {
2878     return false;
2879   }
2880 }
2881 
2882 #ifdef ASSERT
2883 bool G1CollectedHeap::is_in_exact(const void* p) const {
2884   bool contains = reserved_region().contains(p);
2885   bool available = _hrm.is_available(addr_to_region((HeapWord*)p));
2886   if (contains && available) {
2887     return true;
2888   } else {
2889     return false;
2890   }
2891 }
2892 #endif
2893 
2894 // Iteration functions.
2895 
2896 // Applies an ExtendedOopClosure onto all references of objects within a HeapRegion.
2897 
2898 class IterateOopClosureRegionClosure: public HeapRegionClosure {
2899   ExtendedOopClosure* _cl;
2900 public:
2901   IterateOopClosureRegionClosure(ExtendedOopClosure* cl) : _cl(cl) {}
2902   bool doHeapRegion(HeapRegion* r) {
2903     if (!r->is_continues_humongous()) {
2904       r->oop_iterate(_cl);
2905     }
2906     return false;
2907   }
2908 };
2909 
2910 // Iterates an ObjectClosure over all objects within a HeapRegion.
2911 
2912 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2913   ObjectClosure* _cl;
2914 public:
2915   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2916   bool doHeapRegion(HeapRegion* r) {
2917     if (!r->is_continues_humongous()) {
2918       r->object_iterate(_cl);
2919     }
2920     return false;
2921   }
2922 };
2923 
2924 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2925   IterateObjectClosureRegionClosure blk(cl);
2926   heap_region_iterate(&blk);
2927 }
2928 
2929 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2930   _hrm.iterate(cl);
2931 }
2932 
2933 void
2934 G1CollectedHeap::heap_region_par_iterate(HeapRegionClosure* cl,
2935                                          uint worker_id,
2936                                          HeapRegionClaimer *hrclaimer,
2937                                          bool concurrent) const {
2938   _hrm.par_iterate(cl, worker_id, hrclaimer, concurrent);
2939 }
2940 
2941 // Clear the cached CSet starting regions and (more importantly)
2942 // the time stamps. Called when we reset the GC time stamp.
2943 void G1CollectedHeap::clear_cset_start_regions() {
2944   assert(_worker_cset_start_region != NULL, "sanity");
2945   assert(_worker_cset_start_region_time_stamp != NULL, "sanity");
2946 
2947   for (uint i = 0; i < ParallelGCThreads; i++) {
2948     _worker_cset_start_region[i] = NULL;
2949     _worker_cset_start_region_time_stamp[i] = 0;
2950   }
2951 }
2952 
2953 // Given the id of a worker, obtain or calculate a suitable
2954 // starting region for iterating over the current collection set.
2955 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(uint worker_i) {
2956   assert(get_gc_time_stamp() > 0, "should have been updated by now");
2957 
2958   HeapRegion* result = NULL;
2959   unsigned gc_time_stamp = get_gc_time_stamp();
2960 
2961   if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) {
2962     // Cached starting region for current worker was set
2963     // during the current pause - so it's valid.
2964     // Note: the cached starting heap region may be NULL
2965     // (when the collection set is empty).
2966     result = _worker_cset_start_region[worker_i];
2967     assert(result == NULL || result->in_collection_set(), "sanity");
2968     return result;
2969   }
2970 
2971   // The cached entry was not valid so let's calculate
2972   // a suitable starting heap region for this worker.
2973 
2974   // We want the parallel threads to start their collection
2975   // set iteration at different collection set regions to
2976   // avoid contention.
2977   // If we have:
2978   //          n collection set regions
2979   //          p threads
2980   // Then thread t will start at region floor ((t * n) / p)
2981 
2982   result = g1_policy()->collection_set();
2983   uint cs_size = g1_policy()->cset_region_length();
2984   uint active_workers = workers()->active_workers();
2985 
2986   uint end_ind   = (cs_size * worker_i) / active_workers;
2987   uint start_ind = 0;
2988 
2989   if (worker_i > 0 &&
2990       _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) {
2991     // Previous workers starting region is valid
2992     // so let's iterate from there
2993     start_ind = (cs_size * (worker_i - 1)) / active_workers;
2994     result = _worker_cset_start_region[worker_i - 1];
2995   }
2996 
2997   for (uint i = start_ind; i < end_ind; i++) {
2998     result = result->next_in_collection_set();
2999   }
3000 
3001   // Note: the calculated starting heap region may be NULL
3002   // (when the collection set is empty).
3003   assert(result == NULL || result->in_collection_set(), "sanity");
3004   assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp,
3005          "should be updated only once per pause");
3006   _worker_cset_start_region[worker_i] = result;
3007   OrderAccess::storestore();
3008   _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp;
3009   return result;
3010 }
3011 
3012 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
3013   HeapRegion* r = g1_policy()->collection_set();
3014   while (r != NULL) {
3015     HeapRegion* next = r->next_in_collection_set();
3016     if (cl->doHeapRegion(r)) {
3017       cl->incomplete();
3018       return;
3019     }
3020     r = next;
3021   }
3022 }
3023 
3024 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
3025                                                   HeapRegionClosure *cl) {
3026   if (r == NULL) {
3027     // The CSet is empty so there's nothing to do.
3028     return;
3029   }
3030 
3031   assert(r->in_collection_set(),
3032          "Start region must be a member of the collection set.");
3033   HeapRegion* cur = r;
3034   while (cur != NULL) {
3035     HeapRegion* next = cur->next_in_collection_set();
3036     if (cl->doHeapRegion(cur) && false) {
3037       cl->incomplete();
3038       return;
3039     }
3040     cur = next;
3041   }
3042   cur = g1_policy()->collection_set();
3043   while (cur != r) {
3044     HeapRegion* next = cur->next_in_collection_set();
3045     if (cl->doHeapRegion(cur) && false) {
3046       cl->incomplete();
3047       return;
3048     }
3049     cur = next;
3050   }
3051 }
3052 
3053 HeapRegion* G1CollectedHeap::next_compaction_region(const HeapRegion* from) const {
3054   HeapRegion* result = _hrm.next_region_in_heap(from);
3055   while (result != NULL && result->is_pinned()) {
3056     result = _hrm.next_region_in_heap(result);
3057   }
3058   return result;
3059 }
3060 
3061 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
3062   HeapRegion* hr = heap_region_containing(addr);
3063   return hr->block_start(addr);
3064 }
3065 
3066 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
3067   HeapRegion* hr = heap_region_containing(addr);
3068   return hr->block_size(addr);
3069 }
3070 
3071 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
3072   HeapRegion* hr = heap_region_containing(addr);
3073   return hr->block_is_obj(addr);
3074 }
3075 
3076 bool G1CollectedHeap::supports_tlab_allocation() const {
3077   return true;
3078 }
3079 
3080 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
3081   return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes;
3082 }
3083 
3084 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
3085   return young_list()->eden_used_bytes();
3086 }
3087 
3088 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
3089 // must be smaller than the humongous object limit.
3090 size_t G1CollectedHeap::max_tlab_size() const {
3091   return align_size_down(_humongous_object_threshold_in_words - 1, MinObjAlignment);
3092 }
3093 
3094 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
3095   // Return the remaining space in the cur alloc region, but not less than
3096   // the min TLAB size.
3097 
3098   // Also, this value can be at most the humongous object threshold,
3099   // since we can't allow tlabs to grow big enough to accommodate
3100   // humongous objects.
3101 
3102   HeapRegion* hr = _allocator->mutator_alloc_region(AllocationContext::current())->get();
3103   size_t max_tlab = max_tlab_size() * wordSize;
3104   if (hr == NULL) {
3105     return max_tlab;
3106   } else {
3107     return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab);
3108   }
3109 }
3110 
3111 size_t G1CollectedHeap::max_capacity() const {
3112   return _hrm.reserved().byte_size();
3113 }
3114 
3115 jlong G1CollectedHeap::millis_since_last_gc() {
3116   // assert(false, "NYI");
3117   return 0;
3118 }
3119 
3120 void G1CollectedHeap::prepare_for_verify() {
3121   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
3122     ensure_parsability(false);
3123   }
3124   g1_rem_set()->prepare_for_verify();
3125 }
3126 
3127 bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr,
3128                                               VerifyOption vo) {
3129   switch (vo) {
3130   case VerifyOption_G1UsePrevMarking:
3131     return hr->obj_allocated_since_prev_marking(obj);
3132   case VerifyOption_G1UseNextMarking:
3133     return hr->obj_allocated_since_next_marking(obj);
3134   case VerifyOption_G1UseMarkWord:
3135     return false;
3136   default:
3137     ShouldNotReachHere();
3138   }
3139   return false; // keep some compilers happy
3140 }
3141 
3142 HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) {
3143   switch (vo) {
3144   case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start();
3145   case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start();
3146   case VerifyOption_G1UseMarkWord:    return NULL;
3147   default:                            ShouldNotReachHere();
3148   }
3149   return NULL; // keep some compilers happy
3150 }
3151 
3152 bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) {
3153   switch (vo) {
3154   case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj);
3155   case VerifyOption_G1UseNextMarking: return isMarkedNext(obj);
3156   case VerifyOption_G1UseMarkWord:    return obj->is_gc_marked();
3157   default:                            ShouldNotReachHere();
3158   }
3159   return false; // keep some compilers happy
3160 }
3161 
3162 const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) {
3163   switch (vo) {
3164   case VerifyOption_G1UsePrevMarking: return "PTAMS";
3165   case VerifyOption_G1UseNextMarking: return "NTAMS";
3166   case VerifyOption_G1UseMarkWord:    return "NONE";
3167   default:                            ShouldNotReachHere();
3168   }
3169   return NULL; // keep some compilers happy
3170 }
3171 
3172 class VerifyRootsClosure: public OopClosure {
3173 private:
3174   G1CollectedHeap* _g1h;
3175   VerifyOption     _vo;
3176   bool             _failures;
3177 public:
3178   // _vo == UsePrevMarking -> use "prev" marking information,
3179   // _vo == UseNextMarking -> use "next" marking information,
3180   // _vo == UseMarkWord    -> use mark word from object header.
3181   VerifyRootsClosure(VerifyOption vo) :
3182     _g1h(G1CollectedHeap::heap()),
3183     _vo(vo),
3184     _failures(false) { }
3185 
3186   bool failures() { return _failures; }
3187 
3188   template <class T> void do_oop_nv(T* p) {
3189     T heap_oop = oopDesc::load_heap_oop(p);
3190     if (!oopDesc::is_null(heap_oop)) {
3191       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3192       if (_g1h->is_obj_dead_cond(obj, _vo)) {
3193         gclog_or_tty->print_cr("Root location " PTR_FORMAT " "
3194                                "points to dead obj " PTR_FORMAT, p2i(p), p2i(obj));
3195         if (_vo == VerifyOption_G1UseMarkWord) {
3196           gclog_or_tty->print_cr("  Mark word: " INTPTR_FORMAT, (intptr_t)obj->mark());
3197         }
3198         obj->print_on(gclog_or_tty);
3199         _failures = true;
3200       }
3201     }
3202   }
3203 
3204   void do_oop(oop* p)       { do_oop_nv(p); }
3205   void do_oop(narrowOop* p) { do_oop_nv(p); }
3206 };
3207 
3208 class G1VerifyCodeRootOopClosure: public OopClosure {
3209   G1CollectedHeap* _g1h;
3210   OopClosure* _root_cl;
3211   nmethod* _nm;
3212   VerifyOption _vo;
3213   bool _failures;
3214 
3215   template <class T> void do_oop_work(T* p) {
3216     // First verify that this root is live
3217     _root_cl->do_oop(p);
3218 
3219     if (!G1VerifyHeapRegionCodeRoots) {
3220       // We're not verifying the code roots attached to heap region.
3221       return;
3222     }
3223 
3224     // Don't check the code roots during marking verification in a full GC
3225     if (_vo == VerifyOption_G1UseMarkWord) {
3226       return;
3227     }
3228 
3229     // Now verify that the current nmethod (which contains p) is
3230     // in the code root list of the heap region containing the
3231     // object referenced by p.
3232 
3233     T heap_oop = oopDesc::load_heap_oop(p);
3234     if (!oopDesc::is_null(heap_oop)) {
3235       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3236 
3237       // Now fetch the region containing the object
3238       HeapRegion* hr = _g1h->heap_region_containing(obj);
3239       HeapRegionRemSet* hrrs = hr->rem_set();
3240       // Verify that the strong code root list for this region
3241       // contains the nmethod
3242       if (!hrrs->strong_code_roots_list_contains(_nm)) {
3243         gclog_or_tty->print_cr("Code root location " PTR_FORMAT " "
3244                                "from nmethod " PTR_FORMAT " not in strong "
3245                                "code roots for region [" PTR_FORMAT "," PTR_FORMAT ")",
3246                                p2i(p), p2i(_nm), p2i(hr->bottom()), p2i(hr->end()));
3247         _failures = true;
3248       }
3249     }
3250   }
3251 
3252 public:
3253   G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
3254     _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}
3255 
3256   void do_oop(oop* p) { do_oop_work(p); }
3257   void do_oop(narrowOop* p) { do_oop_work(p); }
3258 
3259   void set_nmethod(nmethod* nm) { _nm = nm; }
3260   bool failures() { return _failures; }
3261 };
3262 
3263 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
3264   G1VerifyCodeRootOopClosure* _oop_cl;
3265 
3266 public:
3267   G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
3268     _oop_cl(oop_cl) {}
3269 
3270   void do_code_blob(CodeBlob* cb) {
3271     nmethod* nm = cb->as_nmethod_or_null();
3272     if (nm != NULL) {
3273       _oop_cl->set_nmethod(nm);
3274       nm->oops_do(_oop_cl);
3275     }
3276   }
3277 };
3278 
3279 class YoungRefCounterClosure : public OopClosure {
3280   G1CollectedHeap* _g1h;
3281   int              _count;
3282  public:
3283   YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
3284   void do_oop(oop* p)       { if (_g1h->is_in_young(*p)) { _count++; } }
3285   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3286 
3287   int count() { return _count; }
3288   void reset_count() { _count = 0; };
3289 };
3290 
3291 class VerifyKlassClosure: public KlassClosure {
3292   YoungRefCounterClosure _young_ref_counter_closure;
3293   OopClosure *_oop_closure;
3294  public:
3295   VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
3296   void do_klass(Klass* k) {
3297     k->oops_do(_oop_closure);
3298 
3299     _young_ref_counter_closure.reset_count();
3300     k->oops_do(&_young_ref_counter_closure);
3301     if (_young_ref_counter_closure.count() > 0) {
3302       guarantee(k->has_modified_oops(), err_msg("Klass " PTR_FORMAT ", has young refs but is not dirty.", p2i(k)));
3303     }
3304   }
3305 };
3306 
3307 class VerifyLivenessOopClosure: public OopClosure {
3308   G1CollectedHeap* _g1h;
3309   VerifyOption _vo;
3310 public:
3311   VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
3312     _g1h(g1h), _vo(vo)
3313   { }
3314   void do_oop(narrowOop *p) { do_oop_work(p); }
3315   void do_oop(      oop *p) { do_oop_work(p); }
3316 
3317   template <class T> void do_oop_work(T *p) {
3318     oop obj = oopDesc::load_decode_heap_oop(p);
3319     guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
3320               "Dead object referenced by a not dead object");
3321   }
3322 };
3323 
3324 class VerifyObjsInRegionClosure: public ObjectClosure {
3325 private:
3326   G1CollectedHeap* _g1h;
3327   size_t _live_bytes;
3328   HeapRegion *_hr;
3329   VerifyOption _vo;
3330 public:
3331   // _vo == UsePrevMarking -> use "prev" marking information,
3332   // _vo == UseNextMarking -> use "next" marking information,
3333   // _vo == UseMarkWord    -> use mark word from object header.
3334   VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
3335     : _live_bytes(0), _hr(hr), _vo(vo) {
3336     _g1h = G1CollectedHeap::heap();
3337   }
3338   void do_object(oop o) {
3339     VerifyLivenessOopClosure isLive(_g1h, _vo);
3340     assert(o != NULL, "Huh?");
3341     if (!_g1h->is_obj_dead_cond(o, _vo)) {
3342       // If the object is alive according to the mark word,
3343       // then verify that the marking information agrees.
3344       // Note we can't verify the contra-positive of the
3345       // above: if the object is dead (according to the mark
3346       // word), it may not be marked, or may have been marked
3347       // but has since became dead, or may have been allocated
3348       // since the last marking.
3349       if (_vo == VerifyOption_G1UseMarkWord) {
3350         guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
3351       }
3352 
3353       o->oop_iterate_no_header(&isLive);
3354       if (!_hr->obj_allocated_since_prev_marking(o)) {
3355         size_t obj_size = o->size();    // Make sure we don't overflow
3356         _live_bytes += (obj_size * HeapWordSize);
3357       }
3358     }
3359   }
3360   size_t live_bytes() { return _live_bytes; }
3361 };
3362 
3363 class VerifyArchiveOopClosure: public OopClosure {
3364 public:
3365   VerifyArchiveOopClosure(HeapRegion *hr) { }
3366   void do_oop(narrowOop *p) { do_oop_work(p); }
3367   void do_oop(      oop *p) { do_oop_work(p); }
3368 
3369   template <class T> void do_oop_work(T *p) {
3370     oop obj = oopDesc::load_decode_heap_oop(p);
3371     guarantee(obj == NULL || G1MarkSweep::in_archive_range(obj),
3372               err_msg("Archive object at " PTR_FORMAT " references a non-archive object at " PTR_FORMAT,
3373                       p2i(p), p2i(obj)));
3374   }
3375 };
3376 
3377 class VerifyArchiveRegionClosure: public ObjectClosure {
3378 public:
3379   VerifyArchiveRegionClosure(HeapRegion *hr) { }
3380   // Verify that all object pointers are to archive regions.
3381   void do_object(oop o) {
3382     VerifyArchiveOopClosure checkOop(NULL);
3383     assert(o != NULL, "Should not be here for NULL oops");
3384     o->oop_iterate_no_header(&checkOop);
3385   }
3386 };
3387 
3388 class VerifyRegionClosure: public HeapRegionClosure {
3389 private:
3390   bool             _par;
3391   VerifyOption     _vo;
3392   bool             _failures;
3393 public:
3394   // _vo == UsePrevMarking -> use "prev" marking information,
3395   // _vo == UseNextMarking -> use "next" marking information,
3396   // _vo == UseMarkWord    -> use mark word from object header.
3397   VerifyRegionClosure(bool par, VerifyOption vo)
3398     : _par(par),
3399       _vo(vo),
3400       _failures(false) {}
3401 
3402   bool failures() {
3403     return _failures;
3404   }
3405 
3406   bool doHeapRegion(HeapRegion* r) {
3407     // For archive regions, verify there are no heap pointers to
3408     // non-pinned regions. For all others, verify liveness info.
3409     if (r->is_archive()) {
3410       VerifyArchiveRegionClosure verify_oop_pointers(r);
3411       r->object_iterate(&verify_oop_pointers);
3412       return true;
3413     }
3414     if (!r->is_continues_humongous()) {
3415       bool failures = false;
3416       r->verify(_vo, &failures);
3417       if (failures) {
3418         _failures = true;
3419       } else {
3420         VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
3421         r->object_iterate(&not_dead_yet_cl);
3422         if (_vo != VerifyOption_G1UseNextMarking) {
3423           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
3424             gclog_or_tty->print_cr("[" PTR_FORMAT "," PTR_FORMAT "] "
3425                                    "max_live_bytes " SIZE_FORMAT " "
3426                                    "< calculated " SIZE_FORMAT,
3427                                    p2i(r->bottom()), p2i(r->end()),
3428                                    r->max_live_bytes(),
3429                                  not_dead_yet_cl.live_bytes());
3430             _failures = true;
3431           }
3432         } else {
3433           // When vo == UseNextMarking we cannot currently do a sanity
3434           // check on the live bytes as the calculation has not been
3435           // finalized yet.
3436         }
3437       }
3438     }
3439     return false; // stop the region iteration if we hit a failure
3440   }
3441 };
3442 
3443 // This is the task used for parallel verification of the heap regions
3444 
3445 class G1ParVerifyTask: public AbstractGangTask {
3446 private:
3447   G1CollectedHeap*  _g1h;
3448   VerifyOption      _vo;
3449   bool              _failures;
3450   HeapRegionClaimer _hrclaimer;
3451 
3452 public:
3453   // _vo == UsePrevMarking -> use "prev" marking information,
3454   // _vo == UseNextMarking -> use "next" marking information,
3455   // _vo == UseMarkWord    -> use mark word from object header.
3456   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
3457       AbstractGangTask("Parallel verify task"),
3458       _g1h(g1h),
3459       _vo(vo),
3460       _failures(false),
3461       _hrclaimer(g1h->workers()->active_workers()) {}
3462 
3463   bool failures() {
3464     return _failures;
3465   }
3466 
3467   void work(uint worker_id) {
3468     HandleMark hm;
3469     VerifyRegionClosure blk(true, _vo);
3470     _g1h->heap_region_par_iterate(&blk, worker_id, &_hrclaimer);
3471     if (blk.failures()) {
3472       _failures = true;
3473     }
3474   }
3475 };
3476 
3477 void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
3478   if (SafepointSynchronize::is_at_safepoint()) {
3479     assert(Thread::current()->is_VM_thread(),
3480            "Expected to be executed serially by the VM thread at this point");
3481 
3482     if (!silent) { gclog_or_tty->print("Roots "); }
3483     VerifyRootsClosure rootsCl(vo);
3484     VerifyKlassClosure klassCl(this, &rootsCl);
3485     CLDToKlassAndOopClosure cldCl(&klassCl, &rootsCl, false);
3486 
3487     // We apply the relevant closures to all the oops in the
3488     // system dictionary, class loader data graph, the string table
3489     // and the nmethods in the code cache.
3490     G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);
3491     G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
3492 
3493     {
3494       G1RootProcessor root_processor(this, 1);
3495       root_processor.process_all_roots(&rootsCl,
3496                                        &cldCl,
3497                                        &blobsCl);
3498     }
3499 
3500     bool failures = rootsCl.failures() || codeRootsCl.failures();
3501 
3502     if (vo != VerifyOption_G1UseMarkWord) {
3503       // If we're verifying during a full GC then the region sets
3504       // will have been torn down at the start of the GC. Therefore
3505       // verifying the region sets will fail. So we only verify
3506       // the region sets when not in a full GC.
3507       if (!silent) { gclog_or_tty->print("HeapRegionSets "); }
3508       verify_region_sets();
3509     }
3510 
3511     if (!silent) { gclog_or_tty->print("HeapRegions "); }
3512     if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
3513 
3514       G1ParVerifyTask task(this, vo);
3515       workers()->run_task(&task);
3516       if (task.failures()) {
3517         failures = true;
3518       }
3519 
3520     } else {
3521       VerifyRegionClosure blk(false, vo);
3522       heap_region_iterate(&blk);
3523       if (blk.failures()) {
3524         failures = true;
3525       }
3526     }
3527 
3528     if (G1StringDedup::is_enabled()) {
3529       if (!silent) gclog_or_tty->print("StrDedup ");
3530       G1StringDedup::verify();
3531     }
3532 
3533     if (failures) {
3534       gclog_or_tty->print_cr("Heap:");
3535       // It helps to have the per-region information in the output to
3536       // help us track down what went wrong. This is why we call
3537       // print_extended_on() instead of print_on().
3538       print_extended_on(gclog_or_tty);
3539       gclog_or_tty->cr();
3540       gclog_or_tty->flush();
3541     }
3542     guarantee(!failures, "there should not have been any failures");
3543   } else {
3544     if (!silent) {
3545       gclog_or_tty->print("(SKIPPING Roots, HeapRegionSets, HeapRegions, RemSet");
3546       if (G1StringDedup::is_enabled()) {
3547         gclog_or_tty->print(", StrDedup");
3548       }
3549       gclog_or_tty->print(") ");
3550     }
3551   }
3552 }
3553 
3554 void G1CollectedHeap::verify(bool silent) {
3555   verify(silent, VerifyOption_G1UsePrevMarking);
3556 }
3557 
3558 double G1CollectedHeap::verify(bool guard, const char* msg) {
3559   double verify_time_ms = 0.0;
3560 
3561   if (guard && total_collections() >= VerifyGCStartAt) {
3562     double verify_start = os::elapsedTime();
3563     HandleMark hm;  // Discard invalid handles created during verification
3564     prepare_for_verify();
3565     Universe::verify(VerifyOption_G1UsePrevMarking, msg);
3566     verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
3567   }
3568 
3569   return verify_time_ms;
3570 }
3571 
3572 void G1CollectedHeap::verify_before_gc() {
3573   double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:");
3574   g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);
3575 }
3576 
3577 void G1CollectedHeap::verify_after_gc() {
3578   double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:");
3579   g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);
3580 }
3581 
3582 class PrintRegionClosure: public HeapRegionClosure {
3583   outputStream* _st;
3584 public:
3585   PrintRegionClosure(outputStream* st) : _st(st) {}
3586   bool doHeapRegion(HeapRegion* r) {
3587     r->print_on(_st);
3588     return false;
3589   }
3590 };
3591 
3592 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
3593                                        const HeapRegion* hr,
3594                                        const VerifyOption vo) const {
3595   switch (vo) {
3596   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
3597   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
3598   case VerifyOption_G1UseMarkWord:    return !obj->is_gc_marked() && !hr->is_archive();
3599   default:                            ShouldNotReachHere();
3600   }
3601   return false; // keep some compilers happy
3602 }
3603 
3604 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
3605                                        const VerifyOption vo) const {
3606   switch (vo) {
3607   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
3608   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
3609   case VerifyOption_G1UseMarkWord: {
3610     HeapRegion* hr = _hrm.addr_to_region((HeapWord*)obj);
3611     return !obj->is_gc_marked() && !hr->is_archive();
3612   }
3613   default:                            ShouldNotReachHere();
3614   }
3615   return false; // keep some compilers happy
3616 }
3617 
3618 void G1CollectedHeap::print_on(outputStream* st) const {
3619   st->print(" %-20s", "garbage-first heap");
3620   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
3621             capacity()/K, used_unlocked()/K);
3622   st->print(" [" PTR_FORMAT ", " PTR_FORMAT ", " PTR_FORMAT ")",
3623             p2i(_hrm.reserved().start()),
3624             p2i(_hrm.reserved().start() + _hrm.length() + HeapRegion::GrainWords),
3625             p2i(_hrm.reserved().end()));
3626   st->cr();
3627   st->print("  region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
3628   uint young_regions = _young_list->length();
3629   st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
3630             (size_t) young_regions * HeapRegion::GrainBytes / K);
3631   uint survivor_regions = g1_policy()->recorded_survivor_regions();
3632   st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
3633             (size_t) survivor_regions * HeapRegion::GrainBytes / K);
3634   st->cr();
3635   MetaspaceAux::print_on(st);
3636 }
3637 
3638 void G1CollectedHeap::print_extended_on(outputStream* st) const {
3639   print_on(st);
3640 
3641   // Print the per-region information.
3642   st->cr();
3643   st->print_cr("Heap Regions: (E=young(eden), S=young(survivor), O=old, "
3644                "HS=humongous(starts), HC=humongous(continues), "
3645                "CS=collection set, F=free, A=archive, TS=gc time stamp, "
3646                "PTAMS=previous top-at-mark-start, "
3647                "NTAMS=next top-at-mark-start)");
3648   PrintRegionClosure blk(st);
3649   heap_region_iterate(&blk);
3650 }
3651 
3652 void G1CollectedHeap::print_on_error(outputStream* st) const {
3653   this->CollectedHeap::print_on_error(st);
3654 
3655   if (_cm != NULL) {
3656     st->cr();
3657     _cm->print_on_error(st);
3658   }
3659 }
3660 
3661 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
3662   workers()->print_worker_threads_on(st);
3663   _cmThread->print_on(st);
3664   st->cr();
3665   _cm->print_worker_threads_on(st);
3666   _cg1r->print_worker_threads_on(st);
3667   if (G1StringDedup::is_enabled()) {
3668     G1StringDedup::print_worker_threads_on(st);
3669   }
3670 }
3671 
3672 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
3673   workers()->threads_do(tc);
3674   tc->do_thread(_cmThread);
3675   _cg1r->threads_do(tc);
3676   if (G1StringDedup::is_enabled()) {
3677     G1StringDedup::threads_do(tc);
3678   }
3679 }
3680 
3681 void G1CollectedHeap::print_tracing_info() const {
3682   // We'll overload this to mean "trace GC pause statistics."
3683   if (TraceYoungGenTime || TraceOldGenTime) {
3684     // The "G1CollectorPolicy" is keeping track of these stats, so delegate
3685     // to that.
3686     g1_policy()->print_tracing_info();
3687   }
3688   if (G1SummarizeRSetStats) {
3689     g1_rem_set()->print_summary_info();
3690   }
3691   if (G1SummarizeConcMark) {
3692     concurrent_mark()->print_summary_info();
3693   }
3694   g1_policy()->print_yg_surv_rate_info();
3695 }
3696 
3697 #ifndef PRODUCT
3698 // Helpful for debugging RSet issues.
3699 
3700 class PrintRSetsClosure : public HeapRegionClosure {
3701 private:
3702   const char* _msg;
3703   size_t _occupied_sum;
3704 
3705 public:
3706   bool doHeapRegion(HeapRegion* r) {
3707     HeapRegionRemSet* hrrs = r->rem_set();
3708     size_t occupied = hrrs->occupied();
3709     _occupied_sum += occupied;
3710 
3711     gclog_or_tty->print_cr("Printing RSet for region " HR_FORMAT,
3712                            HR_FORMAT_PARAMS(r));
3713     if (occupied == 0) {
3714       gclog_or_tty->print_cr("  RSet is empty");
3715     } else {
3716       hrrs->print();
3717     }
3718     gclog_or_tty->print_cr("----------");
3719     return false;
3720   }
3721 
3722   PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
3723     gclog_or_tty->cr();
3724     gclog_or_tty->print_cr("========================================");
3725     gclog_or_tty->print_cr("%s", msg);
3726     gclog_or_tty->cr();
3727   }
3728 
3729   ~PrintRSetsClosure() {
3730     gclog_or_tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);
3731     gclog_or_tty->print_cr("========================================");
3732     gclog_or_tty->cr();
3733   }
3734 };
3735 
3736 void G1CollectedHeap::print_cset_rsets() {
3737   PrintRSetsClosure cl("Printing CSet RSets");
3738   collection_set_iterate(&cl);
3739 }
3740 
3741 void G1CollectedHeap::print_all_rsets() {
3742   PrintRSetsClosure cl("Printing All RSets");;
3743   heap_region_iterate(&cl);
3744 }
3745 #endif // PRODUCT
3746 
3747 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {
3748   YoungList* young_list = heap()->young_list();
3749 
3750   size_t eden_used_bytes = young_list->eden_used_bytes();
3751   size_t survivor_used_bytes = young_list->survivor_used_bytes();
3752 
3753   size_t eden_capacity_bytes =
3754     (g1_policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;
3755 
3756   VirtualSpaceSummary heap_summary = create_heap_space_summary();
3757   return G1HeapSummary(heap_summary, used(), eden_used_bytes, eden_capacity_bytes, survivor_used_bytes);
3758 }
3759 
3760 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
3761   const G1HeapSummary& heap_summary = create_g1_heap_summary();
3762   gc_tracer->report_gc_heap_summary(when, heap_summary);
3763 
3764   const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
3765   gc_tracer->report_metaspace_summary(when, metaspace_summary);
3766 }
3767 
3768 
3769 G1CollectedHeap* G1CollectedHeap::heap() {
3770   CollectedHeap* heap = Universe::heap();
3771   assert(heap != NULL, "Uninitialized access to G1CollectedHeap::heap()");
3772   assert(heap->kind() == CollectedHeap::G1CollectedHeap, "Not a G1CollectedHeap");
3773   return (G1CollectedHeap*)heap;
3774 }
3775 
3776 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
3777   // always_do_update_barrier = false;
3778   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
3779   // Fill TLAB's and such
3780   accumulate_statistics_all_tlabs();
3781   ensure_parsability(true);
3782 
3783   if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) &&
3784       (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
3785     g1_rem_set()->print_periodic_summary_info("Before GC RS summary");
3786   }
3787 }
3788 
3789 void G1CollectedHeap::gc_epilogue(bool full) {
3790 
3791   if (G1SummarizeRSetStats &&
3792       (G1SummarizeRSetStatsPeriod > 0) &&
3793       // we are at the end of the GC. Total collections has already been increased.
3794       ((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) {
3795     g1_rem_set()->print_periodic_summary_info("After GC RS summary");
3796   }
3797 
3798   // FIXME: what is this about?
3799   // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
3800   // is set.
3801   COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
3802                         "derived pointer present"));
3803   // always_do_update_barrier = true;
3804 
3805   resize_all_tlabs();
3806   allocation_context_stats().update(full);
3807 
3808   // We have just completed a GC. Update the soft reference
3809   // policy with the new heap occupancy
3810   Universe::update_heap_info_at_gc();
3811 }
3812 
3813 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
3814                                                uint gc_count_before,
3815                                                bool* succeeded,
3816                                                GCCause::Cause gc_cause) {
3817   assert_heap_not_locked_and_not_at_safepoint();
3818   g1_policy()->record_stop_world_start();
3819   VM_G1IncCollectionPause op(gc_count_before,
3820                              word_size,
3821                              false, /* should_initiate_conc_mark */
3822                              g1_policy()->max_pause_time_ms(),
3823                              gc_cause);
3824 
3825   op.set_allocation_context(AllocationContext::current());
3826   VMThread::execute(&op);
3827 
3828   HeapWord* result = op.result();
3829   bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
3830   assert(result == NULL || ret_succeeded,
3831          "the result should be NULL if the VM did not succeed");
3832   *succeeded = ret_succeeded;
3833 
3834   assert_heap_not_locked();
3835   return result;
3836 }
3837 
3838 void
3839 G1CollectedHeap::doConcurrentMark() {
3840   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
3841   if (!_cmThread->in_progress()) {
3842     _cmThread->set_started();
3843     CGC_lock->notify();
3844   }
3845 }
3846 
3847 size_t G1CollectedHeap::pending_card_num() {
3848   size_t extra_cards = 0;
3849   JavaThread *curr = Threads::first();
3850   while (curr != NULL) {
3851     DirtyCardQueue& dcq = curr->dirty_card_queue();
3852     extra_cards += dcq.size();
3853     curr = curr->next();
3854   }
3855   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
3856   size_t buffer_size = dcqs.buffer_size();
3857   size_t buffer_num = dcqs.completed_buffers_num();
3858 
3859   // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes
3860   // in bytes - not the number of 'entries'. We need to convert
3861   // into a number of cards.
3862   return (buffer_size * buffer_num + extra_cards) / oopSize;
3863 }
3864 
3865 size_t G1CollectedHeap::cards_scanned() {
3866   return g1_rem_set()->cardsScanned();
3867 }
3868 
3869 class RegisterHumongousWithInCSetFastTestClosure : public HeapRegionClosure {
3870  private:
3871   size_t _total_humongous;
3872   size_t _candidate_humongous;
3873 
3874   DirtyCardQueue _dcq;
3875 
3876   // We don't nominate objects with many remembered set entries, on
3877   // the assumption that such objects are likely still live.
3878   bool is_remset_small(HeapRegion* region) const {
3879     HeapRegionRemSet* const rset = region->rem_set();
3880     return G1EagerReclaimHumongousObjectsWithStaleRefs
3881       ? rset->occupancy_less_or_equal_than(G1RSetSparseRegionEntries)
3882       : rset->is_empty();
3883   }
3884 
3885   bool is_typeArray_region(HeapRegion* region) const {
3886     return oop(region->bottom())->is_typeArray();
3887   }
3888 
3889   bool humongous_region_is_candidate(G1CollectedHeap* heap, HeapRegion* region) const {
3890     assert(region->is_starts_humongous(), "Must start a humongous object");
3891 
3892     // Candidate selection must satisfy the following constraints
3893     // while concurrent marking is in progress:
3894     //
3895     // * In order to maintain SATB invariants, an object must not be
3896     // reclaimed if it was allocated before the start of marking and
3897     // has not had its references scanned.  Such an object must have
3898     // its references (including type metadata) scanned to ensure no
3899     // live objects are missed by the marking process.  Objects
3900     // allocated after the start of concurrent marking don't need to
3901     // be scanned.
3902     //
3903     // * An object must not be reclaimed if it is on the concurrent
3904     // mark stack.  Objects allocated after the start of concurrent
3905     // marking are never pushed on the mark stack.
3906     //
3907     // Nominating only objects allocated after the start of concurrent
3908     // marking is sufficient to meet both constraints.  This may miss
3909     // some objects that satisfy the constraints, but the marking data
3910     // structures don't support efficiently performing the needed
3911     // additional tests or scrubbing of the mark stack.
3912     //
3913     // However, we presently only nominate is_typeArray() objects.
3914     // A humongous object containing references induces remembered
3915     // set entries on other regions.  In order to reclaim such an
3916     // object, those remembered sets would need to be cleaned up.
3917     //
3918     // We also treat is_typeArray() objects specially, allowing them
3919     // to be reclaimed even if allocated before the start of
3920     // concurrent mark.  For this we rely on mark stack insertion to
3921     // exclude is_typeArray() objects, preventing reclaiming an object
3922     // that is in the mark stack.  We also rely on the metadata for
3923     // such objects to be built-in and so ensured to be kept live.
3924     // Frequent allocation and drop of large binary blobs is an
3925     // important use case for eager reclaim, and this special handling
3926     // may reduce needed headroom.
3927 
3928     return is_typeArray_region(region) && is_remset_small(region);
3929   }
3930 
3931  public:
3932   RegisterHumongousWithInCSetFastTestClosure()
3933   : _total_humongous(0),
3934     _candidate_humongous(0),
3935     _dcq(&JavaThread::dirty_card_queue_set()) {
3936   }
3937 
3938   virtual bool doHeapRegion(HeapRegion* r) {
3939     if (!r->is_starts_humongous()) {
3940       return false;
3941     }
3942     G1CollectedHeap* g1h = G1CollectedHeap::heap();
3943 
3944     bool is_candidate = humongous_region_is_candidate(g1h, r);
3945     uint rindex = r->hrm_index();
3946     g1h->set_humongous_reclaim_candidate(rindex, is_candidate);
3947     if (is_candidate) {
3948       _candidate_humongous++;
3949       g1h->register_humongous_region_with_cset(rindex);
3950       // Is_candidate already filters out humongous object with large remembered sets.
3951       // If we have a humongous object with a few remembered sets, we simply flush these
3952       // remembered set entries into the DCQS. That will result in automatic
3953       // re-evaluation of their remembered set entries during the following evacuation
3954       // phase.
3955       if (!r->rem_set()->is_empty()) {
3956         guarantee(r->rem_set()->occupancy_less_or_equal_than(G1RSetSparseRegionEntries),
3957                   "Found a not-small remembered set here. This is inconsistent with previous assumptions.");
3958         G1SATBCardTableLoggingModRefBS* bs = g1h->g1_barrier_set();
3959         HeapRegionRemSetIterator hrrs(r->rem_set());
3960         size_t card_index;
3961         while (hrrs.has_next(card_index)) {
3962           jbyte* card_ptr = (jbyte*)bs->byte_for_index(card_index);
3963           // The remembered set might contain references to already freed
3964           // regions. Filter out such entries to avoid failing card table
3965           // verification.
3966           if (!g1h->heap_region_containing(bs->addr_for(card_ptr))->is_free()) {
3967             if (*card_ptr != CardTableModRefBS::dirty_card_val()) {
3968               *card_ptr = CardTableModRefBS::dirty_card_val();
3969               _dcq.enqueue(card_ptr);
3970             }
3971           }
3972         }
3973         r->rem_set()->clear_locked();
3974       }
3975       assert(r->rem_set()->is_empty(), "At this point any humongous candidate remembered set must be empty.");
3976     }
3977     _total_humongous++;
3978 
3979     return false;
3980   }
3981 
3982   size_t total_humongous() const { return _total_humongous; }
3983   size_t candidate_humongous() const { return _candidate_humongous; }
3984 
3985   void flush_rem_set_entries() { _dcq.flush(); }
3986 };
3987 
3988 void G1CollectedHeap::register_humongous_regions_with_cset() {
3989   if (!G1EagerReclaimHumongousObjects) {
3990     g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(0.0, 0, 0);
3991     return;
3992   }
3993   double time = os::elapsed_counter();
3994 
3995   // Collect reclaim candidate information and register candidates with cset.
3996   RegisterHumongousWithInCSetFastTestClosure cl;
3997   heap_region_iterate(&cl);
3998 
3999   time = ((double)(os::elapsed_counter() - time) / os::elapsed_frequency()) * 1000.0;
4000   g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(time,
4001                                                                   cl.total_humongous(),
4002                                                                   cl.candidate_humongous());
4003   _has_humongous_reclaim_candidates = cl.candidate_humongous() > 0;
4004 
4005   // Finally flush all remembered set entries to re-check into the global DCQS.
4006   cl.flush_rem_set_entries();
4007 }
4008 
4009 void
4010 G1CollectedHeap::setup_surviving_young_words() {
4011   assert(_surviving_young_words == NULL, "pre-condition");
4012   uint array_length = g1_policy()->young_cset_region_length();
4013   _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC);
4014   if (_surviving_young_words == NULL) {
4015     vm_exit_out_of_memory(sizeof(size_t) * array_length, OOM_MALLOC_ERROR,
4016                           "Not enough space for young surv words summary.");
4017   }
4018   memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t));
4019 #ifdef ASSERT
4020   for (uint i = 0;  i < array_length; ++i) {
4021     assert( _surviving_young_words[i] == 0, "memset above" );
4022   }
4023 #endif // !ASSERT
4024 }
4025 
4026 void
4027 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
4028   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
4029   uint array_length = g1_policy()->young_cset_region_length();
4030   for (uint i = 0; i < array_length; ++i) {
4031     _surviving_young_words[i] += surv_young_words[i];
4032   }
4033 }
4034 
4035 void
4036 G1CollectedHeap::cleanup_surviving_young_words() {
4037   guarantee( _surviving_young_words != NULL, "pre-condition" );
4038   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words);
4039   _surviving_young_words = NULL;
4040 }
4041 
4042 #ifdef ASSERT
4043 class VerifyCSetClosure: public HeapRegionClosure {
4044 public:
4045   bool doHeapRegion(HeapRegion* hr) {
4046     // Here we check that the CSet region's RSet is ready for parallel
4047     // iteration. The fields that we'll verify are only manipulated
4048     // when the region is part of a CSet and is collected. Afterwards,
4049     // we reset these fields when we clear the region's RSet (when the
4050     // region is freed) so they are ready when the region is
4051     // re-allocated. The only exception to this is if there's an
4052     // evacuation failure and instead of freeing the region we leave
4053     // it in the heap. In that case, we reset these fields during
4054     // evacuation failure handling.
4055     guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");
4056 
4057     // Here's a good place to add any other checks we'd like to
4058     // perform on CSet regions.
4059     return false;
4060   }
4061 };
4062 #endif // ASSERT
4063 
4064 uint G1CollectedHeap::num_task_queues() const {
4065   return _task_queues->size();
4066 }
4067 
4068 #if TASKQUEUE_STATS
4069 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
4070   st->print_raw_cr("GC Task Stats");
4071   st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
4072   st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
4073 }
4074 
4075 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
4076   print_taskqueue_stats_hdr(st);
4077 
4078   TaskQueueStats totals;
4079   const uint n = num_task_queues();
4080   for (uint i = 0; i < n; ++i) {
4081     st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr();
4082     totals += task_queue(i)->stats;
4083   }
4084   st->print_raw("tot "); totals.print(st); st->cr();
4085 
4086   DEBUG_ONLY(totals.verify());
4087 }
4088 
4089 void G1CollectedHeap::reset_taskqueue_stats() {
4090   const uint n = num_task_queues();
4091   for (uint i = 0; i < n; ++i) {
4092     task_queue(i)->stats.reset();
4093   }
4094 }
4095 #endif // TASKQUEUE_STATS
4096 
4097 void G1CollectedHeap::log_gc_header() {
4098   if (!G1Log::fine()) {
4099     return;
4100   }
4101 
4102   gclog_or_tty->gclog_stamp(_gc_tracer_stw->gc_id());
4103 
4104   GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
4105     .append(collector_state()->gcs_are_young() ? "(young)" : "(mixed)")
4106     .append(collector_state()->during_initial_mark_pause() ? " (initial-mark)" : "");
4107 
4108   gclog_or_tty->print("[%s", (const char*)gc_cause_str);
4109 }
4110 
4111 void G1CollectedHeap::log_gc_footer(double pause_time_sec) {
4112   if (!G1Log::fine()) {
4113     return;
4114   }
4115 
4116   if (G1Log::finer()) {
4117     if (evacuation_failed()) {
4118       gclog_or_tty->print(" (to-space exhausted)");
4119     }
4120     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
4121     g1_policy()->phase_times()->note_gc_end();
4122     g1_policy()->phase_times()->print(pause_time_sec);
4123     g1_policy()->print_detailed_heap_transition();
4124   } else {
4125     if (evacuation_failed()) {
4126       gclog_or_tty->print("--");
4127     }
4128     g1_policy()->print_heap_transition();
4129     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
4130   }
4131   gclog_or_tty->flush();
4132 }
4133 
4134 void G1CollectedHeap::wait_for_root_region_scanning() {
4135   double scan_wait_start = os::elapsedTime();
4136   // We have to wait until the CM threads finish scanning the
4137   // root regions as it's the only way to ensure that all the
4138   // objects on them have been correctly scanned before we start
4139   // moving them during the GC.
4140   bool waited = _cm->root_regions()->wait_until_scan_finished();
4141   double wait_time_ms = 0.0;
4142   if (waited) {
4143     double scan_wait_end = os::elapsedTime();
4144     wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
4145   }
4146   g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms);
4147 }
4148 
4149 bool
4150 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
4151   assert_at_safepoint(true /* should_be_vm_thread */);
4152   guarantee(!is_gc_active(), "collection is not reentrant");
4153 
4154   if (GC_locker::check_active_before_gc()) {
4155     return false;
4156   }
4157 
4158   _gc_timer_stw->register_gc_start();
4159 
4160   _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
4161 
4162   SvcGCMarker sgcm(SvcGCMarker::MINOR);
4163   ResourceMark rm;
4164 
4165   wait_for_root_region_scanning();
4166 
4167   G1Log::update_level();
4168   print_heap_before_gc();
4169   trace_heap_before_gc(_gc_tracer_stw);
4170 
4171   verify_region_sets_optional();
4172   verify_dirty_young_regions();
4173 
4174   // This call will decide whether this pause is an initial-mark
4175   // pause. If it is, during_initial_mark_pause() will return true
4176   // for the duration of this pause.
4177   g1_policy()->decide_on_conc_mark_initiation();
4178 
4179   // We do not allow initial-mark to be piggy-backed on a mixed GC.
4180   assert(!collector_state()->during_initial_mark_pause() ||
4181           collector_state()->gcs_are_young(), "sanity");
4182 
4183   // We also do not allow mixed GCs during marking.
4184   assert(!collector_state()->mark_in_progress() || collector_state()->gcs_are_young(), "sanity");
4185 
4186   // Record whether this pause is an initial mark. When the current
4187   // thread has completed its logging output and it's safe to signal
4188   // the CM thread, the flag's value in the policy has been reset.
4189   bool should_start_conc_mark = collector_state()->during_initial_mark_pause();
4190 
4191   // Inner scope for scope based logging, timers, and stats collection
4192   {
4193     EvacuationInfo evacuation_info;
4194 
4195     if (collector_state()->during_initial_mark_pause()) {
4196       // We are about to start a marking cycle, so we increment the
4197       // full collection counter.
4198       increment_old_marking_cycles_started();
4199       register_concurrent_cycle_start(_gc_timer_stw->gc_start());
4200     }
4201 
4202     _gc_tracer_stw->report_yc_type(collector_state()->yc_type());
4203 
4204     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
4205 
4206     uint active_workers = AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
4207                                                                   workers()->active_workers(),
4208                                                                   Threads::number_of_non_daemon_threads());
4209     workers()->set_active_workers(active_workers);
4210 
4211     double pause_start_sec = os::elapsedTime();
4212     g1_policy()->phase_times()->note_gc_start(active_workers, collector_state()->mark_in_progress());
4213     log_gc_header();
4214 
4215     TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
4216     TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
4217 
4218     // If the secondary_free_list is not empty, append it to the
4219     // free_list. No need to wait for the cleanup operation to finish;
4220     // the region allocation code will check the secondary_free_list
4221     // and wait if necessary. If the G1StressConcRegionFreeing flag is
4222     // set, skip this step so that the region allocation code has to
4223     // get entries from the secondary_free_list.
4224     if (!G1StressConcRegionFreeing) {
4225       append_secondary_free_list_if_not_empty_with_lock();
4226     }
4227 
4228     assert(check_young_list_well_formed(), "young list should be well formed");
4229 
4230     // Don't dynamically change the number of GC threads this early.  A value of
4231     // 0 is used to indicate serial work.  When parallel work is done,
4232     // it will be set.
4233 
4234     { // Call to jvmpi::post_class_unload_events must occur outside of active GC
4235       IsGCActiveMark x;
4236 
4237       gc_prologue(false);
4238       increment_total_collections(false /* full gc */);
4239       increment_gc_time_stamp();
4240 
4241       verify_before_gc();
4242 
4243       check_bitmaps("GC Start");
4244 
4245       COMPILER2_PRESENT(DerivedPointerTable::clear());
4246 
4247       // Please see comment in g1CollectedHeap.hpp and
4248       // G1CollectedHeap::ref_processing_init() to see how
4249       // reference processing currently works in G1.
4250 
4251       // Enable discovery in the STW reference processor
4252       ref_processor_stw()->enable_discovery();
4253 
4254       {
4255         // We want to temporarily turn off discovery by the
4256         // CM ref processor, if necessary, and turn it back on
4257         // on again later if we do. Using a scoped
4258         // NoRefDiscovery object will do this.
4259         NoRefDiscovery no_cm_discovery(ref_processor_cm());
4260 
4261         // Forget the current alloc region (we might even choose it to be part
4262         // of the collection set!).
4263         _allocator->release_mutator_alloc_region();
4264 
4265         // We should call this after we retire the mutator alloc
4266         // region(s) so that all the ALLOC / RETIRE events are generated
4267         // before the start GC event.
4268         _hr_printer.start_gc(false /* full */, (size_t) total_collections());
4269 
4270         // This timing is only used by the ergonomics to handle our pause target.
4271         // It is unclear why this should not include the full pause. We will
4272         // investigate this in CR 7178365.
4273         //
4274         // Preserving the old comment here if that helps the investigation:
4275         //
4276         // The elapsed time induced by the start time below deliberately elides
4277         // the possible verification above.
4278         double sample_start_time_sec = os::elapsedTime();
4279 
4280 #if YOUNG_LIST_VERBOSE
4281         gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
4282         _young_list->print();
4283         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4284 #endif // YOUNG_LIST_VERBOSE
4285 
4286         g1_policy()->record_collection_pause_start(sample_start_time_sec);
4287 
4288 #if YOUNG_LIST_VERBOSE
4289         gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
4290         _young_list->print();
4291 #endif // YOUNG_LIST_VERBOSE
4292 
4293         if (collector_state()->during_initial_mark_pause()) {
4294           concurrent_mark()->checkpointRootsInitialPre();
4295         }
4296 
4297 #if YOUNG_LIST_VERBOSE
4298         gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
4299         _young_list->print();
4300         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4301 #endif // YOUNG_LIST_VERBOSE
4302 
4303         g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info);
4304 
4305         register_humongous_regions_with_cset();
4306 
4307         assert(check_cset_fast_test(), "Inconsistency in the InCSetState table.");
4308 
4309         _cm->note_start_of_gc();
4310         // We call this after finalize_cset() to
4311         // ensure that the CSet has been finalized.
4312         _cm->verify_no_cset_oops();
4313 
4314         if (_hr_printer.is_active()) {
4315           HeapRegion* hr = g1_policy()->collection_set();
4316           while (hr != NULL) {
4317             _hr_printer.cset(hr);
4318             hr = hr->next_in_collection_set();
4319           }
4320         }
4321 
4322 #ifdef ASSERT
4323         VerifyCSetClosure cl;
4324         collection_set_iterate(&cl);
4325 #endif // ASSERT
4326 
4327         setup_surviving_young_words();
4328 
4329         // Initialize the GC alloc regions.
4330         _allocator->init_gc_alloc_regions(evacuation_info);
4331 
4332         // Actually do the work...
4333         evacuate_collection_set(evacuation_info);
4334 
4335         free_collection_set(g1_policy()->collection_set(), evacuation_info);
4336 
4337         eagerly_reclaim_humongous_regions();
4338 
4339         g1_policy()->clear_collection_set();
4340 
4341         cleanup_surviving_young_words();
4342 
4343         // Start a new incremental collection set for the next pause.
4344         g1_policy()->start_incremental_cset_building();
4345 
4346         clear_cset_fast_test();
4347 
4348         _young_list->reset_sampled_info();
4349 
4350         // Don't check the whole heap at this point as the
4351         // GC alloc regions from this pause have been tagged
4352         // as survivors and moved on to the survivor list.
4353         // Survivor regions will fail the !is_young() check.
4354         assert(check_young_list_empty(false /* check_heap */),
4355           "young list should be empty");
4356 
4357 #if YOUNG_LIST_VERBOSE
4358         gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
4359         _young_list->print();
4360 #endif // YOUNG_LIST_VERBOSE
4361 
4362         g1_policy()->record_survivor_regions(_young_list->survivor_length(),
4363                                              _young_list->first_survivor_region(),
4364                                              _young_list->last_survivor_region());
4365 
4366         _young_list->reset_auxilary_lists();
4367 
4368         if (evacuation_failed()) {
4369           set_used(recalculate_used());
4370           if (_archive_allocator != NULL) {
4371             _archive_allocator->clear_used();
4372           }
4373           for (uint i = 0; i < ParallelGCThreads; i++) {
4374             if (_evacuation_failed_info_array[i].has_failed()) {
4375               _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4376             }
4377           }
4378         } else {
4379           // The "used" of the the collection set have already been subtracted
4380           // when they were freed.  Add in the bytes evacuated.
4381           increase_used(g1_policy()->bytes_copied_during_gc());
4382         }
4383 
4384         if (collector_state()->during_initial_mark_pause()) {
4385           // We have to do this before we notify the CM threads that
4386           // they can start working to make sure that all the
4387           // appropriate initialization is done on the CM object.
4388           concurrent_mark()->checkpointRootsInitialPost();
4389           collector_state()->set_mark_in_progress(true);
4390           // Note that we don't actually trigger the CM thread at
4391           // this point. We do that later when we're sure that
4392           // the current thread has completed its logging output.
4393         }
4394 
4395         allocate_dummy_regions();
4396 
4397 #if YOUNG_LIST_VERBOSE
4398         gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
4399         _young_list->print();
4400         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4401 #endif // YOUNG_LIST_VERBOSE
4402 
4403         _allocator->init_mutator_alloc_region();
4404 
4405         {
4406           size_t expand_bytes = g1_policy()->expansion_amount();
4407           if (expand_bytes > 0) {
4408             size_t bytes_before = capacity();
4409             // No need for an ergo verbose message here,
4410             // expansion_amount() does this when it returns a value > 0.
4411             if (!expand(expand_bytes)) {
4412               // We failed to expand the heap. Cannot do anything about it.
4413             }
4414           }
4415         }
4416 
4417         // We redo the verification but now wrt to the new CSet which
4418         // has just got initialized after the previous CSet was freed.
4419         _cm->verify_no_cset_oops();
4420         _cm->note_end_of_gc();
4421 
4422         // This timing is only used by the ergonomics to handle our pause target.
4423         // It is unclear why this should not include the full pause. We will
4424         // investigate this in CR 7178365.
4425         double sample_end_time_sec = os::elapsedTime();
4426         double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
4427         g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info);
4428 
4429         MemoryService::track_memory_usage();
4430 
4431         // In prepare_for_verify() below we'll need to scan the deferred
4432         // update buffers to bring the RSets up-to-date if
4433         // G1HRRSFlushLogBuffersOnVerify has been set. While scanning
4434         // the update buffers we'll probably need to scan cards on the
4435         // regions we just allocated to (i.e., the GC alloc
4436         // regions). However, during the last GC we called
4437         // set_saved_mark() on all the GC alloc regions, so card
4438         // scanning might skip the [saved_mark_word()...top()] area of
4439         // those regions (i.e., the area we allocated objects into
4440         // during the last GC). But it shouldn't. Given that
4441         // saved_mark_word() is conditional on whether the GC time stamp
4442         // on the region is current or not, by incrementing the GC time
4443         // stamp here we invalidate all the GC time stamps on all the
4444         // regions and saved_mark_word() will simply return top() for
4445         // all the regions. This is a nicer way of ensuring this rather
4446         // than iterating over the regions and fixing them. In fact, the
4447         // GC time stamp increment here also ensures that
4448         // saved_mark_word() will return top() between pauses, i.e.,
4449         // during concurrent refinement. So we don't need the
4450         // is_gc_active() check to decided which top to use when
4451         // scanning cards (see CR 7039627).
4452         increment_gc_time_stamp();
4453 
4454         verify_after_gc();
4455         check_bitmaps("GC End");
4456 
4457         assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
4458         ref_processor_stw()->verify_no_references_recorded();
4459 
4460         // CM reference discovery will be re-enabled if necessary.
4461       }
4462 
4463       // We should do this after we potentially expand the heap so
4464       // that all the COMMIT events are generated before the end GC
4465       // event, and after we retire the GC alloc regions so that all
4466       // RETIRE events are generated before the end GC event.
4467       _hr_printer.end_gc(false /* full */, (size_t) total_collections());
4468 
4469 #ifdef TRACESPINNING
4470       ParallelTaskTerminator::print_termination_counts();
4471 #endif
4472 
4473       gc_epilogue(false);
4474     }
4475 
4476     // Print the remainder of the GC log output.
4477     log_gc_footer(os::elapsedTime() - pause_start_sec);
4478 
4479     // It is not yet to safe to tell the concurrent mark to
4480     // start as we have some optional output below. We don't want the
4481     // output from the concurrent mark thread interfering with this
4482     // logging output either.
4483 
4484     _hrm.verify_optional();
4485     verify_region_sets_optional();
4486 
4487     TASKQUEUE_STATS_ONLY(if (PrintTaskqueue) print_taskqueue_stats());
4488     TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
4489 
4490     print_heap_after_gc();
4491     trace_heap_after_gc(_gc_tracer_stw);
4492 
4493     // We must call G1MonitoringSupport::update_sizes() in the same scoping level
4494     // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
4495     // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
4496     // before any GC notifications are raised.
4497     g1mm()->update_sizes();
4498 
4499     _gc_tracer_stw->report_evacuation_info(&evacuation_info);
4500     _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold());
4501     _gc_timer_stw->register_gc_end();
4502     _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());
4503   }
4504   // It should now be safe to tell the concurrent mark thread to start
4505   // without its logging output interfering with the logging output
4506   // that came from the pause.
4507 
4508   if (should_start_conc_mark) {
4509     // CAUTION: after the doConcurrentMark() call below,
4510     // the concurrent marking thread(s) could be running
4511     // concurrently with us. Make sure that anything after
4512     // this point does not assume that we are the only GC thread
4513     // running. Note: of course, the actual marking work will
4514     // not start until the safepoint itself is released in
4515     // SuspendibleThreadSet::desynchronize().
4516     doConcurrentMark();
4517   }
4518 
4519   return true;
4520 }
4521 
4522 void G1CollectedHeap::remove_self_forwarding_pointers() {
4523   double remove_self_forwards_start = os::elapsedTime();
4524 
4525   G1ParRemoveSelfForwardPtrsTask rsfp_task;
4526   workers()->run_task(&rsfp_task);
4527 
4528   // Now restore saved marks, if any.
4529   for (uint i = 0; i < ParallelGCThreads; i++) {
4530     OopAndMarkOopStack& cur = _preserved_objs[i];
4531     while (!cur.is_empty()) {
4532       OopAndMarkOop elem = cur.pop();
4533       elem.set_mark();
4534     }
4535     cur.clear(true);
4536   }
4537 
4538   g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0);
4539 }
4540 
4541 void G1CollectedHeap::preserve_mark_during_evac_failure(uint queue_num, oop obj, markOop m) {
4542   if (!_evacuation_failed) {
4543     _evacuation_failed = true;
4544   }
4545 
4546   _evacuation_failed_info_array[queue_num].register_copy_failure(obj->size());
4547 
4548   // We want to call the "for_promotion_failure" version only in the
4549   // case of a promotion failure.
4550   if (m->must_be_preserved_for_promotion_failure(obj)) {
4551     OopAndMarkOop elem(obj, m);
4552     _preserved_objs[queue_num].push(elem);
4553   }
4554 }
4555 
4556 void G1ParCopyHelper::mark_object(oop obj) {
4557   assert(!_g1->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet");
4558 
4559   // We know that the object is not moving so it's safe to read its size.
4560   _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
4561 }
4562 
4563 void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) {
4564   assert(from_obj->is_forwarded(), "from obj should be forwarded");
4565   assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");
4566   assert(from_obj != to_obj, "should not be self-forwarded");
4567 
4568   assert(_g1->heap_region_containing(from_obj)->in_collection_set(), "from obj should be in the CSet");
4569   assert(!_g1->heap_region_containing(to_obj)->in_collection_set(), "should not mark objects in the CSet");
4570 
4571   // The object might be in the process of being copied by another
4572   // worker so we cannot trust that its to-space image is
4573   // well-formed. So we have to read its size from its from-space
4574   // image which we know should not be changing.
4575   _cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);
4576 }
4577 
4578 template <class T>
4579 void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) {
4580   if (_g1->heap_region_containing_raw(new_obj)->is_young()) {
4581     _scanned_klass->record_modified_oops();
4582   }
4583 }
4584 
4585 template <G1Barrier barrier, G1Mark do_mark_object>
4586 template <class T>
4587 void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) {
4588   T heap_oop = oopDesc::load_heap_oop(p);
4589 
4590   if (oopDesc::is_null(heap_oop)) {
4591     return;
4592   }
4593 
4594   oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
4595 
4596   assert(_worker_id == _par_scan_state->queue_num(), "sanity");
4597 
4598   const InCSetState state = _g1->in_cset_state(obj);
4599   if (state.is_in_cset()) {
4600     oop forwardee;
4601     markOop m = obj->mark();
4602     if (m->is_marked()) {
4603       forwardee = (oop) m->decode_pointer();
4604     } else {
4605       forwardee = _par_scan_state->copy_to_survivor_space(state, obj, m);
4606     }
4607     assert(forwardee != NULL, "forwardee should not be NULL");
4608     oopDesc::encode_store_heap_oop(p, forwardee);
4609     if (do_mark_object != G1MarkNone && forwardee != obj) {
4610       // If the object is self-forwarded we don't need to explicitly
4611       // mark it, the evacuation failure protocol will do so.
4612       mark_forwarded_object(obj, forwardee);
4613     }
4614 
4615     if (barrier == G1BarrierKlass) {
4616       do_klass_barrier(p, forwardee);
4617     }
4618   } else {
4619     if (state.is_humongous()) {
4620       _g1->set_humongous_is_live(obj);
4621     }
4622     // The object is not in collection set. If we're a root scanning
4623     // closure during an initial mark pause then attempt to mark the object.
4624     if (do_mark_object == G1MarkFromRoot) {
4625       mark_object(obj);
4626     }
4627   }
4628 }
4629 
4630 class G1ParEvacuateFollowersClosure : public VoidClosure {
4631 protected:
4632   G1CollectedHeap*              _g1h;
4633   G1ParScanThreadState*         _par_scan_state;
4634   RefToScanQueueSet*            _queues;
4635   ParallelTaskTerminator*       _terminator;
4636 
4637   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
4638   RefToScanQueueSet*      queues()         { return _queues; }
4639   ParallelTaskTerminator* terminator()     { return _terminator; }
4640 
4641 public:
4642   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4643                                 G1ParScanThreadState* par_scan_state,
4644                                 RefToScanQueueSet* queues,
4645                                 ParallelTaskTerminator* terminator)
4646     : _g1h(g1h), _par_scan_state(par_scan_state),
4647       _queues(queues), _terminator(terminator) {}
4648 
4649   void do_void();
4650 
4651 private:
4652   inline bool offer_termination();
4653 };
4654 
4655 bool G1ParEvacuateFollowersClosure::offer_termination() {
4656   G1ParScanThreadState* const pss = par_scan_state();
4657   pss->start_term_time();
4658   const bool res = terminator()->offer_termination();
4659   pss->end_term_time();
4660   return res;
4661 }
4662 
4663 void G1ParEvacuateFollowersClosure::do_void() {
4664   G1ParScanThreadState* const pss = par_scan_state();
4665   pss->trim_queue();
4666   do {
4667     pss->steal_and_trim_queue(queues());
4668   } while (!offer_termination());
4669 }
4670 
4671 class G1KlassScanClosure : public KlassClosure {
4672  G1ParCopyHelper* _closure;
4673  bool             _process_only_dirty;
4674  int              _count;
4675  public:
4676   G1KlassScanClosure(G1ParCopyHelper* closure, bool process_only_dirty)
4677       : _process_only_dirty(process_only_dirty), _closure(closure), _count(0) {}
4678   void do_klass(Klass* klass) {
4679     // If the klass has not been dirtied we know that there's
4680     // no references into  the young gen and we can skip it.
4681    if (!_process_only_dirty || klass->has_modified_oops()) {
4682       // Clean the klass since we're going to scavenge all the metadata.
4683       klass->clear_modified_oops();
4684 
4685       // Tell the closure that this klass is the Klass to scavenge
4686       // and is the one to dirty if oops are left pointing into the young gen.
4687       _closure->set_scanned_klass(klass);
4688 
4689       klass->oops_do(_closure);
4690 
4691       _closure->set_scanned_klass(NULL);
4692     }
4693     _count++;
4694   }
4695 };
4696 
4697 class G1ParTask : public AbstractGangTask {
4698 protected:
4699   G1CollectedHeap*       _g1h;
4700   RefToScanQueueSet      *_queues;
4701   G1RootProcessor*       _root_processor;
4702   ParallelTaskTerminator _terminator;
4703   uint _n_workers;
4704 
4705   Mutex _stats_lock;
4706   Mutex* stats_lock() { return &_stats_lock; }
4707 
4708 public:
4709   G1ParTask(G1CollectedHeap* g1h, RefToScanQueueSet *task_queues, G1RootProcessor* root_processor, uint n_workers)
4710     : AbstractGangTask("G1 collection"),
4711       _g1h(g1h),
4712       _queues(task_queues),
4713       _root_processor(root_processor),
4714       _terminator(n_workers, _queues),
4715       _n_workers(n_workers),
4716       _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
4717   {}
4718 
4719   RefToScanQueueSet* queues() { return _queues; }
4720 
4721   RefToScanQueue *work_queue(int i) {
4722     return queues()->queue(i);
4723   }
4724 
4725   ParallelTaskTerminator* terminator() { return &_terminator; }
4726 
4727   // Helps out with CLD processing.
4728   //
4729   // During InitialMark we need to:
4730   // 1) Scavenge all CLDs for the young GC.
4731   // 2) Mark all objects directly reachable from strong CLDs.
4732   template <G1Mark do_mark_object>
4733   class G1CLDClosure : public CLDClosure {
4734     G1ParCopyClosure<G1BarrierNone,  do_mark_object>* _oop_closure;
4735     G1ParCopyClosure<G1BarrierKlass, do_mark_object>  _oop_in_klass_closure;
4736     G1KlassScanClosure                                _klass_in_cld_closure;
4737     bool                                              _claim;
4738 
4739    public:
4740     G1CLDClosure(G1ParCopyClosure<G1BarrierNone, do_mark_object>* oop_closure,
4741                  bool only_young, bool claim)
4742         : _oop_closure(oop_closure),
4743           _oop_in_klass_closure(oop_closure->g1(),
4744                                 oop_closure->pss(),
4745                                 oop_closure->rp()),
4746           _klass_in_cld_closure(&_oop_in_klass_closure, only_young),
4747           _claim(claim) {
4748 
4749     }
4750 
4751     void do_cld(ClassLoaderData* cld) {
4752       cld->oops_do(_oop_closure, &_klass_in_cld_closure, _claim);
4753     }
4754   };
4755 
4756   void work(uint worker_id) {
4757     if (worker_id >= _n_workers) return;  // no work needed this round
4758 
4759     _g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, os::elapsedTime());
4760 
4761     {
4762       ResourceMark rm;
4763       HandleMark   hm;
4764 
4765       ReferenceProcessor*             rp = _g1h->ref_processor_stw();
4766 
4767       G1ParScanThreadState            pss(_g1h, worker_id, rp);
4768 
4769       bool only_young = _g1h->collector_state()->gcs_are_young();
4770 
4771       // Non-IM young GC.
4772       G1ParCopyClosure<G1BarrierNone, G1MarkNone>             scan_only_root_cl(_g1h, &pss, rp);
4773       G1CLDClosure<G1MarkNone>                                scan_only_cld_cl(&scan_only_root_cl,
4774                                                                                only_young, // Only process dirty klasses.
4775                                                                                false);     // No need to claim CLDs.
4776       // IM young GC.
4777       //    Strong roots closures.
4778       G1ParCopyClosure<G1BarrierNone, G1MarkFromRoot>         scan_mark_root_cl(_g1h, &pss, rp);
4779       G1CLDClosure<G1MarkFromRoot>                            scan_mark_cld_cl(&scan_mark_root_cl,
4780                                                                                false, // Process all klasses.
4781                                                                                true); // Need to claim CLDs.
4782       //    Weak roots closures.
4783       G1ParCopyClosure<G1BarrierNone, G1MarkPromotedFromRoot> scan_mark_weak_root_cl(_g1h, &pss, rp);
4784       G1CLDClosure<G1MarkPromotedFromRoot>                    scan_mark_weak_cld_cl(&scan_mark_weak_root_cl,
4785                                                                                     false, // Process all klasses.
4786                                                                                     true); // Need to claim CLDs.
4787 
4788       OopClosure* strong_root_cl;
4789       OopClosure* weak_root_cl;
4790       CLDClosure* strong_cld_cl;
4791       CLDClosure* weak_cld_cl;
4792 
4793       bool trace_metadata = false;
4794 
4795       if (_g1h->collector_state()->during_initial_mark_pause()) {
4796         // We also need to mark copied objects.
4797         strong_root_cl = &scan_mark_root_cl;
4798         strong_cld_cl  = &scan_mark_cld_cl;
4799         if (ClassUnloadingWithConcurrentMark) {
4800           weak_root_cl = &scan_mark_weak_root_cl;
4801           weak_cld_cl  = &scan_mark_weak_cld_cl;
4802           trace_metadata = true;
4803         } else {
4804           weak_root_cl = &scan_mark_root_cl;
4805           weak_cld_cl  = &scan_mark_cld_cl;
4806         }
4807       } else {
4808         strong_root_cl = &scan_only_root_cl;
4809         weak_root_cl   = &scan_only_root_cl;
4810         strong_cld_cl  = &scan_only_cld_cl;
4811         weak_cld_cl    = &scan_only_cld_cl;
4812       }
4813 
4814       pss.start_strong_roots();
4815 
4816       _root_processor->evacuate_roots(strong_root_cl,
4817                                       weak_root_cl,
4818                                       strong_cld_cl,
4819                                       weak_cld_cl,
4820                                       trace_metadata,
4821                                       worker_id);
4822 
4823       G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);
4824       _root_processor->scan_remembered_sets(&push_heap_rs_cl,
4825                                             weak_root_cl,
4826                                             worker_id);
4827       pss.end_strong_roots();
4828 
4829       {
4830         double start = os::elapsedTime();
4831         G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
4832         evac.do_void();
4833         double elapsed_sec = os::elapsedTime() - start;
4834         double term_sec = pss.term_time();
4835         _g1h->g1_policy()->phase_times()->add_time_secs(G1GCPhaseTimes::ObjCopy, worker_id, elapsed_sec - term_sec);
4836         _g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::Termination, worker_id, term_sec);
4837         _g1h->g1_policy()->phase_times()->record_thread_work_item(G1GCPhaseTimes::Termination, worker_id, pss.term_attempts());
4838       }
4839       _g1h->g1_policy()->record_thread_age_table(pss.age_table());
4840       _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
4841 
4842       if (PrintTerminationStats) {
4843         MutexLocker x(stats_lock());
4844         pss.print_termination_stats(worker_id);
4845       }
4846 
4847       assert(pss.queue_is_empty(), "should be empty");
4848 
4849       // Close the inner scope so that the ResourceMark and HandleMark
4850       // destructors are executed here and are included as part of the
4851       // "GC Worker Time".
4852     }
4853     _g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, os::elapsedTime());
4854   }
4855 };
4856 
4857 class G1StringSymbolTableUnlinkTask : public AbstractGangTask {
4858 private:
4859   BoolObjectClosure* _is_alive;
4860   int _initial_string_table_size;
4861   int _initial_symbol_table_size;
4862 
4863   bool  _process_strings;
4864   int _strings_processed;
4865   int _strings_removed;
4866 
4867   bool  _process_symbols;
4868   int _symbols_processed;
4869   int _symbols_removed;
4870 
4871 public:
4872   G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :
4873     AbstractGangTask("String/Symbol Unlinking"),
4874     _is_alive(is_alive),
4875     _process_strings(process_strings), _strings_processed(0), _strings_removed(0),
4876     _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {
4877 
4878     _initial_string_table_size = StringTable::the_table()->table_size();
4879     _initial_symbol_table_size = SymbolTable::the_table()->table_size();
4880     if (process_strings) {
4881       StringTable::clear_parallel_claimed_index();
4882     }
4883     if (process_symbols) {
4884       SymbolTable::clear_parallel_claimed_index();
4885     }
4886   }
4887 
4888   ~G1StringSymbolTableUnlinkTask() {
4889     guarantee(!_process_strings || StringTable::parallel_claimed_index() >= _initial_string_table_size,
4890               err_msg("claim value %d after unlink less than initial string table size %d",
4891                       StringTable::parallel_claimed_index(), _initial_string_table_size));
4892     guarantee(!_process_symbols || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
4893               err_msg("claim value %d after unlink less than initial symbol table size %d",
4894                       SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
4895 
4896     if (G1TraceStringSymbolTableScrubbing) {
4897       gclog_or_tty->print_cr("Cleaned string and symbol table, "
4898                              "strings: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed, "
4899                              "symbols: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed",
4900                              strings_processed(), strings_removed(),
4901                              symbols_processed(), symbols_removed());
4902     }
4903   }
4904 
4905   void work(uint worker_id) {
4906     int strings_processed = 0;
4907     int strings_removed = 0;
4908     int symbols_processed = 0;
4909     int symbols_removed = 0;
4910     if (_process_strings) {
4911       StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed);
4912       Atomic::add(strings_processed, &_strings_processed);
4913       Atomic::add(strings_removed, &_strings_removed);
4914     }
4915     if (_process_symbols) {
4916       SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed);
4917       Atomic::add(symbols_processed, &_symbols_processed);
4918       Atomic::add(symbols_removed, &_symbols_removed);
4919     }
4920   }
4921 
4922   size_t strings_processed() const { return (size_t)_strings_processed; }
4923   size_t strings_removed()   const { return (size_t)_strings_removed; }
4924 
4925   size_t symbols_processed() const { return (size_t)_symbols_processed; }
4926   size_t symbols_removed()   const { return (size_t)_symbols_removed; }
4927 };
4928 
4929 class G1CodeCacheUnloadingTask VALUE_OBJ_CLASS_SPEC {
4930 private:
4931   static Monitor* _lock;
4932 
4933   BoolObjectClosure* const _is_alive;
4934   const bool               _unloading_occurred;
4935   const uint               _num_workers;
4936 
4937   // Variables used to claim nmethods.
4938   nmethod* _first_nmethod;
4939   volatile nmethod* _claimed_nmethod;
4940 
4941   // The list of nmethods that need to be processed by the second pass.
4942   volatile nmethod* _postponed_list;
4943   volatile uint     _num_entered_barrier;
4944 
4945  public:
4946   G1CodeCacheUnloadingTask(uint num_workers, BoolObjectClosure* is_alive, bool unloading_occurred) :
4947       _is_alive(is_alive),
4948       _unloading_occurred(unloading_occurred),
4949       _num_workers(num_workers),
4950       _first_nmethod(NULL),
4951       _claimed_nmethod(NULL),
4952       _postponed_list(NULL),
4953       _num_entered_barrier(0)
4954   {
4955     nmethod::increase_unloading_clock();
4956     // Get first alive nmethod
4957     NMethodIterator iter = NMethodIterator();
4958     if(iter.next_alive()) {
4959       _first_nmethod = iter.method();
4960     }
4961     _claimed_nmethod = (volatile nmethod*)_first_nmethod;
4962   }
4963 
4964   ~G1CodeCacheUnloadingTask() {
4965     CodeCache::verify_clean_inline_caches();
4966 
4967     CodeCache::set_needs_cache_clean(false);
4968     guarantee(CodeCache::scavenge_root_nmethods() == NULL, "Must be");
4969 
4970     CodeCache::verify_icholder_relocations();
4971   }
4972 
4973  private:
4974   void add_to_postponed_list(nmethod* nm) {
4975       nmethod* old;
4976       do {
4977         old = (nmethod*)_postponed_list;
4978         nm->set_unloading_next(old);
4979       } while ((nmethod*)Atomic::cmpxchg_ptr(nm, &_postponed_list, old) != old);
4980   }
4981 
4982   void clean_nmethod(nmethod* nm) {
4983     bool postponed = nm->do_unloading_parallel(_is_alive, _unloading_occurred);
4984 
4985     if (postponed) {
4986       // This nmethod referred to an nmethod that has not been cleaned/unloaded yet.
4987       add_to_postponed_list(nm);
4988     }
4989 
4990     // Mark that this thread has been cleaned/unloaded.
4991     // After this call, it will be safe to ask if this nmethod was unloaded or not.
4992     nm->set_unloading_clock(nmethod::global_unloading_clock());
4993   }
4994 
4995   void clean_nmethod_postponed(nmethod* nm) {
4996     nm->do_unloading_parallel_postponed(_is_alive, _unloading_occurred);
4997   }
4998 
4999   static const int MaxClaimNmethods = 16;
5000 
5001   void claim_nmethods(nmethod** claimed_nmethods, int *num_claimed_nmethods) {
5002     nmethod* first;
5003     NMethodIterator last;
5004 
5005     do {
5006       *num_claimed_nmethods = 0;
5007 
5008       first = (nmethod*)_claimed_nmethod;
5009       last = NMethodIterator(first);
5010 
5011       if (first != NULL) {
5012 
5013         for (int i = 0; i < MaxClaimNmethods; i++) {
5014           if (!last.next_alive()) {
5015             break;
5016           }
5017           claimed_nmethods[i] = last.method();
5018           (*num_claimed_nmethods)++;
5019         }
5020       }
5021 
5022     } while ((nmethod*)Atomic::cmpxchg_ptr(last.method(), &_claimed_nmethod, first) != first);
5023   }
5024 
5025   nmethod* claim_postponed_nmethod() {
5026     nmethod* claim;
5027     nmethod* next;
5028 
5029     do {
5030       claim = (nmethod*)_postponed_list;
5031       if (claim == NULL) {
5032         return NULL;
5033       }
5034 
5035       next = claim->unloading_next();
5036 
5037     } while ((nmethod*)Atomic::cmpxchg_ptr(next, &_postponed_list, claim) != claim);
5038 
5039     return claim;
5040   }
5041 
5042  public:
5043   // Mark that we're done with the first pass of nmethod cleaning.
5044   void barrier_mark(uint worker_id) {
5045     MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
5046     _num_entered_barrier++;
5047     if (_num_entered_barrier == _num_workers) {
5048       ml.notify_all();
5049     }
5050   }
5051 
5052   // See if we have to wait for the other workers to
5053   // finish their first-pass nmethod cleaning work.
5054   void barrier_wait(uint worker_id) {
5055     if (_num_entered_barrier < _num_workers) {
5056       MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
5057       while (_num_entered_barrier < _num_workers) {
5058           ml.wait(Mutex::_no_safepoint_check_flag, 0, false);
5059       }
5060     }
5061   }
5062 
5063   // Cleaning and unloading of nmethods. Some work has to be postponed
5064   // to the second pass, when we know which nmethods survive.
5065   void work_first_pass(uint worker_id) {
5066     // The first nmethods is claimed by the first worker.
5067     if (worker_id == 0 && _first_nmethod != NULL) {
5068       clean_nmethod(_first_nmethod);
5069       _first_nmethod = NULL;
5070     }
5071 
5072     int num_claimed_nmethods;
5073     nmethod* claimed_nmethods[MaxClaimNmethods];
5074 
5075     while (true) {
5076       claim_nmethods(claimed_nmethods, &num_claimed_nmethods);
5077 
5078       if (num_claimed_nmethods == 0) {
5079         break;
5080       }
5081 
5082       for (int i = 0; i < num_claimed_nmethods; i++) {
5083         clean_nmethod(claimed_nmethods[i]);
5084       }
5085     }
5086   }
5087 
5088   void work_second_pass(uint worker_id) {
5089     nmethod* nm;
5090     // Take care of postponed nmethods.
5091     while ((nm = claim_postponed_nmethod()) != NULL) {
5092       clean_nmethod_postponed(nm);
5093     }
5094   }
5095 };
5096 
5097 Monitor* G1CodeCacheUnloadingTask::_lock = new Monitor(Mutex::leaf, "Code Cache Unload lock", false, Monitor::_safepoint_check_never);
5098 
5099 class G1KlassCleaningTask : public StackObj {
5100   BoolObjectClosure*                      _is_alive;
5101   volatile jint                           _clean_klass_tree_claimed;
5102   ClassLoaderDataGraphKlassIteratorAtomic _klass_iterator;
5103 
5104  public:
5105   G1KlassCleaningTask(BoolObjectClosure* is_alive) :
5106       _is_alive(is_alive),
5107       _clean_klass_tree_claimed(0),
5108       _klass_iterator() {
5109   }
5110 
5111  private:
5112   bool claim_clean_klass_tree_task() {
5113     if (_clean_klass_tree_claimed) {
5114       return false;
5115     }
5116 
5117     return Atomic::cmpxchg(1, (jint*)&_clean_klass_tree_claimed, 0) == 0;
5118   }
5119 
5120   InstanceKlass* claim_next_klass() {
5121     Klass* klass;
5122     do {
5123       klass =_klass_iterator.next_klass();
5124     } while (klass != NULL && !klass->oop_is_instance());
5125 
5126     return (InstanceKlass*)klass;
5127   }
5128 
5129 public:
5130 
5131   void clean_klass(InstanceKlass* ik) {
5132     ik->clean_implementors_list(_is_alive);
5133     ik->clean_method_data(_is_alive);
5134 
5135     // G1 specific cleanup work that has
5136     // been moved here to be done in parallel.
5137     ik->clean_dependent_nmethods();
5138   }
5139 
5140   void work() {
5141     ResourceMark rm;
5142 
5143     // One worker will clean the subklass/sibling klass tree.
5144     if (claim_clean_klass_tree_task()) {
5145       Klass::clean_subklass_tree(_is_alive);
5146     }
5147 
5148     // All workers will help cleaning the classes,
5149     InstanceKlass* klass;
5150     while ((klass = claim_next_klass()) != NULL) {
5151       clean_klass(klass);
5152     }
5153   }
5154 };
5155 
5156 // To minimize the remark pause times, the tasks below are done in parallel.
5157 class G1ParallelCleaningTask : public AbstractGangTask {
5158 private:
5159   G1StringSymbolTableUnlinkTask _string_symbol_task;
5160   G1CodeCacheUnloadingTask      _code_cache_task;
5161   G1KlassCleaningTask           _klass_cleaning_task;
5162 
5163 public:
5164   // The constructor is run in the VMThread.
5165   G1ParallelCleaningTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, uint num_workers, bool unloading_occurred) :
5166       AbstractGangTask("Parallel Cleaning"),
5167       _string_symbol_task(is_alive, process_strings, process_symbols),
5168       _code_cache_task(num_workers, is_alive, unloading_occurred),
5169       _klass_cleaning_task(is_alive) {
5170   }
5171 
5172   // The parallel work done by all worker threads.
5173   void work(uint worker_id) {
5174     // Do first pass of code cache cleaning.
5175     _code_cache_task.work_first_pass(worker_id);
5176 
5177     // Let the threads mark that the first pass is done.
5178     _code_cache_task.barrier_mark(worker_id);
5179 
5180     // Clean the Strings and Symbols.
5181     _string_symbol_task.work(worker_id);
5182 
5183     // Wait for all workers to finish the first code cache cleaning pass.
5184     _code_cache_task.barrier_wait(worker_id);
5185 
5186     // Do the second code cache cleaning work, which realize on
5187     // the liveness information gathered during the first pass.
5188     _code_cache_task.work_second_pass(worker_id);
5189 
5190     // Clean all klasses that were not unloaded.
5191     _klass_cleaning_task.work();
5192   }
5193 };
5194 
5195 
5196 void G1CollectedHeap::parallel_cleaning(BoolObjectClosure* is_alive,
5197                                         bool process_strings,
5198                                         bool process_symbols,
5199                                         bool class_unloading_occurred) {
5200   uint n_workers = workers()->active_workers();
5201 
5202   G1ParallelCleaningTask g1_unlink_task(is_alive, process_strings, process_symbols,
5203                                         n_workers, class_unloading_occurred);
5204   workers()->run_task(&g1_unlink_task);
5205 }
5206 
5207 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
5208                                                      bool process_strings, bool process_symbols) {
5209   {
5210     G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
5211     workers()->run_task(&g1_unlink_task);
5212   }
5213 
5214   if (G1StringDedup::is_enabled()) {
5215     G1StringDedup::unlink(is_alive);
5216   }
5217 }
5218 
5219 class G1RedirtyLoggedCardsTask : public AbstractGangTask {
5220  private:
5221   DirtyCardQueueSet* _queue;
5222  public:
5223   G1RedirtyLoggedCardsTask(DirtyCardQueueSet* queue) : AbstractGangTask("Redirty Cards"), _queue(queue) { }
5224 
5225   virtual void work(uint worker_id) {
5226     G1GCPhaseTimes* phase_times = G1CollectedHeap::heap()->g1_policy()->phase_times();
5227     G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::RedirtyCards, worker_id);
5228 
5229     RedirtyLoggedCardTableEntryClosure cl;
5230     _queue->par_apply_closure_to_all_completed_buffers(&cl);
5231 
5232     phase_times->record_thread_work_item(G1GCPhaseTimes::RedirtyCards, worker_id, cl.num_processed());
5233   }
5234 };
5235 
5236 void G1CollectedHeap::redirty_logged_cards() {
5237   double redirty_logged_cards_start = os::elapsedTime();
5238 
5239   G1RedirtyLoggedCardsTask redirty_task(&dirty_card_queue_set());
5240   dirty_card_queue_set().reset_for_par_iteration();
5241   workers()->run_task(&redirty_task);
5242 
5243   DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
5244   dcq.merge_bufferlists(&dirty_card_queue_set());
5245   assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
5246 
5247   g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0);
5248 }
5249 
5250 // Weak Reference Processing support
5251 
5252 // An always "is_alive" closure that is used to preserve referents.
5253 // If the object is non-null then it's alive.  Used in the preservation
5254 // of referent objects that are pointed to by reference objects
5255 // discovered by the CM ref processor.
5256 class G1AlwaysAliveClosure: public BoolObjectClosure {
5257   G1CollectedHeap* _g1;
5258 public:
5259   G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5260   bool do_object_b(oop p) {
5261     if (p != NULL) {
5262       return true;
5263     }
5264     return false;
5265   }
5266 };
5267 
5268 bool G1STWIsAliveClosure::do_object_b(oop p) {
5269   // An object is reachable if it is outside the collection set,
5270   // or is inside and copied.
5271   return !_g1->obj_in_cs(p) || p->is_forwarded();
5272 }
5273 
5274 // Non Copying Keep Alive closure
5275 class G1KeepAliveClosure: public OopClosure {
5276   G1CollectedHeap* _g1;
5277 public:
5278   G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5279   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
5280   void do_oop(oop* p) {
5281     oop obj = *p;
5282     assert(obj != NULL, "the caller should have filtered out NULL values");
5283 
5284     const InCSetState cset_state = _g1->in_cset_state(obj);
5285     if (!cset_state.is_in_cset_or_humongous()) {
5286       return;
5287     }
5288     if (cset_state.is_in_cset()) {
5289       assert( obj->is_forwarded(), "invariant" );
5290       *p = obj->forwardee();
5291     } else {
5292       assert(!obj->is_forwarded(), "invariant" );
5293       assert(cset_state.is_humongous(),
5294              err_msg("Only allowed InCSet state is IsHumongous, but is %d", cset_state.value()));
5295       _g1->set_humongous_is_live(obj);
5296     }
5297   }
5298 };
5299 
5300 // Copying Keep Alive closure - can be called from both
5301 // serial and parallel code as long as different worker
5302 // threads utilize different G1ParScanThreadState instances
5303 // and different queues.
5304 
5305 class G1CopyingKeepAliveClosure: public OopClosure {
5306   G1CollectedHeap*         _g1h;
5307   OopClosure*              _copy_non_heap_obj_cl;
5308   G1ParScanThreadState*    _par_scan_state;
5309 
5310 public:
5311   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
5312                             OopClosure* non_heap_obj_cl,
5313                             G1ParScanThreadState* pss):
5314     _g1h(g1h),
5315     _copy_non_heap_obj_cl(non_heap_obj_cl),
5316     _par_scan_state(pss)
5317   {}
5318 
5319   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
5320   virtual void do_oop(      oop* p) { do_oop_work(p); }
5321 
5322   template <class T> void do_oop_work(T* p) {
5323     oop obj = oopDesc::load_decode_heap_oop(p);
5324 
5325     if (_g1h->is_in_cset_or_humongous(obj)) {
5326       // If the referent object has been forwarded (either copied
5327       // to a new location or to itself in the event of an
5328       // evacuation failure) then we need to update the reference
5329       // field and, if both reference and referent are in the G1
5330       // heap, update the RSet for the referent.
5331       //
5332       // If the referent has not been forwarded then we have to keep
5333       // it alive by policy. Therefore we have copy the referent.
5334       //
5335       // If the reference field is in the G1 heap then we can push
5336       // on the PSS queue. When the queue is drained (after each
5337       // phase of reference processing) the object and it's followers
5338       // will be copied, the reference field set to point to the
5339       // new location, and the RSet updated. Otherwise we need to
5340       // use the the non-heap or metadata closures directly to copy
5341       // the referent object and update the pointer, while avoiding
5342       // updating the RSet.
5343 
5344       if (_g1h->is_in_g1_reserved(p)) {
5345         _par_scan_state->push_on_queue(p);
5346       } else {
5347         assert(!Metaspace::contains((const void*)p),
5348                err_msg("Unexpectedly found a pointer from metadata: " PTR_FORMAT, p2i(p)));
5349         _copy_non_heap_obj_cl->do_oop(p);
5350       }
5351     }
5352   }
5353 };
5354 
5355 // Serial drain queue closure. Called as the 'complete_gc'
5356 // closure for each discovered list in some of the
5357 // reference processing phases.
5358 
5359 class G1STWDrainQueueClosure: public VoidClosure {
5360 protected:
5361   G1CollectedHeap* _g1h;
5362   G1ParScanThreadState* _par_scan_state;
5363 
5364   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
5365 
5366 public:
5367   G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
5368     _g1h(g1h),
5369     _par_scan_state(pss)
5370   { }
5371 
5372   void do_void() {
5373     G1ParScanThreadState* const pss = par_scan_state();
5374     pss->trim_queue();
5375   }
5376 };
5377 
5378 // Parallel Reference Processing closures
5379 
5380 // Implementation of AbstractRefProcTaskExecutor for parallel reference
5381 // processing during G1 evacuation pauses.
5382 
5383 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
5384 private:
5385   G1CollectedHeap*   _g1h;
5386   RefToScanQueueSet* _queues;
5387   FlexibleWorkGang*  _workers;
5388   uint               _active_workers;
5389 
5390 public:
5391   G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
5392                            FlexibleWorkGang* workers,
5393                            RefToScanQueueSet *task_queues,
5394                            uint n_workers) :
5395     _g1h(g1h),
5396     _queues(task_queues),
5397     _workers(workers),
5398     _active_workers(n_workers)
5399   {
5400     assert(n_workers > 0, "shouldn't call this otherwise");
5401   }
5402 
5403   // Executes the given task using concurrent marking worker threads.
5404   virtual void execute(ProcessTask& task);
5405   virtual void execute(EnqueueTask& task);
5406 };
5407 
5408 // Gang task for possibly parallel reference processing
5409 
5410 class G1STWRefProcTaskProxy: public AbstractGangTask {
5411   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
5412   ProcessTask&     _proc_task;
5413   G1CollectedHeap* _g1h;
5414   RefToScanQueueSet *_task_queues;
5415   ParallelTaskTerminator* _terminator;
5416 
5417 public:
5418   G1STWRefProcTaskProxy(ProcessTask& proc_task,
5419                      G1CollectedHeap* g1h,
5420                      RefToScanQueueSet *task_queues,
5421                      ParallelTaskTerminator* terminator) :
5422     AbstractGangTask("Process reference objects in parallel"),
5423     _proc_task(proc_task),
5424     _g1h(g1h),
5425     _task_queues(task_queues),
5426     _terminator(terminator)
5427   {}
5428 
5429   virtual void work(uint worker_id) {
5430     // The reference processing task executed by a single worker.
5431     ResourceMark rm;
5432     HandleMark   hm;
5433 
5434     G1STWIsAliveClosure is_alive(_g1h);
5435 
5436     G1ParScanThreadState            pss(_g1h, worker_id, NULL);
5437 
5438     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
5439 
5440     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5441 
5442     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5443 
5444     if (_g1h->collector_state()->during_initial_mark_pause()) {
5445       // We also need to mark copied objects.
5446       copy_non_heap_cl = &copy_mark_non_heap_cl;
5447     }
5448 
5449     // Keep alive closure.
5450     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
5451 
5452     // Complete GC closure
5453     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);
5454 
5455     // Call the reference processing task's work routine.
5456     _proc_task.work(worker_id, is_alive, keep_alive, drain_queue);
5457 
5458     // Note we cannot assert that the refs array is empty here as not all
5459     // of the processing tasks (specifically phase2 - pp2_work) execute
5460     // the complete_gc closure (which ordinarily would drain the queue) so
5461     // the queue may not be empty.
5462   }
5463 };
5464 
5465 // Driver routine for parallel reference processing.
5466 // Creates an instance of the ref processing gang
5467 // task and has the worker threads execute it.
5468 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {
5469   assert(_workers != NULL, "Need parallel worker threads.");
5470 
5471   ParallelTaskTerminator terminator(_active_workers, _queues);
5472   G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator);
5473 
5474   _workers->run_task(&proc_task_proxy);
5475 }
5476 
5477 // Gang task for parallel reference enqueueing.
5478 
5479 class G1STWRefEnqueueTaskProxy: public AbstractGangTask {
5480   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
5481   EnqueueTask& _enq_task;
5482 
5483 public:
5484   G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) :
5485     AbstractGangTask("Enqueue reference objects in parallel"),
5486     _enq_task(enq_task)
5487   { }
5488 
5489   virtual void work(uint worker_id) {
5490     _enq_task.work(worker_id);
5491   }
5492 };
5493 
5494 // Driver routine for parallel reference enqueueing.
5495 // Creates an instance of the ref enqueueing gang
5496 // task and has the worker threads execute it.
5497 
5498 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
5499   assert(_workers != NULL, "Need parallel worker threads.");
5500 
5501   G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task);
5502 
5503   _workers->run_task(&enq_task_proxy);
5504 }
5505 
5506 // End of weak reference support closures
5507 
5508 // Abstract task used to preserve (i.e. copy) any referent objects
5509 // that are in the collection set and are pointed to by reference
5510 // objects discovered by the CM ref processor.
5511 
5512 class G1ParPreserveCMReferentsTask: public AbstractGangTask {
5513 protected:
5514   G1CollectedHeap* _g1h;
5515   RefToScanQueueSet      *_queues;
5516   ParallelTaskTerminator _terminator;
5517   uint _n_workers;
5518 
5519 public:
5520   G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h, uint workers, RefToScanQueueSet *task_queues) :
5521     AbstractGangTask("ParPreserveCMReferents"),
5522     _g1h(g1h),
5523     _queues(task_queues),
5524     _terminator(workers, _queues),
5525     _n_workers(workers)
5526   { }
5527 
5528   void work(uint worker_id) {
5529     ResourceMark rm;
5530     HandleMark   hm;
5531 
5532     G1ParScanThreadState            pss(_g1h, worker_id, NULL);
5533     assert(pss.queue_is_empty(), "both queue and overflow should be empty");
5534 
5535     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
5536 
5537     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5538 
5539     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5540 
5541     if (_g1h->collector_state()->during_initial_mark_pause()) {
5542       // We also need to mark copied objects.
5543       copy_non_heap_cl = &copy_mark_non_heap_cl;
5544     }
5545 
5546     // Is alive closure
5547     G1AlwaysAliveClosure always_alive(_g1h);
5548 
5549     // Copying keep alive closure. Applied to referent objects that need
5550     // to be copied.
5551     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
5552 
5553     ReferenceProcessor* rp = _g1h->ref_processor_cm();
5554 
5555     uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q();
5556     uint stride = MIN2(MAX2(_n_workers, 1U), limit);
5557 
5558     // limit is set using max_num_q() - which was set using ParallelGCThreads.
5559     // So this must be true - but assert just in case someone decides to
5560     // change the worker ids.
5561     assert(worker_id < limit, "sanity");
5562     assert(!rp->discovery_is_atomic(), "check this code");
5563 
5564     // Select discovered lists [i, i+stride, i+2*stride,...,limit)
5565     for (uint idx = worker_id; idx < limit; idx += stride) {
5566       DiscoveredList& ref_list = rp->discovered_refs()[idx];
5567 
5568       DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive);
5569       while (iter.has_next()) {
5570         // Since discovery is not atomic for the CM ref processor, we
5571         // can see some null referent objects.
5572         iter.load_ptrs(DEBUG_ONLY(true));
5573         oop ref = iter.obj();
5574 
5575         // This will filter nulls.
5576         if (iter.is_referent_alive()) {
5577           iter.make_referent_alive();
5578         }
5579         iter.move_to_next();
5580       }
5581     }
5582 
5583     // Drain the queue - which may cause stealing
5584     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);
5585     drain_queue.do_void();
5586     // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure
5587     assert(pss.queue_is_empty(), "should be");
5588   }
5589 };
5590 
5591 // Weak Reference processing during an evacuation pause (part 1).
5592 void G1CollectedHeap::process_discovered_references() {
5593   double ref_proc_start = os::elapsedTime();
5594 
5595   ReferenceProcessor* rp = _ref_processor_stw;
5596   assert(rp->discovery_enabled(), "should have been enabled");
5597 
5598   // Any reference objects, in the collection set, that were 'discovered'
5599   // by the CM ref processor should have already been copied (either by
5600   // applying the external root copy closure to the discovered lists, or
5601   // by following an RSet entry).
5602   //
5603   // But some of the referents, that are in the collection set, that these
5604   // reference objects point to may not have been copied: the STW ref
5605   // processor would have seen that the reference object had already
5606   // been 'discovered' and would have skipped discovering the reference,
5607   // but would not have treated the reference object as a regular oop.
5608   // As a result the copy closure would not have been applied to the
5609   // referent object.
5610   //
5611   // We need to explicitly copy these referent objects - the references
5612   // will be processed at the end of remarking.
5613   //
5614   // We also need to do this copying before we process the reference
5615   // objects discovered by the STW ref processor in case one of these
5616   // referents points to another object which is also referenced by an
5617   // object discovered by the STW ref processor.
5618 
5619   uint no_of_gc_workers = workers()->active_workers();
5620 
5621   G1ParPreserveCMReferentsTask keep_cm_referents(this,
5622                                                  no_of_gc_workers,
5623                                                  _task_queues);
5624 
5625   workers()->run_task(&keep_cm_referents);
5626 
5627   // Closure to test whether a referent is alive.
5628   G1STWIsAliveClosure is_alive(this);
5629 
5630   // Even when parallel reference processing is enabled, the processing
5631   // of JNI refs is serial and performed serially by the current thread
5632   // rather than by a worker. The following PSS will be used for processing
5633   // JNI refs.
5634 
5635   // Use only a single queue for this PSS.
5636   G1ParScanThreadState            pss(this, 0, NULL);
5637   assert(pss.queue_is_empty(), "pre-condition");
5638 
5639   // We do not embed a reference processor in the copying/scanning
5640   // closures while we're actually processing the discovered
5641   // reference objects.
5642 
5643   G1ParScanExtRootClosure        only_copy_non_heap_cl(this, &pss, NULL);
5644 
5645   G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);
5646 
5647   OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
5648 
5649   if (collector_state()->during_initial_mark_pause()) {
5650     // We also need to mark copied objects.
5651     copy_non_heap_cl = &copy_mark_non_heap_cl;
5652   }
5653 
5654   // Keep alive closure.
5655   G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, &pss);
5656 
5657   // Serial Complete GC closure
5658   G1STWDrainQueueClosure drain_queue(this, &pss);
5659 
5660   // Setup the soft refs policy...
5661   rp->setup_policy(false);
5662 
5663   ReferenceProcessorStats stats;
5664   if (!rp->processing_is_mt()) {
5665     // Serial reference processing...
5666     stats = rp->process_discovered_references(&is_alive,
5667                                               &keep_alive,
5668                                               &drain_queue,
5669                                               NULL,
5670                                               _gc_timer_stw,
5671                                               _gc_tracer_stw->gc_id());
5672   } else {
5673     // Parallel reference processing
5674     assert(rp->num_q() == no_of_gc_workers, "sanity");
5675     assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5676 
5677     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5678     stats = rp->process_discovered_references(&is_alive,
5679                                               &keep_alive,
5680                                               &drain_queue,
5681                                               &par_task_executor,
5682                                               _gc_timer_stw,
5683                                               _gc_tracer_stw->gc_id());
5684   }
5685 
5686   _gc_tracer_stw->report_gc_reference_stats(stats);
5687 
5688   // We have completed copying any necessary live referent objects.
5689   assert(pss.queue_is_empty(), "both queue and overflow should be empty");
5690 
5691   double ref_proc_time = os::elapsedTime() - ref_proc_start;
5692   g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
5693 }
5694 
5695 // Weak Reference processing during an evacuation pause (part 2).
5696 void G1CollectedHeap::enqueue_discovered_references() {
5697   double ref_enq_start = os::elapsedTime();
5698 
5699   ReferenceProcessor* rp = _ref_processor_stw;
5700   assert(!rp->discovery_enabled(), "should have been disabled as part of processing");
5701 
5702   // Now enqueue any remaining on the discovered lists on to
5703   // the pending list.
5704   if (!rp->processing_is_mt()) {
5705     // Serial reference processing...
5706     rp->enqueue_discovered_references();
5707   } else {
5708     // Parallel reference enqueueing
5709 
5710     uint n_workers = workers()->active_workers();
5711 
5712     assert(rp->num_q() == n_workers, "sanity");
5713     assert(n_workers <= rp->max_num_q(), "sanity");
5714 
5715     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, n_workers);
5716     rp->enqueue_discovered_references(&par_task_executor);
5717   }
5718 
5719   rp->verify_no_references_recorded();
5720   assert(!rp->discovery_enabled(), "should have been disabled");
5721 
5722   // FIXME
5723   // CM's reference processing also cleans up the string and symbol tables.
5724   // Should we do that here also? We could, but it is a serial operation
5725   // and could significantly increase the pause time.
5726 
5727   double ref_enq_time = os::elapsedTime() - ref_enq_start;
5728   g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0);
5729 }
5730 
5731 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {
5732   _expand_heap_after_alloc_failure = true;
5733   _evacuation_failed = false;
5734 
5735   // Should G1EvacuationFailureALot be in effect for this GC?
5736   NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
5737 
5738   g1_rem_set()->prepare_for_oops_into_collection_set_do();
5739 
5740   // Disable the hot card cache.
5741   G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
5742   hot_card_cache->reset_hot_cache_claimed_index();
5743   hot_card_cache->set_use_cache(false);
5744 
5745   const uint n_workers = workers()->active_workers();
5746 
5747   assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
5748   double start_par_time_sec = os::elapsedTime();
5749   double end_par_time_sec;
5750 
5751   {
5752     G1RootProcessor root_processor(this, n_workers);
5753     G1ParTask g1_par_task(this, _task_queues, &root_processor, n_workers);
5754     // InitialMark needs claim bits to keep track of the marked-through CLDs.
5755     if (collector_state()->during_initial_mark_pause()) {
5756       ClassLoaderDataGraph::clear_claimed_marks();
5757     }
5758 
5759     // The individual threads will set their evac-failure closures.
5760     if (PrintTerminationStats) G1ParScanThreadState::print_termination_stats_hdr();
5761 
5762     workers()->run_task(&g1_par_task);
5763     end_par_time_sec = os::elapsedTime();
5764 
5765     // Closing the inner scope will execute the destructor
5766     // for the G1RootProcessor object. We record the current
5767     // elapsed time before closing the scope so that time
5768     // taken for the destructor is NOT included in the
5769     // reported parallel time.
5770   }
5771 
5772   G1GCPhaseTimes* phase_times = g1_policy()->phase_times();
5773 
5774   double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0;
5775   phase_times->record_par_time(par_time_ms);
5776 
5777   double code_root_fixup_time_ms =
5778         (os::elapsedTime() - end_par_time_sec) * 1000.0;
5779   phase_times->record_code_root_fixup_time(code_root_fixup_time_ms);
5780 
5781   // Process any discovered reference objects - we have
5782   // to do this _before_ we retire the GC alloc regions
5783   // as we may have to copy some 'reachable' referent
5784   // objects (and their reachable sub-graphs) that were
5785   // not copied during the pause.
5786   process_discovered_references();
5787 
5788   if (G1StringDedup::is_enabled()) {
5789     double fixup_start = os::elapsedTime();
5790 
5791     G1STWIsAliveClosure is_alive(this);
5792     G1KeepAliveClosure keep_alive(this);
5793     G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive, true, phase_times);
5794 
5795     double fixup_time_ms = (os::elapsedTime() - fixup_start) * 1000.0;
5796     phase_times->record_string_dedup_fixup_time(fixup_time_ms);
5797   }
5798 
5799   _allocator->release_gc_alloc_regions(evacuation_info);
5800   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
5801 
5802   // Reset and re-enable the hot card cache.
5803   // Note the counts for the cards in the regions in the
5804   // collection set are reset when the collection set is freed.
5805   hot_card_cache->reset_hot_cache();
5806   hot_card_cache->set_use_cache(true);
5807 
5808   purge_code_root_memory();
5809 
5810   if (evacuation_failed()) {
5811     remove_self_forwarding_pointers();
5812 
5813     // Reset the G1EvacuationFailureALot counters and flags
5814     // Note: the values are reset only when an actual
5815     // evacuation failure occurs.
5816     NOT_PRODUCT(reset_evacuation_should_fail();)
5817   }
5818 
5819   // Enqueue any remaining references remaining on the STW
5820   // reference processor's discovered lists. We need to do
5821   // this after the card table is cleaned (and verified) as
5822   // the act of enqueueing entries on to the pending list
5823   // will log these updates (and dirty their associated
5824   // cards). We need these updates logged to update any
5825   // RSets.
5826   enqueue_discovered_references();
5827 
5828   redirty_logged_cards();
5829   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
5830 }
5831 
5832 void G1CollectedHeap::free_region(HeapRegion* hr,
5833                                   FreeRegionList* free_list,
5834                                   bool par,
5835                                   bool locked) {
5836   assert(!hr->is_free(), "the region should not be free");
5837   assert(!hr->is_empty(), "the region should not be empty");
5838   assert(_hrm.is_available(hr->hrm_index()), "region should be committed");
5839   assert(free_list != NULL, "pre-condition");
5840 
5841   if (G1VerifyBitmaps) {
5842     MemRegion mr(hr->bottom(), hr->end());
5843     concurrent_mark()->clearRangePrevBitmap(mr);
5844   }
5845 
5846   // Clear the card counts for this region.
5847   // Note: we only need to do this if the region is not young
5848   // (since we don't refine cards in young regions).
5849   if (!hr->is_young()) {
5850     _cg1r->hot_card_cache()->reset_card_counts(hr);
5851   }
5852   hr->hr_clear(par, true /* clear_space */, locked /* locked */);
5853   free_list->add_ordered(hr);
5854 }
5855 
5856 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
5857                                      FreeRegionList* free_list,
5858                                      bool par) {
5859   assert(hr->is_starts_humongous(), "this is only for starts humongous regions");
5860   assert(free_list != NULL, "pre-condition");
5861 
5862   size_t hr_capacity = hr->capacity();
5863   // We need to read this before we make the region non-humongous,
5864   // otherwise the information will be gone.
5865   uint last_index = hr->last_hc_index();
5866   hr->clear_humongous();
5867   free_region(hr, free_list, par);
5868 
5869   uint i = hr->hrm_index() + 1;
5870   while (i < last_index) {
5871     HeapRegion* curr_hr = region_at(i);
5872     assert(curr_hr->is_continues_humongous(), "invariant");
5873     curr_hr->clear_humongous();
5874     free_region(curr_hr, free_list, par);
5875     i += 1;
5876   }
5877 }
5878 
5879 void G1CollectedHeap::remove_from_old_sets(const HeapRegionSetCount& old_regions_removed,
5880                                        const HeapRegionSetCount& humongous_regions_removed) {
5881   if (old_regions_removed.length() > 0 || humongous_regions_removed.length() > 0) {
5882     MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
5883     _old_set.bulk_remove(old_regions_removed);
5884     _humongous_set.bulk_remove(humongous_regions_removed);
5885   }
5886 
5887 }
5888 
5889 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
5890   assert(list != NULL, "list can't be null");
5891   if (!list->is_empty()) {
5892     MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
5893     _hrm.insert_list_into_free_list(list);
5894   }
5895 }
5896 
5897 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
5898   decrease_used(bytes);
5899 }
5900 
5901 class G1ParCleanupCTTask : public AbstractGangTask {
5902   G1SATBCardTableModRefBS* _ct_bs;
5903   G1CollectedHeap* _g1h;
5904   HeapRegion* volatile _su_head;
5905 public:
5906   G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs,
5907                      G1CollectedHeap* g1h) :
5908     AbstractGangTask("G1 Par Cleanup CT Task"),
5909     _ct_bs(ct_bs), _g1h(g1h) { }
5910 
5911   void work(uint worker_id) {
5912     HeapRegion* r;
5913     while (r = _g1h->pop_dirty_cards_region()) {
5914       clear_cards(r);
5915     }
5916   }
5917 
5918   void clear_cards(HeapRegion* r) {
5919     // Cards of the survivors should have already been dirtied.
5920     if (!r->is_survivor()) {
5921       _ct_bs->clear(MemRegion(r->bottom(), r->end()));
5922     }
5923   }
5924 };
5925 
5926 #ifndef PRODUCT
5927 class G1VerifyCardTableCleanup: public HeapRegionClosure {
5928   G1CollectedHeap* _g1h;
5929   G1SATBCardTableModRefBS* _ct_bs;
5930 public:
5931   G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs)
5932     : _g1h(g1h), _ct_bs(ct_bs) { }
5933   virtual bool doHeapRegion(HeapRegion* r) {
5934     if (r->is_survivor()) {
5935       _g1h->verify_dirty_region(r);
5936     } else {
5937       _g1h->verify_not_dirty_region(r);
5938     }
5939     return false;
5940   }
5941 };
5942 
5943 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {
5944   // All of the region should be clean.
5945   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
5946   MemRegion mr(hr->bottom(), hr->end());
5947   ct_bs->verify_not_dirty_region(mr);
5948 }
5949 
5950 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {
5951   // We cannot guarantee that [bottom(),end()] is dirty.  Threads
5952   // dirty allocated blocks as they allocate them. The thread that
5953   // retires each region and replaces it with a new one will do a
5954   // maximal allocation to fill in [pre_dummy_top(),end()] but will
5955   // not dirty that area (one less thing to have to do while holding
5956   // a lock). So we can only verify that [bottom(),pre_dummy_top()]
5957   // is dirty.
5958   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
5959   MemRegion mr(hr->bottom(), hr->pre_dummy_top());
5960   if (hr->is_young()) {
5961     ct_bs->verify_g1_young_region(mr);
5962   } else {
5963     ct_bs->verify_dirty_region(mr);
5964   }
5965 }
5966 
5967 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {
5968   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
5969   for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {
5970     verify_dirty_region(hr);
5971   }
5972 }
5973 
5974 void G1CollectedHeap::verify_dirty_young_regions() {
5975   verify_dirty_young_list(_young_list->first_region());
5976 }
5977 
5978 bool G1CollectedHeap::verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap,
5979                                                HeapWord* tams, HeapWord* end) {
5980   guarantee(tams <= end,
5981             err_msg("tams: " PTR_FORMAT " end: " PTR_FORMAT, p2i(tams), p2i(end)));
5982   HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end);
5983   if (result < end) {
5984     gclog_or_tty->cr();
5985     gclog_or_tty->print_cr("## wrong marked address on %s bitmap: " PTR_FORMAT,
5986                            bitmap_name, p2i(result));
5987     gclog_or_tty->print_cr("## %s tams: " PTR_FORMAT " end: " PTR_FORMAT,
5988                            bitmap_name, p2i(tams), p2i(end));
5989     return false;
5990   }
5991   return true;
5992 }
5993 
5994 bool G1CollectedHeap::verify_bitmaps(const char* caller, HeapRegion* hr) {
5995   CMBitMapRO* prev_bitmap = concurrent_mark()->prevMarkBitMap();
5996   CMBitMapRO* next_bitmap = (CMBitMapRO*) concurrent_mark()->nextMarkBitMap();
5997 
5998   HeapWord* bottom = hr->bottom();
5999   HeapWord* ptams  = hr->prev_top_at_mark_start();
6000   HeapWord* ntams  = hr->next_top_at_mark_start();
6001   HeapWord* end    = hr->end();
6002 
6003   bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);
6004 
6005   bool res_n = true;
6006   // We reset mark_in_progress() before we reset _cmThread->in_progress() and in this window
6007   // we do the clearing of the next bitmap concurrently. Thus, we can not verify the bitmap
6008   // if we happen to be in that state.
6009   if (collector_state()->mark_in_progress() || !_cmThread->in_progress()) {
6010     res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
6011   }
6012   if (!res_p || !res_n) {
6013     gclog_or_tty->print_cr("#### Bitmap verification failed for " HR_FORMAT,
6014                            HR_FORMAT_PARAMS(hr));
6015     gclog_or_tty->print_cr("#### Caller: %s", caller);
6016     return false;
6017   }
6018   return true;
6019 }
6020 
6021 void G1CollectedHeap::check_bitmaps(const char* caller, HeapRegion* hr) {
6022   if (!G1VerifyBitmaps) return;
6023 
6024   guarantee(verify_bitmaps(caller, hr), "bitmap verification");
6025 }
6026 
6027 class G1VerifyBitmapClosure : public HeapRegionClosure {
6028 private:
6029   const char* _caller;
6030   G1CollectedHeap* _g1h;
6031   bool _failures;
6032 
6033 public:
6034   G1VerifyBitmapClosure(const char* caller, G1CollectedHeap* g1h) :
6035     _caller(caller), _g1h(g1h), _failures(false) { }
6036 
6037   bool failures() { return _failures; }
6038 
6039   virtual bool doHeapRegion(HeapRegion* hr) {
6040     if (hr->is_continues_humongous()) return false;
6041 
6042     bool result = _g1h->verify_bitmaps(_caller, hr);
6043     if (!result) {
6044       _failures = true;
6045     }
6046     return false;
6047   }
6048 };
6049 
6050 void G1CollectedHeap::check_bitmaps(const char* caller) {
6051   if (!G1VerifyBitmaps) return;
6052 
6053   G1VerifyBitmapClosure cl(caller, this);
6054   heap_region_iterate(&cl);
6055   guarantee(!cl.failures(), "bitmap verification");
6056 }
6057 
6058 class G1CheckCSetFastTableClosure : public HeapRegionClosure {
6059  private:
6060   bool _failures;
6061  public:
6062   G1CheckCSetFastTableClosure() : HeapRegionClosure(), _failures(false) { }
6063 
6064   virtual bool doHeapRegion(HeapRegion* hr) {
6065     uint i = hr->hrm_index();
6066     InCSetState cset_state = (InCSetState) G1CollectedHeap::heap()->_in_cset_fast_test.get_by_index(i);
6067     if (hr->is_humongous()) {
6068       if (hr->in_collection_set()) {
6069         gclog_or_tty->print_cr("\n## humongous region %u in CSet", i);
6070         _failures = true;
6071         return true;
6072       }
6073       if (cset_state.is_in_cset()) {
6074         gclog_or_tty->print_cr("\n## inconsistent cset state %d for humongous region %u", cset_state.value(), i);
6075         _failures = true;
6076         return true;
6077       }
6078       if (hr->is_continues_humongous() && cset_state.is_humongous()) {
6079         gclog_or_tty->print_cr("\n## inconsistent cset state %d for continues humongous region %u", cset_state.value(), i);
6080         _failures = true;
6081         return true;
6082       }
6083     } else {
6084       if (cset_state.is_humongous()) {
6085         gclog_or_tty->print_cr("\n## inconsistent cset state %d for non-humongous region %u", cset_state.value(), i);
6086         _failures = true;
6087         return true;
6088       }
6089       if (hr->in_collection_set() != cset_state.is_in_cset()) {
6090         gclog_or_tty->print_cr("\n## in CSet %d / cset state %d inconsistency for region %u",
6091                                hr->in_collection_set(), cset_state.value(), i);
6092         _failures = true;
6093         return true;
6094       }
6095       if (cset_state.is_in_cset()) {
6096         if (hr->is_young() != (cset_state.is_young())) {
6097           gclog_or_tty->print_cr("\n## is_young %d / cset state %d inconsistency for region %u",
6098                                  hr->is_young(), cset_state.value(), i);
6099           _failures = true;
6100           return true;
6101         }
6102         if (hr->is_old() != (cset_state.is_old())) {
6103           gclog_or_tty->print_cr("\n## is_old %d / cset state %d inconsistency for region %u",
6104                                  hr->is_old(), cset_state.value(), i);
6105           _failures = true;
6106           return true;
6107         }
6108       }
6109     }
6110     return false;
6111   }
6112 
6113   bool failures() const { return _failures; }
6114 };
6115 
6116 bool G1CollectedHeap::check_cset_fast_test() {
6117   G1CheckCSetFastTableClosure cl;
6118   _hrm.iterate(&cl);
6119   return !cl.failures();
6120 }
6121 #endif // PRODUCT
6122 
6123 void G1CollectedHeap::cleanUpCardTable() {
6124   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6125   double start = os::elapsedTime();
6126 
6127   {
6128     // Iterate over the dirty cards region list.
6129     G1ParCleanupCTTask cleanup_task(ct_bs, this);
6130 
6131     workers()->run_task(&cleanup_task);
6132 #ifndef PRODUCT
6133     if (G1VerifyCTCleanup || VerifyAfterGC) {
6134       G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
6135       heap_region_iterate(&cleanup_verifier);
6136     }
6137 #endif
6138   }
6139 
6140   double elapsed = os::elapsedTime() - start;
6141   g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0);
6142 }
6143 
6144 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) {
6145   size_t pre_used = 0;
6146   FreeRegionList local_free_list("Local List for CSet Freeing");
6147 
6148   double young_time_ms     = 0.0;
6149   double non_young_time_ms = 0.0;
6150 
6151   // Since the collection set is a superset of the the young list,
6152   // all we need to do to clear the young list is clear its
6153   // head and length, and unlink any young regions in the code below
6154   _young_list->clear();
6155 
6156   G1CollectorPolicy* policy = g1_policy();
6157 
6158   double start_sec = os::elapsedTime();
6159   bool non_young = true;
6160 
6161   HeapRegion* cur = cs_head;
6162   int age_bound = -1;
6163   size_t rs_lengths = 0;
6164 
6165   while (cur != NULL) {
6166     assert(!is_on_master_free_list(cur), "sanity");
6167     if (non_young) {
6168       if (cur->is_young()) {
6169         double end_sec = os::elapsedTime();
6170         double elapsed_ms = (end_sec - start_sec) * 1000.0;
6171         non_young_time_ms += elapsed_ms;
6172 
6173         start_sec = os::elapsedTime();
6174         non_young = false;
6175       }
6176     } else {
6177       if (!cur->is_young()) {
6178         double end_sec = os::elapsedTime();
6179         double elapsed_ms = (end_sec - start_sec) * 1000.0;
6180         young_time_ms += elapsed_ms;
6181 
6182         start_sec = os::elapsedTime();
6183         non_young = true;
6184       }
6185     }
6186 
6187     rs_lengths += cur->rem_set()->occupied_locked();
6188 
6189     HeapRegion* next = cur->next_in_collection_set();
6190     assert(cur->in_collection_set(), "bad CS");
6191     cur->set_next_in_collection_set(NULL);
6192     clear_in_cset(cur);
6193 
6194     if (cur->is_young()) {
6195       int index = cur->young_index_in_cset();
6196       assert(index != -1, "invariant");
6197       assert((uint) index < policy->young_cset_region_length(), "invariant");
6198       size_t words_survived = _surviving_young_words[index];
6199       cur->record_surv_words_in_group(words_survived);
6200 
6201       // At this point the we have 'popped' cur from the collection set
6202       // (linked via next_in_collection_set()) but it is still in the
6203       // young list (linked via next_young_region()). Clear the
6204       // _next_young_region field.
6205       cur->set_next_young_region(NULL);
6206     } else {
6207       int index = cur->young_index_in_cset();
6208       assert(index == -1, "invariant");
6209     }
6210 
6211     assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
6212             (!cur->is_young() && cur->young_index_in_cset() == -1),
6213             "invariant" );
6214 
6215     if (!cur->evacuation_failed()) {
6216       MemRegion used_mr = cur->used_region();
6217 
6218       // And the region is empty.
6219       assert(!used_mr.is_empty(), "Should not have empty regions in a CS.");
6220       pre_used += cur->used();
6221       free_region(cur, &local_free_list, false /* par */, true /* locked */);
6222     } else {
6223       cur->uninstall_surv_rate_group();
6224       if (cur->is_young()) {
6225         cur->set_young_index_in_cset(-1);
6226       }
6227       cur->set_evacuation_failed(false);
6228       // The region is now considered to be old.
6229       cur->set_old();
6230       _old_set.add(cur);
6231       evacuation_info.increment_collectionset_used_after(cur->used());
6232     }
6233     cur = next;
6234   }
6235 
6236   evacuation_info.set_regions_freed(local_free_list.length());
6237   policy->record_max_rs_lengths(rs_lengths);
6238   policy->cset_regions_freed();
6239 
6240   double end_sec = os::elapsedTime();
6241   double elapsed_ms = (end_sec - start_sec) * 1000.0;
6242 
6243   if (non_young) {
6244     non_young_time_ms += elapsed_ms;
6245   } else {
6246     young_time_ms += elapsed_ms;
6247   }
6248 
6249   prepend_to_freelist(&local_free_list);
6250   decrement_summary_bytes(pre_used);
6251   policy->phase_times()->record_young_free_cset_time_ms(young_time_ms);
6252   policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms);
6253 }
6254 
6255 class G1FreeHumongousRegionClosure : public HeapRegionClosure {
6256  private:
6257   FreeRegionList* _free_region_list;
6258   HeapRegionSet* _proxy_set;
6259   HeapRegionSetCount _humongous_regions_removed;
6260   size_t _freed_bytes;
6261  public:
6262 
6263   G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) :
6264     _free_region_list(free_region_list), _humongous_regions_removed(), _freed_bytes(0) {
6265   }
6266 
6267   virtual bool doHeapRegion(HeapRegion* r) {
6268     if (!r->is_starts_humongous()) {
6269       return false;
6270     }
6271 
6272     G1CollectedHeap* g1h = G1CollectedHeap::heap();
6273 
6274     oop obj = (oop)r->bottom();
6275     CMBitMap* next_bitmap = g1h->concurrent_mark()->nextMarkBitMap();
6276 
6277     // The following checks whether the humongous object is live are sufficient.
6278     // The main additional check (in addition to having a reference from the roots
6279     // or the young gen) is whether the humongous object has a remembered set entry.
6280     //
6281     // A humongous object cannot be live if there is no remembered set for it
6282     // because:
6283     // - there can be no references from within humongous starts regions referencing
6284     // the object because we never allocate other objects into them.
6285     // (I.e. there are no intra-region references that may be missed by the
6286     // remembered set)
6287     // - as soon there is a remembered set entry to the humongous starts region
6288     // (i.e. it has "escaped" to an old object) this remembered set entry will stay
6289     // until the end of a concurrent mark.
6290     //
6291     // It is not required to check whether the object has been found dead by marking
6292     // or not, in fact it would prevent reclamation within a concurrent cycle, as
6293     // all objects allocated during that time are considered live.
6294     // SATB marking is even more conservative than the remembered set.
6295     // So if at this point in the collection there is no remembered set entry,
6296     // nobody has a reference to it.
6297     // At the start of collection we flush all refinement logs, and remembered sets
6298     // are completely up-to-date wrt to references to the humongous object.
6299     //
6300     // Other implementation considerations:
6301     // - never consider object arrays at this time because they would pose
6302     // considerable effort for cleaning up the the remembered sets. This is
6303     // required because stale remembered sets might reference locations that
6304     // are currently allocated into.
6305     uint region_idx = r->hrm_index();
6306     if (!g1h->is_humongous_reclaim_candidate(region_idx) ||
6307         !r->rem_set()->is_empty()) {
6308 
6309       if (G1TraceEagerReclaimHumongousObjects) {
6310         gclog_or_tty->print_cr("Live humongous region %u size " SIZE_FORMAT " start " PTR_FORMAT " length %u with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",
6311                                region_idx,
6312                                (size_t)obj->size() * HeapWordSize,
6313                                p2i(r->bottom()),
6314                                r->region_num(),
6315                                r->rem_set()->occupied(),
6316                                r->rem_set()->strong_code_roots_list_length(),
6317                                next_bitmap->isMarked(r->bottom()),
6318                                g1h->is_humongous_reclaim_candidate(region_idx),
6319                                obj->is_typeArray()
6320                               );
6321       }
6322 
6323       return false;
6324     }
6325 
6326     guarantee(obj->is_typeArray(),
6327               err_msg("Only eagerly reclaiming type arrays is supported, but the object "
6328                       PTR_FORMAT " is not.",
6329                       p2i(r->bottom())));
6330 
6331     if (G1TraceEagerReclaimHumongousObjects) {
6332       gclog_or_tty->print_cr("Dead humongous region %u size " SIZE_FORMAT " start " PTR_FORMAT " length %u with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",
6333                              region_idx,
6334                              (size_t)obj->size() * HeapWordSize,
6335                              p2i(r->bottom()),
6336                              r->region_num(),
6337                              r->rem_set()->occupied(),
6338                              r->rem_set()->strong_code_roots_list_length(),
6339                              next_bitmap->isMarked(r->bottom()),
6340                              g1h->is_humongous_reclaim_candidate(region_idx),
6341                              obj->is_typeArray()
6342                             );
6343     }
6344     // Need to clear mark bit of the humongous object if already set.
6345     if (next_bitmap->isMarked(r->bottom())) {
6346       next_bitmap->clear(r->bottom());
6347     }
6348     _freed_bytes += r->used();
6349     r->set_containing_set(NULL);
6350     _humongous_regions_removed.increment(1u, r->capacity());
6351     g1h->free_humongous_region(r, _free_region_list, false);
6352 
6353     return false;
6354   }
6355 
6356   HeapRegionSetCount& humongous_free_count() {
6357     return _humongous_regions_removed;
6358   }
6359 
6360   size_t bytes_freed() const {
6361     return _freed_bytes;
6362   }
6363 
6364   size_t humongous_reclaimed() const {
6365     return _humongous_regions_removed.length();
6366   }
6367 };
6368 
6369 void G1CollectedHeap::eagerly_reclaim_humongous_regions() {
6370   assert_at_safepoint(true);
6371 
6372   if (!G1EagerReclaimHumongousObjects ||
6373       (!_has_humongous_reclaim_candidates && !G1TraceEagerReclaimHumongousObjects)) {
6374     g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0);
6375     return;
6376   }
6377 
6378   double start_time = os::elapsedTime();
6379 
6380   FreeRegionList local_cleanup_list("Local Humongous Cleanup List");
6381 
6382   G1FreeHumongousRegionClosure cl(&local_cleanup_list);
6383   heap_region_iterate(&cl);
6384 
6385   HeapRegionSetCount empty_set;
6386   remove_from_old_sets(empty_set, cl.humongous_free_count());
6387 
6388   G1HRPrinter* hrp = hr_printer();
6389   if (hrp->is_active()) {
6390     FreeRegionListIterator iter(&local_cleanup_list);
6391     while (iter.more_available()) {
6392       HeapRegion* hr = iter.get_next();
6393       hrp->cleanup(hr);
6394     }
6395   }
6396 
6397   prepend_to_freelist(&local_cleanup_list);
6398   decrement_summary_bytes(cl.bytes_freed());
6399 
6400   g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0,
6401                                                                     cl.humongous_reclaimed());
6402 }
6403 
6404 // This routine is similar to the above but does not record
6405 // any policy statistics or update free lists; we are abandoning
6406 // the current incremental collection set in preparation of a
6407 // full collection. After the full GC we will start to build up
6408 // the incremental collection set again.
6409 // This is only called when we're doing a full collection
6410 // and is immediately followed by the tearing down of the young list.
6411 
6412 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
6413   HeapRegion* cur = cs_head;
6414 
6415   while (cur != NULL) {
6416     HeapRegion* next = cur->next_in_collection_set();
6417     assert(cur->in_collection_set(), "bad CS");
6418     cur->set_next_in_collection_set(NULL);
6419     clear_in_cset(cur);
6420     cur->set_young_index_in_cset(-1);
6421     cur = next;
6422   }
6423 }
6424 
6425 void G1CollectedHeap::set_free_regions_coming() {
6426   if (G1ConcRegionFreeingVerbose) {
6427     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6428                            "setting free regions coming");
6429   }
6430 
6431   assert(!free_regions_coming(), "pre-condition");
6432   _free_regions_coming = true;
6433 }
6434 
6435 void G1CollectedHeap::reset_free_regions_coming() {
6436   assert(free_regions_coming(), "pre-condition");
6437 
6438   {
6439     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6440     _free_regions_coming = false;
6441     SecondaryFreeList_lock->notify_all();
6442   }
6443 
6444   if (G1ConcRegionFreeingVerbose) {
6445     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6446                            "reset free regions coming");
6447   }
6448 }
6449 
6450 void G1CollectedHeap::wait_while_free_regions_coming() {
6451   // Most of the time we won't have to wait, so let's do a quick test
6452   // first before we take the lock.
6453   if (!free_regions_coming()) {
6454     return;
6455   }
6456 
6457   if (G1ConcRegionFreeingVerbose) {
6458     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6459                            "waiting for free regions");
6460   }
6461 
6462   {
6463     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6464     while (free_regions_coming()) {
6465       SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
6466     }
6467   }
6468 
6469   if (G1ConcRegionFreeingVerbose) {
6470     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6471                            "done waiting for free regions");
6472   }
6473 }
6474 
6475 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
6476   _young_list->push_region(hr);
6477 }
6478 
6479 class NoYoungRegionsClosure: public HeapRegionClosure {
6480 private:
6481   bool _success;
6482 public:
6483   NoYoungRegionsClosure() : _success(true) { }
6484   bool doHeapRegion(HeapRegion* r) {
6485     if (r->is_young()) {
6486       gclog_or_tty->print_cr("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
6487                              p2i(r->bottom()), p2i(r->end()));
6488       _success = false;
6489     }
6490     return false;
6491   }
6492   bool success() { return _success; }
6493 };
6494 
6495 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
6496   bool ret = _young_list->check_list_empty(check_sample);
6497 
6498   if (check_heap) {
6499     NoYoungRegionsClosure closure;
6500     heap_region_iterate(&closure);
6501     ret = ret && closure.success();
6502   }
6503 
6504   return ret;
6505 }
6506 
6507 class TearDownRegionSetsClosure : public HeapRegionClosure {
6508 private:
6509   HeapRegionSet *_old_set;
6510 
6511 public:
6512   TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }
6513 
6514   bool doHeapRegion(HeapRegion* r) {
6515     if (r->is_old()) {
6516       _old_set->remove(r);
6517     } else {
6518       // We ignore free regions, we'll empty the free list afterwards.
6519       // We ignore young regions, we'll empty the young list afterwards.
6520       // We ignore humongous regions, we're not tearing down the
6521       // humongous regions set.
6522       assert(r->is_free() || r->is_young() || r->is_humongous(),
6523              "it cannot be another type");
6524     }
6525     return false;
6526   }
6527 
6528   ~TearDownRegionSetsClosure() {
6529     assert(_old_set->is_empty(), "post-condition");
6530   }
6531 };
6532 
6533 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {
6534   assert_at_safepoint(true /* should_be_vm_thread */);
6535 
6536   if (!free_list_only) {
6537     TearDownRegionSetsClosure cl(&_old_set);
6538     heap_region_iterate(&cl);
6539 
6540     // Note that emptying the _young_list is postponed and instead done as
6541     // the first step when rebuilding the regions sets again. The reason for
6542     // this is that during a full GC string deduplication needs to know if
6543     // a collected region was young or old when the full GC was initiated.
6544   }
6545   _hrm.remove_all_free_regions();
6546 }
6547 
6548 void G1CollectedHeap::increase_used(size_t bytes) {
6549   _summary_bytes_used += bytes;
6550 }
6551 
6552 void G1CollectedHeap::decrease_used(size_t bytes) {
6553   assert(_summary_bytes_used >= bytes,
6554          err_msg("invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,
6555                  _summary_bytes_used, bytes));
6556   _summary_bytes_used -= bytes;
6557 }
6558 
6559 void G1CollectedHeap::set_used(size_t bytes) {
6560   _summary_bytes_used = bytes;
6561 }
6562 
6563 class RebuildRegionSetsClosure : public HeapRegionClosure {
6564 private:
6565   bool            _free_list_only;
6566   HeapRegionSet*   _old_set;
6567   HeapRegionManager*   _hrm;
6568   size_t          _total_used;
6569 
6570 public:
6571   RebuildRegionSetsClosure(bool free_list_only,
6572                            HeapRegionSet* old_set, HeapRegionManager* hrm) :
6573     _free_list_only(free_list_only),
6574     _old_set(old_set), _hrm(hrm), _total_used(0) {
6575     assert(_hrm->num_free_regions() == 0, "pre-condition");
6576     if (!free_list_only) {
6577       assert(_old_set->is_empty(), "pre-condition");
6578     }
6579   }
6580 
6581   bool doHeapRegion(HeapRegion* r) {
6582     if (r->is_continues_humongous()) {
6583       return false;
6584     }
6585 
6586     if (r->is_empty()) {
6587       // Add free regions to the free list
6588       r->set_free();
6589       r->set_allocation_context(AllocationContext::system());
6590       _hrm->insert_into_free_list(r);
6591     } else if (!_free_list_only) {
6592       assert(!r->is_young(), "we should not come across young regions");
6593 
6594       if (r->is_humongous()) {
6595         // We ignore humongous regions. We left the humongous set unchanged.
6596       } else {
6597         // Objects that were compacted would have ended up on regions
6598         // that were previously old or free.  Archive regions (which are
6599         // old) will not have been touched.
6600         assert(r->is_free() || r->is_old(), "invariant");
6601         // We now consider them old, so register as such. Leave
6602         // archive regions set that way, however, while still adding
6603         // them to the old set.
6604         if (!r->is_archive()) {
6605           r->set_old();
6606         }
6607         _old_set->add(r);
6608       }
6609       _total_used += r->used();
6610     }
6611 
6612     return false;
6613   }
6614 
6615   size_t total_used() {
6616     return _total_used;
6617   }
6618 };
6619 
6620 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
6621   assert_at_safepoint(true /* should_be_vm_thread */);
6622 
6623   if (!free_list_only) {
6624     _young_list->empty_list();
6625   }
6626 
6627   RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_hrm);
6628   heap_region_iterate(&cl);
6629 
6630   if (!free_list_only) {
6631     set_used(cl.total_used());
6632     if (_archive_allocator != NULL) {
6633       _archive_allocator->clear_used();
6634     }
6635   }
6636   assert(used_unlocked() == recalculate_used(),
6637          err_msg("inconsistent used_unlocked(), "
6638                  "value: " SIZE_FORMAT " recalculated: " SIZE_FORMAT,
6639                  used_unlocked(), recalculate_used()));
6640 }
6641 
6642 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
6643   _refine_cte_cl_concurrency = concurrent;
6644 }
6645 
6646 bool G1CollectedHeap::refine_cte_cl_concurrency() {
6647   return _refine_cte_cl_concurrency;
6648 }
6649 
6650 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
6651   HeapRegion* hr = heap_region_containing(p);
6652   return hr->is_in(p);
6653 }
6654 
6655 // Methods for the mutator alloc region
6656 
6657 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
6658                                                       bool force) {
6659   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6660   assert(!force || g1_policy()->can_expand_young_list(),
6661          "if force is true we should be able to expand the young list");
6662   bool young_list_full = g1_policy()->is_young_list_full();
6663   if (force || !young_list_full) {
6664     HeapRegion* new_alloc_region = new_region(word_size,
6665                                               false /* is_old */,
6666                                               false /* do_expand */);
6667     if (new_alloc_region != NULL) {
6668       set_region_short_lived_locked(new_alloc_region);
6669       _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
6670       check_bitmaps("Mutator Region Allocation", new_alloc_region);
6671       return new_alloc_region;
6672     }
6673   }
6674   return NULL;
6675 }
6676 
6677 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
6678                                                   size_t allocated_bytes) {
6679   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6680   assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
6681 
6682   g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
6683   increase_used(allocated_bytes);
6684   _hr_printer.retire(alloc_region);
6685   // We update the eden sizes here, when the region is retired,
6686   // instead of when it's allocated, since this is the point that its
6687   // used space has been recored in _summary_bytes_used.
6688   g1mm()->update_eden_size();
6689 }
6690 
6691 // Methods for the GC alloc regions
6692 
6693 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,
6694                                                  uint count,
6695                                                  InCSetState dest) {
6696   assert(FreeList_lock->owned_by_self(), "pre-condition");
6697 
6698   if (count < g1_policy()->max_regions(dest)) {
6699     const bool is_survivor = (dest.is_young());
6700     HeapRegion* new_alloc_region = new_region(word_size,
6701                                               !is_survivor,
6702                                               true /* do_expand */);
6703     if (new_alloc_region != NULL) {
6704       // We really only need to do this for old regions given that we
6705       // should never scan survivors. But it doesn't hurt to do it
6706       // for survivors too.
6707       new_alloc_region->record_timestamp();
6708       if (is_survivor) {
6709         new_alloc_region->set_survivor();
6710         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
6711         check_bitmaps("Survivor Region Allocation", new_alloc_region);
6712       } else {
6713         new_alloc_region->set_old();
6714         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
6715         check_bitmaps("Old Region Allocation", new_alloc_region);
6716       }
6717       bool during_im = collector_state()->during_initial_mark_pause();
6718       new_alloc_region->note_start_of_copying(during_im);
6719       return new_alloc_region;
6720     }
6721   }
6722   return NULL;
6723 }
6724 
6725 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
6726                                              size_t allocated_bytes,
6727                                              InCSetState dest) {
6728   bool during_im = collector_state()->during_initial_mark_pause();
6729   alloc_region->note_end_of_copying(during_im);
6730   g1_policy()->record_bytes_copied_during_gc(allocated_bytes);
6731   if (dest.is_young()) {
6732     young_list()->add_survivor_region(alloc_region);
6733   } else {
6734     _old_set.add(alloc_region);
6735   }
6736   _hr_printer.retire(alloc_region);
6737 }
6738 
6739 HeapRegion* G1CollectedHeap::alloc_highest_free_region() {
6740   bool expanded = false;
6741   uint index = _hrm.find_highest_free(&expanded);
6742 
6743   if (index != G1_NO_HRM_INDEX) {
6744     if (expanded) {
6745       ergo_verbose1(ErgoHeapSizing,
6746                     "attempt heap expansion",
6747                     ergo_format_reason("requested address range outside heap bounds")
6748                     ergo_format_byte("region size"),
6749                     HeapRegion::GrainWords * HeapWordSize);
6750     }
6751     _hrm.allocate_free_regions_starting_at(index, 1);
6752     return region_at(index);
6753   }
6754   return NULL;
6755 }
6756 
6757 
6758 // Heap region set verification
6759 
6760 class VerifyRegionListsClosure : public HeapRegionClosure {
6761 private:
6762   HeapRegionSet*   _old_set;
6763   HeapRegionSet*   _humongous_set;
6764   HeapRegionManager*   _hrm;
6765 
6766 public:
6767   HeapRegionSetCount _old_count;
6768   HeapRegionSetCount _humongous_count;
6769   HeapRegionSetCount _free_count;
6770 
6771   VerifyRegionListsClosure(HeapRegionSet* old_set,
6772                            HeapRegionSet* humongous_set,
6773                            HeapRegionManager* hrm) :
6774     _old_set(old_set), _humongous_set(humongous_set), _hrm(hrm),
6775     _old_count(), _humongous_count(), _free_count(){ }
6776 
6777   bool doHeapRegion(HeapRegion* hr) {
6778     if (hr->is_continues_humongous()) {
6779       return false;
6780     }
6781 
6782     if (hr->is_young()) {
6783       // TODO
6784     } else if (hr->is_starts_humongous()) {
6785       assert(hr->containing_set() == _humongous_set, err_msg("Heap region %u is starts humongous but not in humongous set.", hr->hrm_index()));
6786       _humongous_count.increment(1u, hr->capacity());
6787     } else if (hr->is_empty()) {
6788       assert(_hrm->is_free(hr), err_msg("Heap region %u is empty but not on the free list.", hr->hrm_index()));
6789       _free_count.increment(1u, hr->capacity());
6790     } else if (hr->is_old()) {
6791       assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->hrm_index()));
6792       _old_count.increment(1u, hr->capacity());
6793     } else {
6794       // There are no other valid region types. Check for one invalid
6795       // one we can identify: pinned without old or humongous set.
6796       assert(!hr->is_pinned(), err_msg("Heap region %u is pinned but not old (archive) or humongous.", hr->hrm_index()));
6797       ShouldNotReachHere();
6798     }
6799     return false;
6800   }
6801 
6802   void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, HeapRegionManager* free_list) {
6803     guarantee(old_set->length() == _old_count.length(), err_msg("Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count.length()));
6804     guarantee(old_set->total_capacity_bytes() == _old_count.capacity(), err_msg("Old set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6805         old_set->total_capacity_bytes(), _old_count.capacity()));
6806 
6807     guarantee(humongous_set->length() == _humongous_count.length(), err_msg("Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count.length()));
6808     guarantee(humongous_set->total_capacity_bytes() == _humongous_count.capacity(), err_msg("Hum set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6809         humongous_set->total_capacity_bytes(), _humongous_count.capacity()));
6810 
6811     guarantee(free_list->num_free_regions() == _free_count.length(), err_msg("Free list count mismatch. Expected %u, actual %u.", free_list->num_free_regions(), _free_count.length()));
6812     guarantee(free_list->total_capacity_bytes() == _free_count.capacity(), err_msg("Free list capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6813         free_list->total_capacity_bytes(), _free_count.capacity()));
6814   }
6815 };
6816 
6817 void G1CollectedHeap::verify_region_sets() {
6818   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6819 
6820   // First, check the explicit lists.
6821   _hrm.verify();
6822   {
6823     // Given that a concurrent operation might be adding regions to
6824     // the secondary free list we have to take the lock before
6825     // verifying it.
6826     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6827     _secondary_free_list.verify_list();
6828   }
6829 
6830   // If a concurrent region freeing operation is in progress it will
6831   // be difficult to correctly attributed any free regions we come
6832   // across to the correct free list given that they might belong to
6833   // one of several (free_list, secondary_free_list, any local lists,
6834   // etc.). So, if that's the case we will skip the rest of the
6835   // verification operation. Alternatively, waiting for the concurrent
6836   // operation to complete will have a non-trivial effect on the GC's
6837   // operation (no concurrent operation will last longer than the
6838   // interval between two calls to verification) and it might hide
6839   // any issues that we would like to catch during testing.
6840   if (free_regions_coming()) {
6841     return;
6842   }
6843 
6844   // Make sure we append the secondary_free_list on the free_list so
6845   // that all free regions we will come across can be safely
6846   // attributed to the free_list.
6847   append_secondary_free_list_if_not_empty_with_lock();
6848 
6849   // Finally, make sure that the region accounting in the lists is
6850   // consistent with what we see in the heap.
6851 
6852   VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_hrm);
6853   heap_region_iterate(&cl);
6854   cl.verify_counts(&_old_set, &_humongous_set, &_hrm);
6855 }
6856 
6857 // Optimized nmethod scanning
6858 
6859 class RegisterNMethodOopClosure: public OopClosure {
6860   G1CollectedHeap* _g1h;
6861   nmethod* _nm;
6862 
6863   template <class T> void do_oop_work(T* p) {
6864     T heap_oop = oopDesc::load_heap_oop(p);
6865     if (!oopDesc::is_null(heap_oop)) {
6866       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6867       HeapRegion* hr = _g1h->heap_region_containing(obj);
6868       assert(!hr->is_continues_humongous(),
6869              err_msg("trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
6870                      " starting at " HR_FORMAT,
6871                      p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
6872 
6873       // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.
6874       hr->add_strong_code_root_locked(_nm);
6875     }
6876   }
6877 
6878 public:
6879   RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
6880     _g1h(g1h), _nm(nm) {}
6881 
6882   void do_oop(oop* p)       { do_oop_work(p); }
6883   void do_oop(narrowOop* p) { do_oop_work(p); }
6884 };
6885 
6886 class UnregisterNMethodOopClosure: public OopClosure {
6887   G1CollectedHeap* _g1h;
6888   nmethod* _nm;
6889 
6890   template <class T> void do_oop_work(T* p) {
6891     T heap_oop = oopDesc::load_heap_oop(p);
6892     if (!oopDesc::is_null(heap_oop)) {
6893       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6894       HeapRegion* hr = _g1h->heap_region_containing(obj);
6895       assert(!hr->is_continues_humongous(),
6896              err_msg("trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
6897                      " starting at " HR_FORMAT,
6898                      p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
6899 
6900       hr->remove_strong_code_root(_nm);
6901     }
6902   }
6903 
6904 public:
6905   UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
6906     _g1h(g1h), _nm(nm) {}
6907 
6908   void do_oop(oop* p)       { do_oop_work(p); }
6909   void do_oop(narrowOop* p) { do_oop_work(p); }
6910 };
6911 
6912 void G1CollectedHeap::register_nmethod(nmethod* nm) {
6913   CollectedHeap::register_nmethod(nm);
6914 
6915   guarantee(nm != NULL, "sanity");
6916   RegisterNMethodOopClosure reg_cl(this, nm);
6917   nm->oops_do(&reg_cl);
6918 }
6919 
6920 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
6921   CollectedHeap::unregister_nmethod(nm);
6922 
6923   guarantee(nm != NULL, "sanity");
6924   UnregisterNMethodOopClosure reg_cl(this, nm);
6925   nm->oops_do(&reg_cl, true);
6926 }
6927 
6928 void G1CollectedHeap::purge_code_root_memory() {
6929   double purge_start = os::elapsedTime();
6930   G1CodeRootSet::purge();
6931   double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0;
6932   g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms);
6933 }
6934 
6935 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
6936   G1CollectedHeap* _g1h;
6937 
6938 public:
6939   RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
6940     _g1h(g1h) {}
6941 
6942   void do_code_blob(CodeBlob* cb) {
6943     nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
6944     if (nm == NULL) {
6945       return;
6946     }
6947 
6948     if (ScavengeRootsInCode) {
6949       _g1h->register_nmethod(nm);
6950     }
6951   }
6952 };
6953 
6954 void G1CollectedHeap::rebuild_strong_code_roots() {
6955   RebuildStrongCodeRootClosure blob_cl(this);
6956   CodeCache::blobs_do(&blob_cl);
6957 }