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