src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp

Mon, 23 Jun 2014 16:43:41 +0200

author
pliden
date
Mon, 23 Jun 2014 16:43:41 +0200
changeset 6905
fd81a5764900
parent 6904
0982ec23da03
child 6906
581e70386ec9
permissions
-rw-r--r--

8046231: G1: Code root location ... from nmethod ... not in strong code roots for region
Reviewed-by: tschatzl, ehelin

     1 /*
     2  * Copyright (c) 2001, 2014, 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  */
    25 #if !defined(__clang_major__) && defined(__GNUC__)
    26 #define ATTRIBUTE_PRINTF(x,y) // FIXME, formats are a mess.
    27 #endif
    29 #include "precompiled.hpp"
    30 #include "code/codeCache.hpp"
    31 #include "code/icBuffer.hpp"
    32 #include "gc_implementation/g1/bufferingOopClosure.hpp"
    33 #include "gc_implementation/g1/concurrentG1Refine.hpp"
    34 #include "gc_implementation/g1/concurrentG1RefineThread.hpp"
    35 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
    36 #include "gc_implementation/g1/g1AllocRegion.inline.hpp"
    37 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
    38 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
    39 #include "gc_implementation/g1/g1ErgoVerbose.hpp"
    40 #include "gc_implementation/g1/g1EvacFailure.hpp"
    41 #include "gc_implementation/g1/g1GCPhaseTimes.hpp"
    42 #include "gc_implementation/g1/g1Log.hpp"
    43 #include "gc_implementation/g1/g1MarkSweep.hpp"
    44 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
    45 #include "gc_implementation/g1/g1RemSet.inline.hpp"
    46 #include "gc_implementation/g1/g1StringDedup.hpp"
    47 #include "gc_implementation/g1/g1YCTypes.hpp"
    48 #include "gc_implementation/g1/heapRegion.inline.hpp"
    49 #include "gc_implementation/g1/heapRegionRemSet.hpp"
    50 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
    51 #include "gc_implementation/g1/vm_operations_g1.hpp"
    52 #include "gc_implementation/shared/gcHeapSummary.hpp"
    53 #include "gc_implementation/shared/gcTimer.hpp"
    54 #include "gc_implementation/shared/gcTrace.hpp"
    55 #include "gc_implementation/shared/gcTraceTime.hpp"
    56 #include "gc_implementation/shared/isGCActiveMark.hpp"
    57 #include "memory/gcLocker.inline.hpp"
    58 #include "memory/generationSpec.hpp"
    59 #include "memory/iterator.hpp"
    60 #include "memory/referenceProcessor.hpp"
    61 #include "oops/oop.inline.hpp"
    62 #include "oops/oop.pcgc.inline.hpp"
    63 #include "runtime/vmThread.hpp"
    64 #include "utilities/ticks.hpp"
    66 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
    68 // turn it on so that the contents of the young list (scan-only /
    69 // to-be-collected) are printed at "strategic" points before / during
    70 // / after the collection --- this is useful for debugging
    71 #define YOUNG_LIST_VERBOSE 0
    72 // CURRENT STATUS
    73 // This file is under construction.  Search for "FIXME".
    75 // INVARIANTS/NOTES
    76 //
    77 // All allocation activity covered by the G1CollectedHeap interface is
    78 // serialized by acquiring the HeapLock.  This happens in mem_allocate
    79 // and allocate_new_tlab, which are the "entry" points to the
    80 // allocation code from the rest of the JVM.  (Note that this does not
    81 // apply to TLAB allocation, which is not part of this interface: it
    82 // is done by clients of this interface.)
    84 // Notes on implementation of parallelism in different tasks.
    85 //
    86 // G1ParVerifyTask uses heap_region_par_iterate_chunked() for parallelism.
    87 // The number of GC workers is passed to heap_region_par_iterate_chunked().
    88 // It does use run_task() which sets _n_workers in the task.
    89 // G1ParTask executes g1_process_strong_roots() ->
    90 // SharedHeap::process_strong_roots() which calls eventually to
    91 // CardTableModRefBS::par_non_clean_card_iterate_work() which uses
    92 // SequentialSubTasksDone.  SharedHeap::process_strong_roots() also
    93 // directly uses SubTasksDone (_process_strong_tasks field in SharedHeap).
    94 //
    96 // Local to this file.
    98 class RefineCardTableEntryClosure: public CardTableEntryClosure {
    99   SuspendibleThreadSet* _sts;
   100   G1RemSet* _g1rs;
   101   ConcurrentG1Refine* _cg1r;
   102   bool _concurrent;
   103 public:
   104   RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
   105                               G1RemSet* g1rs,
   106                               ConcurrentG1Refine* cg1r) :
   107     _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
   108   {}
   109   bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
   110     bool oops_into_cset = _g1rs->refine_card(card_ptr, worker_i, false);
   111     // This path is executed by the concurrent refine or mutator threads,
   112     // concurrently, and so we do not care if card_ptr contains references
   113     // that point into the collection set.
   114     assert(!oops_into_cset, "should be");
   116     if (_concurrent && _sts->should_yield()) {
   117       // Caller will actually yield.
   118       return false;
   119     }
   120     // Otherwise, we finished successfully; return true.
   121     return true;
   122   }
   123   void set_concurrent(bool b) { _concurrent = b; }
   124 };
   127 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
   128   int _calls;
   129   G1CollectedHeap* _g1h;
   130   CardTableModRefBS* _ctbs;
   131   int _histo[256];
   132 public:
   133   ClearLoggedCardTableEntryClosure() :
   134     _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set())
   135   {
   136     for (int i = 0; i < 256; i++) _histo[i] = 0;
   137   }
   138   bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
   139     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
   140       _calls++;
   141       unsigned char* ujb = (unsigned char*)card_ptr;
   142       int ind = (int)(*ujb);
   143       _histo[ind]++;
   144       *card_ptr = -1;
   145     }
   146     return true;
   147   }
   148   int calls() { return _calls; }
   149   void print_histo() {
   150     gclog_or_tty->print_cr("Card table value histogram:");
   151     for (int i = 0; i < 256; i++) {
   152       if (_histo[i] != 0) {
   153         gclog_or_tty->print_cr("  %d: %d", i, _histo[i]);
   154       }
   155     }
   156   }
   157 };
   159 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
   160   int _calls;
   161   G1CollectedHeap* _g1h;
   162   CardTableModRefBS* _ctbs;
   163 public:
   164   RedirtyLoggedCardTableEntryClosure() :
   165     _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set()) {}
   167   bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
   168     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
   169       _calls++;
   170       *card_ptr = 0;
   171     }
   172     return true;
   173   }
   174   int calls() { return _calls; }
   175 };
   177 YoungList::YoungList(G1CollectedHeap* g1h) :
   178     _g1h(g1h), _head(NULL), _length(0), _last_sampled_rs_lengths(0),
   179     _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0) {
   180   guarantee(check_list_empty(false), "just making sure...");
   181 }
   183 void YoungList::push_region(HeapRegion *hr) {
   184   assert(!hr->is_young(), "should not already be young");
   185   assert(hr->get_next_young_region() == NULL, "cause it should!");
   187   hr->set_next_young_region(_head);
   188   _head = hr;
   190   _g1h->g1_policy()->set_region_eden(hr, (int) _length);
   191   ++_length;
   192 }
   194 void YoungList::add_survivor_region(HeapRegion* hr) {
   195   assert(hr->is_survivor(), "should be flagged as survivor region");
   196   assert(hr->get_next_young_region() == NULL, "cause it should!");
   198   hr->set_next_young_region(_survivor_head);
   199   if (_survivor_head == NULL) {
   200     _survivor_tail = hr;
   201   }
   202   _survivor_head = hr;
   203   ++_survivor_length;
   204 }
   206 void YoungList::empty_list(HeapRegion* list) {
   207   while (list != NULL) {
   208     HeapRegion* next = list->get_next_young_region();
   209     list->set_next_young_region(NULL);
   210     list->uninstall_surv_rate_group();
   211     list->set_not_young();
   212     list = next;
   213   }
   214 }
   216 void YoungList::empty_list() {
   217   assert(check_list_well_formed(), "young list should be well formed");
   219   empty_list(_head);
   220   _head = NULL;
   221   _length = 0;
   223   empty_list(_survivor_head);
   224   _survivor_head = NULL;
   225   _survivor_tail = NULL;
   226   _survivor_length = 0;
   228   _last_sampled_rs_lengths = 0;
   230   assert(check_list_empty(false), "just making sure...");
   231 }
   233 bool YoungList::check_list_well_formed() {
   234   bool ret = true;
   236   uint length = 0;
   237   HeapRegion* curr = _head;
   238   HeapRegion* last = NULL;
   239   while (curr != NULL) {
   240     if (!curr->is_young()) {
   241       gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
   242                              "incorrectly tagged (y: %d, surv: %d)",
   243                              curr->bottom(), curr->end(),
   244                              curr->is_young(), curr->is_survivor());
   245       ret = false;
   246     }
   247     ++length;
   248     last = curr;
   249     curr = curr->get_next_young_region();
   250   }
   251   ret = ret && (length == _length);
   253   if (!ret) {
   254     gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
   255     gclog_or_tty->print_cr("###   list has %u entries, _length is %u",
   256                            length, _length);
   257   }
   259   return ret;
   260 }
   262 bool YoungList::check_list_empty(bool check_sample) {
   263   bool ret = true;
   265   if (_length != 0) {
   266     gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %u",
   267                   _length);
   268     ret = false;
   269   }
   270   if (check_sample && _last_sampled_rs_lengths != 0) {
   271     gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
   272     ret = false;
   273   }
   274   if (_head != NULL) {
   275     gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
   276     ret = false;
   277   }
   278   if (!ret) {
   279     gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
   280   }
   282   return ret;
   283 }
   285 void
   286 YoungList::rs_length_sampling_init() {
   287   _sampled_rs_lengths = 0;
   288   _curr               = _head;
   289 }
   291 bool
   292 YoungList::rs_length_sampling_more() {
   293   return _curr != NULL;
   294 }
   296 void
   297 YoungList::rs_length_sampling_next() {
   298   assert( _curr != NULL, "invariant" );
   299   size_t rs_length = _curr->rem_set()->occupied();
   301   _sampled_rs_lengths += rs_length;
   303   // The current region may not yet have been added to the
   304   // incremental collection set (it gets added when it is
   305   // retired as the current allocation region).
   306   if (_curr->in_collection_set()) {
   307     // Update the collection set policy information for this region
   308     _g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);
   309   }
   311   _curr = _curr->get_next_young_region();
   312   if (_curr == NULL) {
   313     _last_sampled_rs_lengths = _sampled_rs_lengths;
   314     // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
   315   }
   316 }
   318 void
   319 YoungList::reset_auxilary_lists() {
   320   guarantee( is_empty(), "young list should be empty" );
   321   assert(check_list_well_formed(), "young list should be well formed");
   323   // Add survivor regions to SurvRateGroup.
   324   _g1h->g1_policy()->note_start_adding_survivor_regions();
   325   _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
   327   int young_index_in_cset = 0;
   328   for (HeapRegion* curr = _survivor_head;
   329        curr != NULL;
   330        curr = curr->get_next_young_region()) {
   331     _g1h->g1_policy()->set_region_survivor(curr, young_index_in_cset);
   333     // The region is a non-empty survivor so let's add it to
   334     // the incremental collection set for the next evacuation
   335     // pause.
   336     _g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);
   337     young_index_in_cset += 1;
   338   }
   339   assert((uint) young_index_in_cset == _survivor_length, "post-condition");
   340   _g1h->g1_policy()->note_stop_adding_survivor_regions();
   342   _head   = _survivor_head;
   343   _length = _survivor_length;
   344   if (_survivor_head != NULL) {
   345     assert(_survivor_tail != NULL, "cause it shouldn't be");
   346     assert(_survivor_length > 0, "invariant");
   347     _survivor_tail->set_next_young_region(NULL);
   348   }
   350   // Don't clear the survivor list handles until the start of
   351   // the next evacuation pause - we need it in order to re-tag
   352   // the survivor regions from this evacuation pause as 'young'
   353   // at the start of the next.
   355   _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
   357   assert(check_list_well_formed(), "young list should be well formed");
   358 }
   360 void YoungList::print() {
   361   HeapRegion* lists[] = {_head,   _survivor_head};
   362   const char* names[] = {"YOUNG", "SURVIVOR"};
   364   for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
   365     gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
   366     HeapRegion *curr = lists[list];
   367     if (curr == NULL)
   368       gclog_or_tty->print_cr("  empty");
   369     while (curr != NULL) {
   370       gclog_or_tty->print_cr("  "HR_FORMAT", P: "PTR_FORMAT "N: "PTR_FORMAT", age: %4d",
   371                              HR_FORMAT_PARAMS(curr),
   372                              curr->prev_top_at_mark_start(),
   373                              curr->next_top_at_mark_start(),
   374                              curr->age_in_surv_rate_group_cond());
   375       curr = curr->get_next_young_region();
   376     }
   377   }
   379   gclog_or_tty->cr();
   380 }
   382 void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)
   383 {
   384   // Claim the right to put the region on the dirty cards region list
   385   // by installing a self pointer.
   386   HeapRegion* next = hr->get_next_dirty_cards_region();
   387   if (next == NULL) {
   388     HeapRegion* res = (HeapRegion*)
   389       Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),
   390                           NULL);
   391     if (res == NULL) {
   392       HeapRegion* head;
   393       do {
   394         // Put the region to the dirty cards region list.
   395         head = _dirty_cards_region_list;
   396         next = (HeapRegion*)
   397           Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);
   398         if (next == head) {
   399           assert(hr->get_next_dirty_cards_region() == hr,
   400                  "hr->get_next_dirty_cards_region() != hr");
   401           if (next == NULL) {
   402             // The last region in the list points to itself.
   403             hr->set_next_dirty_cards_region(hr);
   404           } else {
   405             hr->set_next_dirty_cards_region(next);
   406           }
   407         }
   408       } while (next != head);
   409     }
   410   }
   411 }
   413 HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
   414 {
   415   HeapRegion* head;
   416   HeapRegion* hr;
   417   do {
   418     head = _dirty_cards_region_list;
   419     if (head == NULL) {
   420       return NULL;
   421     }
   422     HeapRegion* new_head = head->get_next_dirty_cards_region();
   423     if (head == new_head) {
   424       // The last region.
   425       new_head = NULL;
   426     }
   427     hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,
   428                                           head);
   429   } while (hr != head);
   430   assert(hr != NULL, "invariant");
   431   hr->set_next_dirty_cards_region(NULL);
   432   return hr;
   433 }
   435 #ifdef ASSERT
   436 // A region is added to the collection set as it is retired
   437 // so an address p can point to a region which will be in the
   438 // collection set but has not yet been retired.  This method
   439 // therefore is only accurate during a GC pause after all
   440 // regions have been retired.  It is used for debugging
   441 // to check if an nmethod has references to objects that can
   442 // be move during a partial collection.  Though it can be
   443 // inaccurate, it is sufficient for G1 because the conservative
   444 // implementation of is_scavengable() for G1 will indicate that
   445 // all nmethods must be scanned during a partial collection.
   446 bool G1CollectedHeap::is_in_partial_collection(const void* p) {
   447   HeapRegion* hr = heap_region_containing(p);
   448   return hr != NULL && hr->in_collection_set();
   449 }
   450 #endif
   452 // Returns true if the reference points to an object that
   453 // can move in an incremental collection.
   454 bool G1CollectedHeap::is_scavengable(const void* p) {
   455   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   456   G1CollectorPolicy* g1p = g1h->g1_policy();
   457   HeapRegion* hr = heap_region_containing(p);
   458   if (hr == NULL) {
   459      // null
   460      assert(p == NULL, err_msg("Not NULL " PTR_FORMAT ,p));
   461      return false;
   462   } else {
   463     return !hr->isHumongous();
   464   }
   465 }
   467 void G1CollectedHeap::check_ct_logs_at_safepoint() {
   468   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
   469   CardTableModRefBS* ct_bs = g1_barrier_set();
   471   // Count the dirty cards at the start.
   472   CountNonCleanMemRegionClosure count1(this);
   473   ct_bs->mod_card_iterate(&count1);
   474   int orig_count = count1.n();
   476   // First clear the logged cards.
   477   ClearLoggedCardTableEntryClosure clear;
   478   dcqs.set_closure(&clear);
   479   dcqs.apply_closure_to_all_completed_buffers();
   480   dcqs.iterate_closure_all_threads(false);
   481   clear.print_histo();
   483   // Now ensure that there's no dirty cards.
   484   CountNonCleanMemRegionClosure count2(this);
   485   ct_bs->mod_card_iterate(&count2);
   486   if (count2.n() != 0) {
   487     gclog_or_tty->print_cr("Card table has %d entries; %d originally",
   488                            count2.n(), orig_count);
   489   }
   490   guarantee(count2.n() == 0, "Card table should be clean.");
   492   RedirtyLoggedCardTableEntryClosure redirty;
   493   JavaThread::dirty_card_queue_set().set_closure(&redirty);
   494   dcqs.apply_closure_to_all_completed_buffers();
   495   dcqs.iterate_closure_all_threads(false);
   496   gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
   497                          clear.calls(), orig_count);
   498   guarantee(redirty.calls() == clear.calls(),
   499             "Or else mechanism is broken.");
   501   CountNonCleanMemRegionClosure count3(this);
   502   ct_bs->mod_card_iterate(&count3);
   503   if (count3.n() != orig_count) {
   504     gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
   505                            orig_count, count3.n());
   506     guarantee(count3.n() >= orig_count, "Should have restored them all.");
   507   }
   509   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
   510 }
   512 // Private class members.
   514 G1CollectedHeap* G1CollectedHeap::_g1h;
   516 // Private methods.
   518 HeapRegion*
   519 G1CollectedHeap::new_region_try_secondary_free_list(bool is_old) {
   520   MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
   521   while (!_secondary_free_list.is_empty() || free_regions_coming()) {
   522     if (!_secondary_free_list.is_empty()) {
   523       if (G1ConcRegionFreeingVerbose) {
   524         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
   525                                "secondary_free_list has %u entries",
   526                                _secondary_free_list.length());
   527       }
   528       // It looks as if there are free regions available on the
   529       // secondary_free_list. Let's move them to the free_list and try
   530       // again to allocate from it.
   531       append_secondary_free_list();
   533       assert(!_free_list.is_empty(), "if the secondary_free_list was not "
   534              "empty we should have moved at least one entry to the free_list");
   535       HeapRegion* res = _free_list.remove_region(is_old);
   536       if (G1ConcRegionFreeingVerbose) {
   537         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
   538                                "allocated "HR_FORMAT" from secondary_free_list",
   539                                HR_FORMAT_PARAMS(res));
   540       }
   541       return res;
   542     }
   544     // Wait here until we get notified either when (a) there are no
   545     // more free regions coming or (b) some regions have been moved on
   546     // the secondary_free_list.
   547     SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
   548   }
   550   if (G1ConcRegionFreeingVerbose) {
   551     gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
   552                            "could not allocate from secondary_free_list");
   553   }
   554   return NULL;
   555 }
   557 HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool is_old, bool do_expand) {
   558   assert(!isHumongous(word_size) || word_size <= HeapRegion::GrainWords,
   559          "the only time we use this to allocate a humongous region is "
   560          "when we are allocating a single humongous region");
   562   HeapRegion* res;
   563   if (G1StressConcRegionFreeing) {
   564     if (!_secondary_free_list.is_empty()) {
   565       if (G1ConcRegionFreeingVerbose) {
   566         gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
   567                                "forced to look at the secondary_free_list");
   568       }
   569       res = new_region_try_secondary_free_list(is_old);
   570       if (res != NULL) {
   571         return res;
   572       }
   573     }
   574   }
   576   res = _free_list.remove_region(is_old);
   578   if (res == NULL) {
   579     if (G1ConcRegionFreeingVerbose) {
   580       gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
   581                              "res == NULL, trying the secondary_free_list");
   582     }
   583     res = new_region_try_secondary_free_list(is_old);
   584   }
   585   if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
   586     // Currently, only attempts to allocate GC alloc regions set
   587     // do_expand to true. So, we should only reach here during a
   588     // safepoint. If this assumption changes we might have to
   589     // reconsider the use of _expand_heap_after_alloc_failure.
   590     assert(SafepointSynchronize::is_at_safepoint(), "invariant");
   592     ergo_verbose1(ErgoHeapSizing,
   593                   "attempt heap expansion",
   594                   ergo_format_reason("region allocation request failed")
   595                   ergo_format_byte("allocation request"),
   596                   word_size * HeapWordSize);
   597     if (expand(word_size * HeapWordSize)) {
   598       // Given that expand() succeeded in expanding the heap, and we
   599       // always expand the heap by an amount aligned to the heap
   600       // region size, the free list should in theory not be empty.
   601       // In either case remove_region() will check for NULL.
   602       res = _free_list.remove_region(is_old);
   603     } else {
   604       _expand_heap_after_alloc_failure = false;
   605     }
   606   }
   607   return res;
   608 }
   610 uint G1CollectedHeap::humongous_obj_allocate_find_first(uint num_regions,
   611                                                         size_t word_size) {
   612   assert(isHumongous(word_size), "word_size should be humongous");
   613   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
   615   uint first = G1_NULL_HRS_INDEX;
   616   if (num_regions == 1) {
   617     // Only one region to allocate, no need to go through the slower
   618     // path. The caller will attempt the expansion if this fails, so
   619     // let's not try to expand here too.
   620     HeapRegion* hr = new_region(word_size, true /* is_old */, false /* do_expand */);
   621     if (hr != NULL) {
   622       first = hr->hrs_index();
   623     } else {
   624       first = G1_NULL_HRS_INDEX;
   625     }
   626   } else {
   627     // We can't allocate humongous regions while cleanupComplete() is
   628     // running, since some of the regions we find to be empty might not
   629     // yet be added to the free list and it is not straightforward to
   630     // know which list they are on so that we can remove them. Note
   631     // that we only need to do this if we need to allocate more than
   632     // one region to satisfy the current humongous allocation
   633     // request. If we are only allocating one region we use the common
   634     // region allocation code (see above).
   635     wait_while_free_regions_coming();
   636     append_secondary_free_list_if_not_empty_with_lock();
   638     if (free_regions() >= num_regions) {
   639       first = _hrs.find_contiguous(num_regions);
   640       if (first != G1_NULL_HRS_INDEX) {
   641         for (uint i = first; i < first + num_regions; ++i) {
   642           HeapRegion* hr = region_at(i);
   643           assert(hr->is_empty(), "sanity");
   644           assert(is_on_master_free_list(hr), "sanity");
   645           hr->set_pending_removal(true);
   646         }
   647         _free_list.remove_all_pending(num_regions);
   648       }
   649     }
   650   }
   651   return first;
   652 }
   654 HeapWord*
   655 G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first,
   656                                                            uint num_regions,
   657                                                            size_t word_size) {
   658   assert(first != G1_NULL_HRS_INDEX, "pre-condition");
   659   assert(isHumongous(word_size), "word_size should be humongous");
   660   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
   662   // Index of last region in the series + 1.
   663   uint last = first + num_regions;
   665   // We need to initialize the region(s) we just discovered. This is
   666   // a bit tricky given that it can happen concurrently with
   667   // refinement threads refining cards on these regions and
   668   // potentially wanting to refine the BOT as they are scanning
   669   // those cards (this can happen shortly after a cleanup; see CR
   670   // 6991377). So we have to set up the region(s) carefully and in
   671   // a specific order.
   673   // The word size sum of all the regions we will allocate.
   674   size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
   675   assert(word_size <= word_size_sum, "sanity");
   677   // This will be the "starts humongous" region.
   678   HeapRegion* first_hr = region_at(first);
   679   // The header of the new object will be placed at the bottom of
   680   // the first region.
   681   HeapWord* new_obj = first_hr->bottom();
   682   // This will be the new end of the first region in the series that
   683   // should also match the end of the last region in the series.
   684   HeapWord* new_end = new_obj + word_size_sum;
   685   // This will be the new top of the first region that will reflect
   686   // this allocation.
   687   HeapWord* new_top = new_obj + word_size;
   689   // First, we need to zero the header of the space that we will be
   690   // allocating. When we update top further down, some refinement
   691   // threads might try to scan the region. By zeroing the header we
   692   // ensure that any thread that will try to scan the region will
   693   // come across the zero klass word and bail out.
   694   //
   695   // NOTE: It would not have been correct to have used
   696   // CollectedHeap::fill_with_object() and make the space look like
   697   // an int array. The thread that is doing the allocation will
   698   // later update the object header to a potentially different array
   699   // type and, for a very short period of time, the klass and length
   700   // fields will be inconsistent. This could cause a refinement
   701   // thread to calculate the object size incorrectly.
   702   Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
   704   // We will set up the first region as "starts humongous". This
   705   // will also update the BOT covering all the regions to reflect
   706   // that there is a single object that starts at the bottom of the
   707   // first region.
   708   first_hr->set_startsHumongous(new_top, new_end);
   710   // Then, if there are any, we will set up the "continues
   711   // humongous" regions.
   712   HeapRegion* hr = NULL;
   713   for (uint i = first + 1; i < last; ++i) {
   714     hr = region_at(i);
   715     hr->set_continuesHumongous(first_hr);
   716   }
   717   // If we have "continues humongous" regions (hr != NULL), then the
   718   // end of the last one should match new_end.
   719   assert(hr == NULL || hr->end() == new_end, "sanity");
   721   // Up to this point no concurrent thread would have been able to
   722   // do any scanning on any region in this series. All the top
   723   // fields still point to bottom, so the intersection between
   724   // [bottom,top] and [card_start,card_end] will be empty. Before we
   725   // update the top fields, we'll do a storestore to make sure that
   726   // no thread sees the update to top before the zeroing of the
   727   // object header and the BOT initialization.
   728   OrderAccess::storestore();
   730   // Now that the BOT and the object header have been initialized,
   731   // we can update top of the "starts humongous" region.
   732   assert(first_hr->bottom() < new_top && new_top <= first_hr->end(),
   733          "new_top should be in this region");
   734   first_hr->set_top(new_top);
   735   if (_hr_printer.is_active()) {
   736     HeapWord* bottom = first_hr->bottom();
   737     HeapWord* end = first_hr->orig_end();
   738     if ((first + 1) == last) {
   739       // the series has a single humongous region
   740       _hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top);
   741     } else {
   742       // the series has more than one humongous regions
   743       _hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end);
   744     }
   745   }
   747   // Now, we will update the top fields of the "continues humongous"
   748   // regions. The reason we need to do this is that, otherwise,
   749   // these regions would look empty and this will confuse parts of
   750   // G1. For example, the code that looks for a consecutive number
   751   // of empty regions will consider them empty and try to
   752   // re-allocate them. We can extend is_empty() to also include
   753   // !continuesHumongous(), but it is easier to just update the top
   754   // fields here. The way we set top for all regions (i.e., top ==
   755   // end for all regions but the last one, top == new_top for the
   756   // last one) is actually used when we will free up the humongous
   757   // region in free_humongous_region().
   758   hr = NULL;
   759   for (uint i = first + 1; i < last; ++i) {
   760     hr = region_at(i);
   761     if ((i + 1) == last) {
   762       // last continues humongous region
   763       assert(hr->bottom() < new_top && new_top <= hr->end(),
   764              "new_top should fall on this region");
   765       hr->set_top(new_top);
   766       _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top);
   767     } else {
   768       // not last one
   769       assert(new_top > hr->end(), "new_top should be above this region");
   770       hr->set_top(hr->end());
   771       _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end());
   772     }
   773   }
   774   // If we have continues humongous regions (hr != NULL), then the
   775   // end of the last one should match new_end and its top should
   776   // match new_top.
   777   assert(hr == NULL ||
   778          (hr->end() == new_end && hr->top() == new_top), "sanity");
   780   assert(first_hr->used() == word_size * HeapWordSize, "invariant");
   781   _summary_bytes_used += first_hr->used();
   782   _humongous_set.add(first_hr);
   784   return new_obj;
   785 }
   787 // If could fit into free regions w/o expansion, try.
   788 // Otherwise, if can expand, do so.
   789 // Otherwise, if using ex regions might help, try with ex given back.
   790 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
   791   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
   793   verify_region_sets_optional();
   795   size_t word_size_rounded = round_to(word_size, HeapRegion::GrainWords);
   796   uint num_regions = (uint) (word_size_rounded / HeapRegion::GrainWords);
   797   uint x_num = expansion_regions();
   798   uint fs = _hrs.free_suffix();
   799   uint first = humongous_obj_allocate_find_first(num_regions, word_size);
   800   if (first == G1_NULL_HRS_INDEX) {
   801     // The only thing we can do now is attempt expansion.
   802     if (fs + x_num >= num_regions) {
   803       // If the number of regions we're trying to allocate for this
   804       // object is at most the number of regions in the free suffix,
   805       // then the call to humongous_obj_allocate_find_first() above
   806       // should have succeeded and we wouldn't be here.
   807       //
   808       // We should only be trying to expand when the free suffix is
   809       // not sufficient for the object _and_ we have some expansion
   810       // room available.
   811       assert(num_regions > fs, "earlier allocation should have succeeded");
   813       ergo_verbose1(ErgoHeapSizing,
   814                     "attempt heap expansion",
   815                     ergo_format_reason("humongous allocation request failed")
   816                     ergo_format_byte("allocation request"),
   817                     word_size * HeapWordSize);
   818       if (expand((num_regions - fs) * HeapRegion::GrainBytes)) {
   819         // Even though the heap was expanded, it might not have
   820         // reached the desired size. So, we cannot assume that the
   821         // allocation will succeed.
   822         first = humongous_obj_allocate_find_first(num_regions, word_size);
   823       }
   824     }
   825   }
   827   HeapWord* result = NULL;
   828   if (first != G1_NULL_HRS_INDEX) {
   829     result =
   830       humongous_obj_allocate_initialize_regions(first, num_regions, word_size);
   831     assert(result != NULL, "it should always return a valid result");
   833     // A successful humongous object allocation changes the used space
   834     // information of the old generation so we need to recalculate the
   835     // sizes and update the jstat counters here.
   836     g1mm()->update_sizes();
   837   }
   839   verify_region_sets_optional();
   841   return result;
   842 }
   844 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {
   845   assert_heap_not_locked_and_not_at_safepoint();
   846   assert(!isHumongous(word_size), "we do not allow humongous TLABs");
   848   unsigned int dummy_gc_count_before;
   849   int dummy_gclocker_retry_count = 0;
   850   return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);
   851 }
   853 HeapWord*
   854 G1CollectedHeap::mem_allocate(size_t word_size,
   855                               bool*  gc_overhead_limit_was_exceeded) {
   856   assert_heap_not_locked_and_not_at_safepoint();
   858   // Loop until the allocation is satisfied, or unsatisfied after GC.
   859   for (int try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
   860     unsigned int gc_count_before;
   862     HeapWord* result = NULL;
   863     if (!isHumongous(word_size)) {
   864       result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);
   865     } else {
   866       result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);
   867     }
   868     if (result != NULL) {
   869       return result;
   870     }
   872     // Create the garbage collection operation...
   873     VM_G1CollectForAllocation op(gc_count_before, word_size);
   874     // ...and get the VM thread to execute it.
   875     VMThread::execute(&op);
   877     if (op.prologue_succeeded() && op.pause_succeeded()) {
   878       // If the operation was successful we'll return the result even
   879       // if it is NULL. If the allocation attempt failed immediately
   880       // after a Full GC, it's unlikely we'll be able to allocate now.
   881       HeapWord* result = op.result();
   882       if (result != NULL && !isHumongous(word_size)) {
   883         // Allocations that take place on VM operations do not do any
   884         // card dirtying and we have to do it here. We only have to do
   885         // this for non-humongous allocations, though.
   886         dirty_young_block(result, word_size);
   887       }
   888       return result;
   889     } else {
   890       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
   891         return NULL;
   892       }
   893       assert(op.result() == NULL,
   894              "the result should be NULL if the VM op did not succeed");
   895     }
   897     // Give a warning if we seem to be looping forever.
   898     if ((QueuedAllocationWarningCount > 0) &&
   899         (try_count % QueuedAllocationWarningCount == 0)) {
   900       warning("G1CollectedHeap::mem_allocate retries %d times", try_count);
   901     }
   902   }
   904   ShouldNotReachHere();
   905   return NULL;
   906 }
   908 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
   909                                            unsigned int *gc_count_before_ret,
   910                                            int* gclocker_retry_count_ret) {
   911   // Make sure you read the note in attempt_allocation_humongous().
   913   assert_heap_not_locked_and_not_at_safepoint();
   914   assert(!isHumongous(word_size), "attempt_allocation_slow() should not "
   915          "be called for humongous allocation requests");
   917   // We should only get here after the first-level allocation attempt
   918   // (attempt_allocation()) failed to allocate.
   920   // We will loop until a) we manage to successfully perform the
   921   // allocation or b) we successfully schedule a collection which
   922   // fails to perform the allocation. b) is the only case when we'll
   923   // return NULL.
   924   HeapWord* result = NULL;
   925   for (int try_count = 1; /* we'll return */; try_count += 1) {
   926     bool should_try_gc;
   927     unsigned int gc_count_before;
   929     {
   930       MutexLockerEx x(Heap_lock);
   932       result = _mutator_alloc_region.attempt_allocation_locked(word_size,
   933                                                       false /* bot_updates */);
   934       if (result != NULL) {
   935         return result;
   936       }
   938       // If we reach here, attempt_allocation_locked() above failed to
   939       // allocate a new region. So the mutator alloc region should be NULL.
   940       assert(_mutator_alloc_region.get() == NULL, "only way to get here");
   942       if (GC_locker::is_active_and_needs_gc()) {
   943         if (g1_policy()->can_expand_young_list()) {
   944           // No need for an ergo verbose message here,
   945           // can_expand_young_list() does this when it returns true.
   946           result = _mutator_alloc_region.attempt_allocation_force(word_size,
   947                                                       false /* bot_updates */);
   948           if (result != NULL) {
   949             return result;
   950           }
   951         }
   952         should_try_gc = false;
   953       } else {
   954         // The GCLocker may not be active but the GCLocker initiated
   955         // GC may not yet have been performed (GCLocker::needs_gc()
   956         // returns true). In this case we do not try this GC and
   957         // wait until the GCLocker initiated GC is performed, and
   958         // then retry the allocation.
   959         if (GC_locker::needs_gc()) {
   960           should_try_gc = false;
   961         } else {
   962           // Read the GC count while still holding the Heap_lock.
   963           gc_count_before = total_collections();
   964           should_try_gc = true;
   965         }
   966       }
   967     }
   969     if (should_try_gc) {
   970       bool succeeded;
   971       result = do_collection_pause(word_size, gc_count_before, &succeeded,
   972           GCCause::_g1_inc_collection_pause);
   973       if (result != NULL) {
   974         assert(succeeded, "only way to get back a non-NULL result");
   975         return result;
   976       }
   978       if (succeeded) {
   979         // If we get here we successfully scheduled a collection which
   980         // failed to allocate. No point in trying to allocate
   981         // further. We'll just return NULL.
   982         MutexLockerEx x(Heap_lock);
   983         *gc_count_before_ret = total_collections();
   984         return NULL;
   985       }
   986     } else {
   987       if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
   988         MutexLockerEx x(Heap_lock);
   989         *gc_count_before_ret = total_collections();
   990         return NULL;
   991       }
   992       // The GCLocker is either active or the GCLocker initiated
   993       // GC has not yet been performed. Stall until it is and
   994       // then retry the allocation.
   995       GC_locker::stall_until_clear();
   996       (*gclocker_retry_count_ret) += 1;
   997     }
   999     // We can reach here if we were unsuccessful in scheduling a
  1000     // collection (because another thread beat us to it) or if we were
  1001     // stalled due to the GC locker. In either can we should retry the
  1002     // allocation attempt in case another thread successfully
  1003     // performed a collection and reclaimed enough space. We do the
  1004     // first attempt (without holding the Heap_lock) here and the
  1005     // follow-on attempt will be at the start of the next loop
  1006     // iteration (after taking the Heap_lock).
  1007     result = _mutator_alloc_region.attempt_allocation(word_size,
  1008                                                       false /* bot_updates */);
  1009     if (result != NULL) {
  1010       return result;
  1013     // Give a warning if we seem to be looping forever.
  1014     if ((QueuedAllocationWarningCount > 0) &&
  1015         (try_count % QueuedAllocationWarningCount == 0)) {
  1016       warning("G1CollectedHeap::attempt_allocation_slow() "
  1017               "retries %d times", try_count);
  1021   ShouldNotReachHere();
  1022   return NULL;
  1025 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
  1026                                           unsigned int * gc_count_before_ret,
  1027                                           int* gclocker_retry_count_ret) {
  1028   // The structure of this method has a lot of similarities to
  1029   // attempt_allocation_slow(). The reason these two were not merged
  1030   // into a single one is that such a method would require several "if
  1031   // allocation is not humongous do this, otherwise do that"
  1032   // conditional paths which would obscure its flow. In fact, an early
  1033   // version of this code did use a unified method which was harder to
  1034   // follow and, as a result, it had subtle bugs that were hard to
  1035   // track down. So keeping these two methods separate allows each to
  1036   // be more readable. It will be good to keep these two in sync as
  1037   // much as possible.
  1039   assert_heap_not_locked_and_not_at_safepoint();
  1040   assert(isHumongous(word_size), "attempt_allocation_humongous() "
  1041          "should only be called for humongous allocations");
  1043   // Humongous objects can exhaust the heap quickly, so we should check if we
  1044   // need to start a marking cycle at each humongous object allocation. We do
  1045   // the check before we do the actual allocation. The reason for doing it
  1046   // before the allocation is that we avoid having to keep track of the newly
  1047   // allocated memory while we do a GC.
  1048   if (g1_policy()->need_to_start_conc_mark("concurrent humongous allocation",
  1049                                            word_size)) {
  1050     collect(GCCause::_g1_humongous_allocation);
  1053   // We will loop until a) we manage to successfully perform the
  1054   // allocation or b) we successfully schedule a collection which
  1055   // fails to perform the allocation. b) is the only case when we'll
  1056   // return NULL.
  1057   HeapWord* result = NULL;
  1058   for (int try_count = 1; /* we'll return */; try_count += 1) {
  1059     bool should_try_gc;
  1060     unsigned int gc_count_before;
  1063       MutexLockerEx x(Heap_lock);
  1065       // Given that humongous objects are not allocated in young
  1066       // regions, we'll first try to do the allocation without doing a
  1067       // collection hoping that there's enough space in the heap.
  1068       result = humongous_obj_allocate(word_size);
  1069       if (result != NULL) {
  1070         return result;
  1073       if (GC_locker::is_active_and_needs_gc()) {
  1074         should_try_gc = false;
  1075       } else {
  1076          // The GCLocker may not be active but the GCLocker initiated
  1077         // GC may not yet have been performed (GCLocker::needs_gc()
  1078         // returns true). In this case we do not try this GC and
  1079         // wait until the GCLocker initiated GC is performed, and
  1080         // then retry the allocation.
  1081         if (GC_locker::needs_gc()) {
  1082           should_try_gc = false;
  1083         } else {
  1084           // Read the GC count while still holding the Heap_lock.
  1085           gc_count_before = total_collections();
  1086           should_try_gc = true;
  1091     if (should_try_gc) {
  1092       // If we failed to allocate the humongous object, we should try to
  1093       // do a collection pause (if we're allowed) in case it reclaims
  1094       // enough space for the allocation to succeed after the pause.
  1096       bool succeeded;
  1097       result = do_collection_pause(word_size, gc_count_before, &succeeded,
  1098           GCCause::_g1_humongous_allocation);
  1099       if (result != NULL) {
  1100         assert(succeeded, "only way to get back a non-NULL result");
  1101         return result;
  1104       if (succeeded) {
  1105         // If we get here we successfully scheduled a collection which
  1106         // failed to allocate. No point in trying to allocate
  1107         // further. We'll just return NULL.
  1108         MutexLockerEx x(Heap_lock);
  1109         *gc_count_before_ret = total_collections();
  1110         return NULL;
  1112     } else {
  1113       if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
  1114         MutexLockerEx x(Heap_lock);
  1115         *gc_count_before_ret = total_collections();
  1116         return NULL;
  1118       // The GCLocker is either active or the GCLocker initiated
  1119       // GC has not yet been performed. Stall until it is and
  1120       // then retry the allocation.
  1121       GC_locker::stall_until_clear();
  1122       (*gclocker_retry_count_ret) += 1;
  1125     // We can reach here if we were unsuccessful in scheduling a
  1126     // collection (because another thread beat us to it) or if we were
  1127     // stalled due to the GC locker. In either can we should retry the
  1128     // allocation attempt in case another thread successfully
  1129     // performed a collection and reclaimed enough space.  Give a
  1130     // warning if we seem to be looping forever.
  1132     if ((QueuedAllocationWarningCount > 0) &&
  1133         (try_count % QueuedAllocationWarningCount == 0)) {
  1134       warning("G1CollectedHeap::attempt_allocation_humongous() "
  1135               "retries %d times", try_count);
  1139   ShouldNotReachHere();
  1140   return NULL;
  1143 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
  1144                                        bool expect_null_mutator_alloc_region) {
  1145   assert_at_safepoint(true /* should_be_vm_thread */);
  1146   assert(_mutator_alloc_region.get() == NULL ||
  1147                                              !expect_null_mutator_alloc_region,
  1148          "the current alloc region was unexpectedly found to be non-NULL");
  1150   if (!isHumongous(word_size)) {
  1151     return _mutator_alloc_region.attempt_allocation_locked(word_size,
  1152                                                       false /* bot_updates */);
  1153   } else {
  1154     HeapWord* result = humongous_obj_allocate(word_size);
  1155     if (result != NULL && g1_policy()->need_to_start_conc_mark("STW humongous allocation")) {
  1156       g1_policy()->set_initiate_conc_mark_if_possible();
  1158     return result;
  1161   ShouldNotReachHere();
  1164 class PostMCRemSetClearClosure: public HeapRegionClosure {
  1165   G1CollectedHeap* _g1h;
  1166   ModRefBarrierSet* _mr_bs;
  1167 public:
  1168   PostMCRemSetClearClosure(G1CollectedHeap* g1h, ModRefBarrierSet* mr_bs) :
  1169     _g1h(g1h), _mr_bs(mr_bs) {}
  1171   bool doHeapRegion(HeapRegion* r) {
  1172     HeapRegionRemSet* hrrs = r->rem_set();
  1174     if (r->continuesHumongous()) {
  1175       // We'll assert that the strong code root list and RSet is empty
  1176       assert(hrrs->strong_code_roots_list_length() == 0, "sanity");
  1177       assert(hrrs->occupied() == 0, "RSet should be empty");
  1178       return false;
  1181     _g1h->reset_gc_time_stamps(r);
  1182     hrrs->clear();
  1183     // You might think here that we could clear just the cards
  1184     // corresponding to the used region.  But no: if we leave a dirty card
  1185     // in a region we might allocate into, then it would prevent that card
  1186     // from being enqueued, and cause it to be missed.
  1187     // Re: the performance cost: we shouldn't be doing full GC anyway!
  1188     _mr_bs->clear(MemRegion(r->bottom(), r->end()));
  1190     return false;
  1192 };
  1194 void G1CollectedHeap::clear_rsets_post_compaction() {
  1195   PostMCRemSetClearClosure rs_clear(this, g1_barrier_set());
  1196   heap_region_iterate(&rs_clear);
  1199 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
  1200   G1CollectedHeap*   _g1h;
  1201   UpdateRSOopClosure _cl;
  1202   int                _worker_i;
  1203 public:
  1204   RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
  1205     _cl(g1->g1_rem_set(), worker_i),
  1206     _worker_i(worker_i),
  1207     _g1h(g1)
  1208   { }
  1210   bool doHeapRegion(HeapRegion* r) {
  1211     if (!r->continuesHumongous()) {
  1212       _cl.set_from(r);
  1213       r->oop_iterate(&_cl);
  1215     return false;
  1217 };
  1219 class ParRebuildRSTask: public AbstractGangTask {
  1220   G1CollectedHeap* _g1;
  1221 public:
  1222   ParRebuildRSTask(G1CollectedHeap* g1)
  1223     : AbstractGangTask("ParRebuildRSTask"),
  1224       _g1(g1)
  1225   { }
  1227   void work(uint worker_id) {
  1228     RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);
  1229     _g1->heap_region_par_iterate_chunked(&rebuild_rs, worker_id,
  1230                                           _g1->workers()->active_workers(),
  1231                                          HeapRegion::RebuildRSClaimValue);
  1233 };
  1235 class PostCompactionPrinterClosure: public HeapRegionClosure {
  1236 private:
  1237   G1HRPrinter* _hr_printer;
  1238 public:
  1239   bool doHeapRegion(HeapRegion* hr) {
  1240     assert(!hr->is_young(), "not expecting to find young regions");
  1241     // We only generate output for non-empty regions.
  1242     if (!hr->is_empty()) {
  1243       if (!hr->isHumongous()) {
  1244         _hr_printer->post_compaction(hr, G1HRPrinter::Old);
  1245       } else if (hr->startsHumongous()) {
  1246         if (hr->region_num() == 1) {
  1247           // single humongous region
  1248           _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
  1249         } else {
  1250           _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
  1252       } else {
  1253         assert(hr->continuesHumongous(), "only way to get here");
  1254         _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
  1257     return false;
  1260   PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
  1261     : _hr_printer(hr_printer) { }
  1262 };
  1264 void G1CollectedHeap::print_hrs_post_compaction() {
  1265   PostCompactionPrinterClosure cl(hr_printer());
  1266   heap_region_iterate(&cl);
  1269 bool G1CollectedHeap::do_collection(bool explicit_gc,
  1270                                     bool clear_all_soft_refs,
  1271                                     size_t word_size) {
  1272   assert_at_safepoint(true /* should_be_vm_thread */);
  1274   if (GC_locker::check_active_before_gc()) {
  1275     return false;
  1278   STWGCTimer* gc_timer = G1MarkSweep::gc_timer();
  1279   gc_timer->register_gc_start();
  1281   SerialOldTracer* gc_tracer = G1MarkSweep::gc_tracer();
  1282   gc_tracer->report_gc_start(gc_cause(), gc_timer->gc_start());
  1284   SvcGCMarker sgcm(SvcGCMarker::FULL);
  1285   ResourceMark rm;
  1287   print_heap_before_gc();
  1288   trace_heap_before_gc(gc_tracer);
  1290   size_t metadata_prev_used = MetaspaceAux::used_bytes();
  1292   verify_region_sets_optional();
  1294   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
  1295                            collector_policy()->should_clear_all_soft_refs();
  1297   ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
  1300     IsGCActiveMark x;
  1302     // Timing
  1303     assert(gc_cause() != GCCause::_java_lang_system_gc || explicit_gc, "invariant");
  1304     gclog_or_tty->date_stamp(G1Log::fine() && PrintGCDateStamps);
  1305     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
  1308       GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL, gc_tracer->gc_id());
  1309       TraceCollectorStats tcs(g1mm()->full_collection_counters());
  1310       TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
  1312       double start = os::elapsedTime();
  1313       g1_policy()->record_full_collection_start();
  1315       // Note: When we have a more flexible GC logging framework that
  1316       // allows us to add optional attributes to a GC log record we
  1317       // could consider timing and reporting how long we wait in the
  1318       // following two methods.
  1319       wait_while_free_regions_coming();
  1320       // If we start the compaction before the CM threads finish
  1321       // scanning the root regions we might trip them over as we'll
  1322       // be moving objects / updating references. So let's wait until
  1323       // they are done. By telling them to abort, they should complete
  1324       // early.
  1325       _cm->root_regions()->abort();
  1326       _cm->root_regions()->wait_until_scan_finished();
  1327       append_secondary_free_list_if_not_empty_with_lock();
  1329       gc_prologue(true);
  1330       increment_total_collections(true /* full gc */);
  1331       increment_old_marking_cycles_started();
  1333       assert(used() == recalculate_used(), "Should be equal");
  1335       verify_before_gc();
  1337       pre_full_gc_dump(gc_timer);
  1339       COMPILER2_PRESENT(DerivedPointerTable::clear());
  1341       // Disable discovery and empty the discovered lists
  1342       // for the CM ref processor.
  1343       ref_processor_cm()->disable_discovery();
  1344       ref_processor_cm()->abandon_partial_discovery();
  1345       ref_processor_cm()->verify_no_references_recorded();
  1347       // Abandon current iterations of concurrent marking and concurrent
  1348       // refinement, if any are in progress. We have to do this before
  1349       // wait_until_scan_finished() below.
  1350       concurrent_mark()->abort();
  1352       // Make sure we'll choose a new allocation region afterwards.
  1353       release_mutator_alloc_region();
  1354       abandon_gc_alloc_regions();
  1355       g1_rem_set()->cleanupHRRS();
  1357       // We should call this after we retire any currently active alloc
  1358       // regions so that all the ALLOC / RETIRE events are generated
  1359       // before the start GC event.
  1360       _hr_printer.start_gc(true /* full */, (size_t) total_collections());
  1362       // We may have added regions to the current incremental collection
  1363       // set between the last GC or pause and now. We need to clear the
  1364       // incremental collection set and then start rebuilding it afresh
  1365       // after this full GC.
  1366       abandon_collection_set(g1_policy()->inc_cset_head());
  1367       g1_policy()->clear_incremental_cset();
  1368       g1_policy()->stop_incremental_cset_building();
  1370       tear_down_region_sets(false /* free_list_only */);
  1371       g1_policy()->set_gcs_are_young(true);
  1373       // See the comments in g1CollectedHeap.hpp and
  1374       // G1CollectedHeap::ref_processing_init() about
  1375       // how reference processing currently works in G1.
  1377       // Temporarily make discovery by the STW ref processor single threaded (non-MT).
  1378       ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);
  1380       // Temporarily clear the STW ref processor's _is_alive_non_header field.
  1381       ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);
  1383       ref_processor_stw()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
  1384       ref_processor_stw()->setup_policy(do_clear_all_soft_refs);
  1386       // Do collection work
  1388         HandleMark hm;  // Discard invalid handles created during gc
  1389         G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);
  1392       assert(free_regions() == 0, "we should not have added any free regions");
  1393       rebuild_region_sets(false /* free_list_only */);
  1395       // Enqueue any discovered reference objects that have
  1396       // not been removed from the discovered lists.
  1397       ref_processor_stw()->enqueue_discovered_references();
  1399       COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
  1401       MemoryService::track_memory_usage();
  1403       assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
  1404       ref_processor_stw()->verify_no_references_recorded();
  1406       // Delete metaspaces for unloaded class loaders and clean up loader_data graph
  1407       ClassLoaderDataGraph::purge();
  1408       MetaspaceAux::verify_metrics();
  1410       // Note: since we've just done a full GC, concurrent
  1411       // marking is no longer active. Therefore we need not
  1412       // re-enable reference discovery for the CM ref processor.
  1413       // That will be done at the start of the next marking cycle.
  1414       assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");
  1415       ref_processor_cm()->verify_no_references_recorded();
  1417       reset_gc_time_stamp();
  1418       // Since everything potentially moved, we will clear all remembered
  1419       // sets, and clear all cards.  Later we will rebuild remembered
  1420       // sets. We will also reset the GC time stamps of the regions.
  1421       clear_rsets_post_compaction();
  1422       check_gc_time_stamps();
  1424       // Resize the heap if necessary.
  1425       resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
  1427       if (_hr_printer.is_active()) {
  1428         // We should do this after we potentially resize the heap so
  1429         // that all the COMMIT / UNCOMMIT events are generated before
  1430         // the end GC event.
  1432         print_hrs_post_compaction();
  1433         _hr_printer.end_gc(true /* full */, (size_t) total_collections());
  1436       G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
  1437       if (hot_card_cache->use_cache()) {
  1438         hot_card_cache->reset_card_counts();
  1439         hot_card_cache->reset_hot_cache();
  1442       // Rebuild remembered sets of all regions.
  1443       if (G1CollectedHeap::use_parallel_gc_threads()) {
  1444         uint n_workers =
  1445           AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
  1446                                                   workers()->active_workers(),
  1447                                                   Threads::number_of_non_daemon_threads());
  1448         assert(UseDynamicNumberOfGCThreads ||
  1449                n_workers == workers()->total_workers(),
  1450                "If not dynamic should be using all the  workers");
  1451         workers()->set_active_workers(n_workers);
  1452         // Set parallel threads in the heap (_n_par_threads) only
  1453         // before a parallel phase and always reset it to 0 after
  1454         // the phase so that the number of parallel threads does
  1455         // no get carried forward to a serial phase where there
  1456         // may be code that is "possibly_parallel".
  1457         set_par_threads(n_workers);
  1459         ParRebuildRSTask rebuild_rs_task(this);
  1460         assert(check_heap_region_claim_values(
  1461                HeapRegion::InitialClaimValue), "sanity check");
  1462         assert(UseDynamicNumberOfGCThreads ||
  1463                workers()->active_workers() == workers()->total_workers(),
  1464                "Unless dynamic should use total workers");
  1465         // Use the most recent number of  active workers
  1466         assert(workers()->active_workers() > 0,
  1467                "Active workers not properly set");
  1468         set_par_threads(workers()->active_workers());
  1469         workers()->run_task(&rebuild_rs_task);
  1470         set_par_threads(0);
  1471         assert(check_heap_region_claim_values(
  1472                HeapRegion::RebuildRSClaimValue), "sanity check");
  1473         reset_heap_region_claim_values();
  1474       } else {
  1475         RebuildRSOutOfRegionClosure rebuild_rs(this);
  1476         heap_region_iterate(&rebuild_rs);
  1479       // Rebuild the strong code root lists for each region
  1480       rebuild_strong_code_roots();
  1482       if (true) { // FIXME
  1483         MetaspaceGC::compute_new_size();
  1486 #ifdef TRACESPINNING
  1487       ParallelTaskTerminator::print_termination_counts();
  1488 #endif
  1490       // Discard all rset updates
  1491       JavaThread::dirty_card_queue_set().abandon_logs();
  1492       assert(!G1DeferredRSUpdate
  1493              || (G1DeferredRSUpdate &&
  1494                 (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
  1496       _young_list->reset_sampled_info();
  1497       // At this point there should be no regions in the
  1498       // entire heap tagged as young.
  1499       assert(check_young_list_empty(true /* check_heap */),
  1500              "young list should be empty at this point");
  1502       // Update the number of full collections that have been completed.
  1503       increment_old_marking_cycles_completed(false /* concurrent */);
  1505       _hrs.verify_optional();
  1506       verify_region_sets_optional();
  1508       verify_after_gc();
  1510       // Start a new incremental collection set for the next pause
  1511       assert(g1_policy()->collection_set() == NULL, "must be");
  1512       g1_policy()->start_incremental_cset_building();
  1514       // Clear the _cset_fast_test bitmap in anticipation of adding
  1515       // regions to the incremental collection set for the next
  1516       // evacuation pause.
  1517       clear_cset_fast_test();
  1519       init_mutator_alloc_region();
  1521       double end = os::elapsedTime();
  1522       g1_policy()->record_full_collection_end();
  1524       if (G1Log::fine()) {
  1525         g1_policy()->print_heap_transition();
  1528       // We must call G1MonitoringSupport::update_sizes() in the same scoping level
  1529       // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
  1530       // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
  1531       // before any GC notifications are raised.
  1532       g1mm()->update_sizes();
  1534       gc_epilogue(true);
  1537     if (G1Log::finer()) {
  1538       g1_policy()->print_detailed_heap_transition(true /* full */);
  1541     print_heap_after_gc();
  1542     trace_heap_after_gc(gc_tracer);
  1544     post_full_gc_dump(gc_timer);
  1546     gc_timer->register_gc_end();
  1547     gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
  1550   return true;
  1553 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
  1554   // do_collection() will return whether it succeeded in performing
  1555   // the GC. Currently, there is no facility on the
  1556   // do_full_collection() API to notify the caller than the collection
  1557   // did not succeed (e.g., because it was locked out by the GC
  1558   // locker). So, right now, we'll ignore the return value.
  1559   bool dummy = do_collection(true,                /* explicit_gc */
  1560                              clear_all_soft_refs,
  1561                              0                    /* word_size */);
  1564 // This code is mostly copied from TenuredGeneration.
  1565 void
  1566 G1CollectedHeap::
  1567 resize_if_necessary_after_full_collection(size_t word_size) {
  1568   // Include the current allocation, if any, and bytes that will be
  1569   // pre-allocated to support collections, as "used".
  1570   const size_t used_after_gc = used();
  1571   const size_t capacity_after_gc = capacity();
  1572   const size_t free_after_gc = capacity_after_gc - used_after_gc;
  1574   // This is enforced in arguments.cpp.
  1575   assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
  1576          "otherwise the code below doesn't make sense");
  1578   // We don't have floating point command-line arguments
  1579   const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
  1580   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1581   const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
  1582   const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1584   const size_t min_heap_size = collector_policy()->min_heap_byte_size();
  1585   const size_t max_heap_size = collector_policy()->max_heap_byte_size();
  1587   // We have to be careful here as these two calculations can overflow
  1588   // 32-bit size_t's.
  1589   double used_after_gc_d = (double) used_after_gc;
  1590   double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
  1591   double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
  1593   // Let's make sure that they are both under the max heap size, which
  1594   // by default will make them fit into a size_t.
  1595   double desired_capacity_upper_bound = (double) max_heap_size;
  1596   minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
  1597                                     desired_capacity_upper_bound);
  1598   maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
  1599                                     desired_capacity_upper_bound);
  1601   // We can now safely turn them into size_t's.
  1602   size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
  1603   size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
  1605   // This assert only makes sense here, before we adjust them
  1606   // with respect to the min and max heap size.
  1607   assert(minimum_desired_capacity <= maximum_desired_capacity,
  1608          err_msg("minimum_desired_capacity = "SIZE_FORMAT", "
  1609                  "maximum_desired_capacity = "SIZE_FORMAT,
  1610                  minimum_desired_capacity, maximum_desired_capacity));
  1612   // Should not be greater than the heap max size. No need to adjust
  1613   // it with respect to the heap min size as it's a lower bound (i.e.,
  1614   // we'll try to make the capacity larger than it, not smaller).
  1615   minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);
  1616   // Should not be less than the heap min size. No need to adjust it
  1617   // with respect to the heap max size as it's an upper bound (i.e.,
  1618   // we'll try to make the capacity smaller than it, not greater).
  1619   maximum_desired_capacity =  MAX2(maximum_desired_capacity, min_heap_size);
  1621   if (capacity_after_gc < minimum_desired_capacity) {
  1622     // Don't expand unless it's significant
  1623     size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
  1624     ergo_verbose4(ErgoHeapSizing,
  1625                   "attempt heap expansion",
  1626                   ergo_format_reason("capacity lower than "
  1627                                      "min desired capacity after Full GC")
  1628                   ergo_format_byte("capacity")
  1629                   ergo_format_byte("occupancy")
  1630                   ergo_format_byte_perc("min desired capacity"),
  1631                   capacity_after_gc, used_after_gc,
  1632                   minimum_desired_capacity, (double) MinHeapFreeRatio);
  1633     expand(expand_bytes);
  1635     // No expansion, now see if we want to shrink
  1636   } else if (capacity_after_gc > maximum_desired_capacity) {
  1637     // Capacity too large, compute shrinking size
  1638     size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
  1639     ergo_verbose4(ErgoHeapSizing,
  1640                   "attempt heap shrinking",
  1641                   ergo_format_reason("capacity higher than "
  1642                                      "max desired capacity after Full GC")
  1643                   ergo_format_byte("capacity")
  1644                   ergo_format_byte("occupancy")
  1645                   ergo_format_byte_perc("max desired capacity"),
  1646                   capacity_after_gc, used_after_gc,
  1647                   maximum_desired_capacity, (double) MaxHeapFreeRatio);
  1648     shrink(shrink_bytes);
  1653 HeapWord*
  1654 G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
  1655                                            bool* succeeded) {
  1656   assert_at_safepoint(true /* should_be_vm_thread */);
  1658   *succeeded = true;
  1659   // Let's attempt the allocation first.
  1660   HeapWord* result =
  1661     attempt_allocation_at_safepoint(word_size,
  1662                                  false /* expect_null_mutator_alloc_region */);
  1663   if (result != NULL) {
  1664     assert(*succeeded, "sanity");
  1665     return result;
  1668   // In a G1 heap, we're supposed to keep allocation from failing by
  1669   // incremental pauses.  Therefore, at least for now, we'll favor
  1670   // expansion over collection.  (This might change in the future if we can
  1671   // do something smarter than full collection to satisfy a failed alloc.)
  1672   result = expand_and_allocate(word_size);
  1673   if (result != NULL) {
  1674     assert(*succeeded, "sanity");
  1675     return result;
  1678   // Expansion didn't work, we'll try to do a Full GC.
  1679   bool gc_succeeded = do_collection(false, /* explicit_gc */
  1680                                     false, /* clear_all_soft_refs */
  1681                                     word_size);
  1682   if (!gc_succeeded) {
  1683     *succeeded = false;
  1684     return NULL;
  1687   // Retry the allocation
  1688   result = attempt_allocation_at_safepoint(word_size,
  1689                                   true /* expect_null_mutator_alloc_region */);
  1690   if (result != NULL) {
  1691     assert(*succeeded, "sanity");
  1692     return result;
  1695   // Then, try a Full GC that will collect all soft references.
  1696   gc_succeeded = do_collection(false, /* explicit_gc */
  1697                                true,  /* clear_all_soft_refs */
  1698                                word_size);
  1699   if (!gc_succeeded) {
  1700     *succeeded = false;
  1701     return NULL;
  1704   // Retry the allocation once more
  1705   result = attempt_allocation_at_safepoint(word_size,
  1706                                   true /* expect_null_mutator_alloc_region */);
  1707   if (result != NULL) {
  1708     assert(*succeeded, "sanity");
  1709     return result;
  1712   assert(!collector_policy()->should_clear_all_soft_refs(),
  1713          "Flag should have been handled and cleared prior to this point");
  1715   // What else?  We might try synchronous finalization later.  If the total
  1716   // space available is large enough for the allocation, then a more
  1717   // complete compaction phase than we've tried so far might be
  1718   // appropriate.
  1719   assert(*succeeded, "sanity");
  1720   return NULL;
  1723 // Attempting to expand the heap sufficiently
  1724 // to support an allocation of the given "word_size".  If
  1725 // successful, perform the allocation and return the address of the
  1726 // allocated block, or else "NULL".
  1728 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
  1729   assert_at_safepoint(true /* should_be_vm_thread */);
  1731   verify_region_sets_optional();
  1733   size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
  1734   ergo_verbose1(ErgoHeapSizing,
  1735                 "attempt heap expansion",
  1736                 ergo_format_reason("allocation request failed")
  1737                 ergo_format_byte("allocation request"),
  1738                 word_size * HeapWordSize);
  1739   if (expand(expand_bytes)) {
  1740     _hrs.verify_optional();
  1741     verify_region_sets_optional();
  1742     return attempt_allocation_at_safepoint(word_size,
  1743                                  false /* expect_null_mutator_alloc_region */);
  1745   return NULL;
  1748 void G1CollectedHeap::update_committed_space(HeapWord* old_end,
  1749                                              HeapWord* new_end) {
  1750   assert(old_end != new_end, "don't call this otherwise");
  1751   assert((HeapWord*) _g1_storage.high() == new_end, "invariant");
  1753   // Update the committed mem region.
  1754   _g1_committed.set_end(new_end);
  1755   // Tell the card table about the update.
  1756   Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
  1757   // Tell the BOT about the update.
  1758   _bot_shared->resize(_g1_committed.word_size());
  1759   // Tell the hot card cache about the update
  1760   _cg1r->hot_card_cache()->resize_card_counts(capacity());
  1763 bool G1CollectedHeap::expand(size_t expand_bytes) {
  1764   size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
  1765   aligned_expand_bytes = align_size_up(aligned_expand_bytes,
  1766                                        HeapRegion::GrainBytes);
  1767   ergo_verbose2(ErgoHeapSizing,
  1768                 "expand the heap",
  1769                 ergo_format_byte("requested expansion amount")
  1770                 ergo_format_byte("attempted expansion amount"),
  1771                 expand_bytes, aligned_expand_bytes);
  1773   if (_g1_storage.uncommitted_size() == 0) {
  1774     ergo_verbose0(ErgoHeapSizing,
  1775                       "did not expand the heap",
  1776                       ergo_format_reason("heap already fully expanded"));
  1777     return false;
  1780   // First commit the memory.
  1781   HeapWord* old_end = (HeapWord*) _g1_storage.high();
  1782   bool successful = _g1_storage.expand_by(aligned_expand_bytes);
  1783   if (successful) {
  1784     // Then propagate this update to the necessary data structures.
  1785     HeapWord* new_end = (HeapWord*) _g1_storage.high();
  1786     update_committed_space(old_end, new_end);
  1788     FreeRegionList expansion_list("Local Expansion List");
  1789     MemRegion mr = _hrs.expand_by(old_end, new_end, &expansion_list);
  1790     assert(mr.start() == old_end, "post-condition");
  1791     // mr might be a smaller region than what was requested if
  1792     // expand_by() was unable to allocate the HeapRegion instances
  1793     assert(mr.end() <= new_end, "post-condition");
  1795     size_t actual_expand_bytes = mr.byte_size();
  1796     assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
  1797     assert(actual_expand_bytes == expansion_list.total_capacity_bytes(),
  1798            "post-condition");
  1799     if (actual_expand_bytes < aligned_expand_bytes) {
  1800       // We could not expand _hrs to the desired size. In this case we
  1801       // need to shrink the committed space accordingly.
  1802       assert(mr.end() < new_end, "invariant");
  1804       size_t diff_bytes = aligned_expand_bytes - actual_expand_bytes;
  1805       // First uncommit the memory.
  1806       _g1_storage.shrink_by(diff_bytes);
  1807       // Then propagate this update to the necessary data structures.
  1808       update_committed_space(new_end, mr.end());
  1810     _free_list.add_as_tail(&expansion_list);
  1812     if (_hr_printer.is_active()) {
  1813       HeapWord* curr = mr.start();
  1814       while (curr < mr.end()) {
  1815         HeapWord* curr_end = curr + HeapRegion::GrainWords;
  1816         _hr_printer.commit(curr, curr_end);
  1817         curr = curr_end;
  1819       assert(curr == mr.end(), "post-condition");
  1821     g1_policy()->record_new_heap_size(n_regions());
  1822   } else {
  1823     ergo_verbose0(ErgoHeapSizing,
  1824                   "did not expand the heap",
  1825                   ergo_format_reason("heap expansion operation failed"));
  1826     // The expansion of the virtual storage space was unsuccessful.
  1827     // Let's see if it was because we ran out of swap.
  1828     if (G1ExitOnExpansionFailure &&
  1829         _g1_storage.uncommitted_size() >= aligned_expand_bytes) {
  1830       // We had head room...
  1831       vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
  1834   return successful;
  1837 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
  1838   size_t aligned_shrink_bytes =
  1839     ReservedSpace::page_align_size_down(shrink_bytes);
  1840   aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
  1841                                          HeapRegion::GrainBytes);
  1842   uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
  1844   uint num_regions_removed = _hrs.shrink_by(num_regions_to_remove);
  1845   HeapWord* old_end = (HeapWord*) _g1_storage.high();
  1846   size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
  1848   ergo_verbose3(ErgoHeapSizing,
  1849                 "shrink the heap",
  1850                 ergo_format_byte("requested shrinking amount")
  1851                 ergo_format_byte("aligned shrinking amount")
  1852                 ergo_format_byte("attempted shrinking amount"),
  1853                 shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
  1854   if (num_regions_removed > 0) {
  1855     _g1_storage.shrink_by(shrunk_bytes);
  1856     HeapWord* new_end = (HeapWord*) _g1_storage.high();
  1858     if (_hr_printer.is_active()) {
  1859       HeapWord* curr = old_end;
  1860       while (curr > new_end) {
  1861         HeapWord* curr_end = curr;
  1862         curr -= HeapRegion::GrainWords;
  1863         _hr_printer.uncommit(curr, curr_end);
  1867     _expansion_regions += num_regions_removed;
  1868     update_committed_space(old_end, new_end);
  1869     HeapRegionRemSet::shrink_heap(n_regions());
  1870     g1_policy()->record_new_heap_size(n_regions());
  1871   } else {
  1872     ergo_verbose0(ErgoHeapSizing,
  1873                   "did not shrink the heap",
  1874                   ergo_format_reason("heap shrinking operation failed"));
  1878 void G1CollectedHeap::shrink(size_t shrink_bytes) {
  1879   verify_region_sets_optional();
  1881   // We should only reach here at the end of a Full GC which means we
  1882   // should not not be holding to any GC alloc regions. The method
  1883   // below will make sure of that and do any remaining clean up.
  1884   abandon_gc_alloc_regions();
  1886   // Instead of tearing down / rebuilding the free lists here, we
  1887   // could instead use the remove_all_pending() method on free_list to
  1888   // remove only the ones that we need to remove.
  1889   tear_down_region_sets(true /* free_list_only */);
  1890   shrink_helper(shrink_bytes);
  1891   rebuild_region_sets(true /* free_list_only */);
  1893   _hrs.verify_optional();
  1894   verify_region_sets_optional();
  1897 // Public methods.
  1899 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
  1900 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
  1901 #endif // _MSC_VER
  1904 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
  1905   SharedHeap(policy_),
  1906   _g1_policy(policy_),
  1907   _dirty_card_queue_set(false),
  1908   _into_cset_dirty_card_queue_set(false),
  1909   _is_alive_closure_cm(this),
  1910   _is_alive_closure_stw(this),
  1911   _ref_processor_cm(NULL),
  1912   _ref_processor_stw(NULL),
  1913   _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
  1914   _bot_shared(NULL),
  1915   _evac_failure_scan_stack(NULL),
  1916   _mark_in_progress(false),
  1917   _cg1r(NULL), _summary_bytes_used(0),
  1918   _g1mm(NULL),
  1919   _refine_cte_cl(NULL),
  1920   _full_collection(false),
  1921   _free_list("Master Free List", new MasterFreeRegionListMtSafeChecker()),
  1922   _secondary_free_list("Secondary Free List", new SecondaryFreeRegionListMtSafeChecker()),
  1923   _old_set("Old Set", false /* humongous */, new OldRegionSetMtSafeChecker()),
  1924   _humongous_set("Master Humongous Set", true /* humongous */, new HumongousRegionSetMtSafeChecker()),
  1925   _free_regions_coming(false),
  1926   _young_list(new YoungList(this)),
  1927   _gc_time_stamp(0),
  1928   _retained_old_gc_alloc_region(NULL),
  1929   _survivor_plab_stats(YoungPLABSize, PLABWeight),
  1930   _old_plab_stats(OldPLABSize, PLABWeight),
  1931   _expand_heap_after_alloc_failure(true),
  1932   _surviving_young_words(NULL),
  1933   _old_marking_cycles_started(0),
  1934   _old_marking_cycles_completed(0),
  1935   _concurrent_cycle_started(false),
  1936   _in_cset_fast_test(NULL),
  1937   _in_cset_fast_test_base(NULL),
  1938   _dirty_cards_region_list(NULL),
  1939   _worker_cset_start_region(NULL),
  1940   _worker_cset_start_region_time_stamp(NULL),
  1941   _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
  1942   _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
  1943   _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
  1944   _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()) {
  1946   _g1h = this;
  1947   if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
  1948     vm_exit_during_initialization("Failed necessary allocation.");
  1951   _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2;
  1953   int n_queues = MAX2((int)ParallelGCThreads, 1);
  1954   _task_queues = new RefToScanQueueSet(n_queues);
  1956   uint n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
  1957   assert(n_rem_sets > 0, "Invariant.");
  1959   _worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC);
  1960   _worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(unsigned int, n_queues, mtGC);
  1961   _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
  1963   for (int i = 0; i < n_queues; i++) {
  1964     RefToScanQueue* q = new RefToScanQueue();
  1965     q->initialize();
  1966     _task_queues->register_queue(i, q);
  1967     ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
  1969   clear_cset_start_regions();
  1971   // Initialize the G1EvacuationFailureALot counters and flags.
  1972   NOT_PRODUCT(reset_evacuation_should_fail();)
  1974   guarantee(_task_queues != NULL, "task_queues allocation failure.");
  1977 jint G1CollectedHeap::initialize() {
  1978   CollectedHeap::pre_initialize();
  1979   os::enable_vtime();
  1981   G1Log::init();
  1983   // Necessary to satisfy locking discipline assertions.
  1985   MutexLocker x(Heap_lock);
  1987   // We have to initialize the printer before committing the heap, as
  1988   // it will be used then.
  1989   _hr_printer.set_active(G1PrintHeapRegions);
  1991   // While there are no constraints in the GC code that HeapWordSize
  1992   // be any particular value, there are multiple other areas in the
  1993   // system which believe this to be true (e.g. oop->object_size in some
  1994   // cases incorrectly returns the size in wordSize units rather than
  1995   // HeapWordSize).
  1996   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
  1998   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
  1999   size_t max_byte_size = collector_policy()->max_heap_byte_size();
  2000   size_t heap_alignment = collector_policy()->heap_alignment();
  2002   // Ensure that the sizes are properly aligned.
  2003   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
  2004   Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
  2005   Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap");
  2007   _cg1r = new ConcurrentG1Refine(this);
  2009   // Reserve the maximum.
  2011   // When compressed oops are enabled, the preferred heap base
  2012   // is calculated by subtracting the requested size from the
  2013   // 32Gb boundary and using the result as the base address for
  2014   // heap reservation. If the requested size is not aligned to
  2015   // HeapRegion::GrainBytes (i.e. the alignment that is passed
  2016   // into the ReservedHeapSpace constructor) then the actual
  2017   // base of the reserved heap may end up differing from the
  2018   // address that was requested (i.e. the preferred heap base).
  2019   // If this happens then we could end up using a non-optimal
  2020   // compressed oops mode.
  2022   ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size,
  2023                                                  heap_alignment);
  2025   // It is important to do this in a way such that concurrent readers can't
  2026   // temporarily think something is in the heap.  (I've actually seen this
  2027   // happen in asserts: DLD.)
  2028   _reserved.set_word_size(0);
  2029   _reserved.set_start((HeapWord*)heap_rs.base());
  2030   _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
  2032   _expansion_regions = (uint) (max_byte_size / HeapRegion::GrainBytes);
  2034   // Create the gen rem set (and barrier set) for the entire reserved region.
  2035   _rem_set = collector_policy()->create_rem_set(_reserved, 2);
  2036   set_barrier_set(rem_set()->bs());
  2037   if (!barrier_set()->is_a(BarrierSet::G1SATBCTLogging)) {
  2038     vm_exit_during_initialization("G1 requires a G1SATBLoggingCardTableModRefBS");
  2039     return JNI_ENOMEM;
  2042   // Also create a G1 rem set.
  2043   _g1_rem_set = new G1RemSet(this, g1_barrier_set());
  2045   // Carve out the G1 part of the heap.
  2047   ReservedSpace g1_rs   = heap_rs.first_part(max_byte_size);
  2048   _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
  2049                            g1_rs.size()/HeapWordSize);
  2051   _g1_storage.initialize(g1_rs, 0);
  2052   _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
  2053   _hrs.initialize((HeapWord*) _g1_reserved.start(),
  2054                   (HeapWord*) _g1_reserved.end());
  2055   assert(_hrs.max_length() == _expansion_regions,
  2056          err_msg("max length: %u expansion regions: %u",
  2057                  _hrs.max_length(), _expansion_regions));
  2059   // Do later initialization work for concurrent refinement.
  2060   _cg1r->init();
  2062   // 6843694 - ensure that the maximum region index can fit
  2063   // in the remembered set structures.
  2064   const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
  2065   guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
  2067   size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
  2068   guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
  2069   guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
  2070             "too many cards per region");
  2072   FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
  2074   _bot_shared = new G1BlockOffsetSharedArray(_reserved,
  2075                                              heap_word_size(init_byte_size));
  2077   _g1h = this;
  2079   _in_cset_fast_test_length = max_regions();
  2080   _in_cset_fast_test_base =
  2081                    NEW_C_HEAP_ARRAY(bool, (size_t) _in_cset_fast_test_length, mtGC);
  2083   // We're biasing _in_cset_fast_test to avoid subtracting the
  2084   // beginning of the heap every time we want to index; basically
  2085   // it's the same with what we do with the card table.
  2086   _in_cset_fast_test = _in_cset_fast_test_base -
  2087                ((uintx) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
  2089   // Clear the _cset_fast_test bitmap in anticipation of adding
  2090   // regions to the incremental collection set for the first
  2091   // evacuation pause.
  2092   clear_cset_fast_test();
  2094   // Create the ConcurrentMark data structure and thread.
  2095   // (Must do this late, so that "max_regions" is defined.)
  2096   _cm = new ConcurrentMark(this, heap_rs);
  2097   if (_cm == NULL || !_cm->completed_initialization()) {
  2098     vm_shutdown_during_initialization("Could not create/initialize ConcurrentMark");
  2099     return JNI_ENOMEM;
  2101   _cmThread = _cm->cmThread();
  2103   // Initialize the from_card cache structure of HeapRegionRemSet.
  2104   HeapRegionRemSet::init_heap(max_regions());
  2106   // Now expand into the initial heap size.
  2107   if (!expand(init_byte_size)) {
  2108     vm_shutdown_during_initialization("Failed to allocate initial heap.");
  2109     return JNI_ENOMEM;
  2112   // Perform any initialization actions delegated to the policy.
  2113   g1_policy()->init();
  2115   _refine_cte_cl =
  2116     new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
  2117                                     g1_rem_set(),
  2118                                     concurrent_g1_refine());
  2119   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
  2121   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
  2122                                                SATB_Q_FL_lock,
  2123                                                G1SATBProcessCompletedThreshold,
  2124                                                Shared_SATB_Q_lock);
  2126   JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
  2127                                                 DirtyCardQ_FL_lock,
  2128                                                 concurrent_g1_refine()->yellow_zone(),
  2129                                                 concurrent_g1_refine()->red_zone(),
  2130                                                 Shared_DirtyCardQ_lock);
  2132   if (G1DeferredRSUpdate) {
  2133     dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
  2134                                       DirtyCardQ_FL_lock,
  2135                                       -1, // never trigger processing
  2136                                       -1, // no limit on length
  2137                                       Shared_DirtyCardQ_lock,
  2138                                       &JavaThread::dirty_card_queue_set());
  2141   // Initialize the card queue set used to hold cards containing
  2142   // references into the collection set.
  2143   _into_cset_dirty_card_queue_set.initialize(DirtyCardQ_CBL_mon,
  2144                                              DirtyCardQ_FL_lock,
  2145                                              -1, // never trigger processing
  2146                                              -1, // no limit on length
  2147                                              Shared_DirtyCardQ_lock,
  2148                                              &JavaThread::dirty_card_queue_set());
  2150   // In case we're keeping closure specialization stats, initialize those
  2151   // counts and that mechanism.
  2152   SpecializationStats::clear();
  2154   // Here we allocate the dummy full region that is required by the
  2155   // G1AllocRegion class. If we don't pass an address in the reserved
  2156   // space here, lots of asserts fire.
  2158   HeapRegion* dummy_region = new_heap_region(0 /* index of bottom region */,
  2159                                              _g1_reserved.start());
  2160   // We'll re-use the same region whether the alloc region will
  2161   // require BOT updates or not and, if it doesn't, then a non-young
  2162   // region will complain that it cannot support allocations without
  2163   // BOT updates. So we'll tag the dummy region as young to avoid that.
  2164   dummy_region->set_young();
  2165   // Make sure it's full.
  2166   dummy_region->set_top(dummy_region->end());
  2167   G1AllocRegion::setup(this, dummy_region);
  2169   init_mutator_alloc_region();
  2171   // Do create of the monitoring and management support so that
  2172   // values in the heap have been properly initialized.
  2173   _g1mm = new G1MonitoringSupport(this);
  2175   G1StringDedup::initialize();
  2177   return JNI_OK;
  2180 void G1CollectedHeap::stop() {
  2181   // Stop all concurrent threads. We do this to make sure these threads
  2182   // do not continue to execute and access resources (e.g. gclog_or_tty)
  2183   // that are destroyed during shutdown.
  2184   _cg1r->stop();
  2185   _cmThread->stop();
  2186   if (G1StringDedup::is_enabled()) {
  2187     G1StringDedup::stop();
  2191 size_t G1CollectedHeap::conservative_max_heap_alignment() {
  2192   return HeapRegion::max_region_size();
  2195 void G1CollectedHeap::ref_processing_init() {
  2196   // Reference processing in G1 currently works as follows:
  2197   //
  2198   // * There are two reference processor instances. One is
  2199   //   used to record and process discovered references
  2200   //   during concurrent marking; the other is used to
  2201   //   record and process references during STW pauses
  2202   //   (both full and incremental).
  2203   // * Both ref processors need to 'span' the entire heap as
  2204   //   the regions in the collection set may be dotted around.
  2205   //
  2206   // * For the concurrent marking ref processor:
  2207   //   * Reference discovery is enabled at initial marking.
  2208   //   * Reference discovery is disabled and the discovered
  2209   //     references processed etc during remarking.
  2210   //   * Reference discovery is MT (see below).
  2211   //   * Reference discovery requires a barrier (see below).
  2212   //   * Reference processing may or may not be MT
  2213   //     (depending on the value of ParallelRefProcEnabled
  2214   //     and ParallelGCThreads).
  2215   //   * A full GC disables reference discovery by the CM
  2216   //     ref processor and abandons any entries on it's
  2217   //     discovered lists.
  2218   //
  2219   // * For the STW processor:
  2220   //   * Non MT discovery is enabled at the start of a full GC.
  2221   //   * Processing and enqueueing during a full GC is non-MT.
  2222   //   * During a full GC, references are processed after marking.
  2223   //
  2224   //   * Discovery (may or may not be MT) is enabled at the start
  2225   //     of an incremental evacuation pause.
  2226   //   * References are processed near the end of a STW evacuation pause.
  2227   //   * For both types of GC:
  2228   //     * Discovery is atomic - i.e. not concurrent.
  2229   //     * Reference discovery will not need a barrier.
  2231   SharedHeap::ref_processing_init();
  2232   MemRegion mr = reserved_region();
  2234   // Concurrent Mark ref processor
  2235   _ref_processor_cm =
  2236     new ReferenceProcessor(mr,    // span
  2237                            ParallelRefProcEnabled && (ParallelGCThreads > 1),
  2238                                 // mt processing
  2239                            (int) ParallelGCThreads,
  2240                                 // degree of mt processing
  2241                            (ParallelGCThreads > 1) || (ConcGCThreads > 1),
  2242                                 // mt discovery
  2243                            (int) MAX2(ParallelGCThreads, ConcGCThreads),
  2244                                 // degree of mt discovery
  2245                            false,
  2246                                 // Reference discovery is not atomic
  2247                            &_is_alive_closure_cm);
  2248                                 // is alive closure
  2249                                 // (for efficiency/performance)
  2251   // STW ref processor
  2252   _ref_processor_stw =
  2253     new ReferenceProcessor(mr,    // span
  2254                            ParallelRefProcEnabled && (ParallelGCThreads > 1),
  2255                                 // mt processing
  2256                            MAX2((int)ParallelGCThreads, 1),
  2257                                 // degree of mt processing
  2258                            (ParallelGCThreads > 1),
  2259                                 // mt discovery
  2260                            MAX2((int)ParallelGCThreads, 1),
  2261                                 // degree of mt discovery
  2262                            true,
  2263                                 // Reference discovery is atomic
  2264                            &_is_alive_closure_stw);
  2265                                 // is alive closure
  2266                                 // (for efficiency/performance)
  2269 size_t G1CollectedHeap::capacity() const {
  2270   return _g1_committed.byte_size();
  2273 void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) {
  2274   assert(!hr->continuesHumongous(), "pre-condition");
  2275   hr->reset_gc_time_stamp();
  2276   if (hr->startsHumongous()) {
  2277     uint first_index = hr->hrs_index() + 1;
  2278     uint last_index = hr->last_hc_index();
  2279     for (uint i = first_index; i < last_index; i += 1) {
  2280       HeapRegion* chr = region_at(i);
  2281       assert(chr->continuesHumongous(), "sanity");
  2282       chr->reset_gc_time_stamp();
  2287 #ifndef PRODUCT
  2288 class CheckGCTimeStampsHRClosure : public HeapRegionClosure {
  2289 private:
  2290   unsigned _gc_time_stamp;
  2291   bool _failures;
  2293 public:
  2294   CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) :
  2295     _gc_time_stamp(gc_time_stamp), _failures(false) { }
  2297   virtual bool doHeapRegion(HeapRegion* hr) {
  2298     unsigned region_gc_time_stamp = hr->get_gc_time_stamp();
  2299     if (_gc_time_stamp != region_gc_time_stamp) {
  2300       gclog_or_tty->print_cr("Region "HR_FORMAT" has GC time stamp = %d, "
  2301                              "expected %d", HR_FORMAT_PARAMS(hr),
  2302                              region_gc_time_stamp, _gc_time_stamp);
  2303       _failures = true;
  2305     return false;
  2308   bool failures() { return _failures; }
  2309 };
  2311 void G1CollectedHeap::check_gc_time_stamps() {
  2312   CheckGCTimeStampsHRClosure cl(_gc_time_stamp);
  2313   heap_region_iterate(&cl);
  2314   guarantee(!cl.failures(), "all GC time stamps should have been reset");
  2316 #endif // PRODUCT
  2318 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,
  2319                                                  DirtyCardQueue* into_cset_dcq,
  2320                                                  bool concurrent,
  2321                                                  uint worker_i) {
  2322   // Clean cards in the hot card cache
  2323   G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
  2324   hot_card_cache->drain(worker_i, g1_rem_set(), into_cset_dcq);
  2326   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
  2327   int n_completed_buffers = 0;
  2328   while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {
  2329     n_completed_buffers++;
  2331   g1_policy()->phase_times()->record_update_rs_processed_buffers(worker_i, n_completed_buffers);
  2332   dcqs.clear_n_completed_buffers();
  2333   assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
  2337 // Computes the sum of the storage used by the various regions.
  2339 size_t G1CollectedHeap::used() const {
  2340   assert(Heap_lock->owner() != NULL,
  2341          "Should be owned on this thread's behalf.");
  2342   size_t result = _summary_bytes_used;
  2343   // Read only once in case it is set to NULL concurrently
  2344   HeapRegion* hr = _mutator_alloc_region.get();
  2345   if (hr != NULL)
  2346     result += hr->used();
  2347   return result;
  2350 size_t G1CollectedHeap::used_unlocked() const {
  2351   size_t result = _summary_bytes_used;
  2352   return result;
  2355 class SumUsedClosure: public HeapRegionClosure {
  2356   size_t _used;
  2357 public:
  2358   SumUsedClosure() : _used(0) {}
  2359   bool doHeapRegion(HeapRegion* r) {
  2360     if (!r->continuesHumongous()) {
  2361       _used += r->used();
  2363     return false;
  2365   size_t result() { return _used; }
  2366 };
  2368 size_t G1CollectedHeap::recalculate_used() const {
  2369   double recalculate_used_start = os::elapsedTime();
  2371   SumUsedClosure blk;
  2372   heap_region_iterate(&blk);
  2374   g1_policy()->phase_times()->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0);
  2375   return blk.result();
  2378 size_t G1CollectedHeap::unsafe_max_alloc() {
  2379   if (free_regions() > 0) return HeapRegion::GrainBytes;
  2380   // otherwise, is there space in the current allocation region?
  2382   // We need to store the current allocation region in a local variable
  2383   // here. The problem is that this method doesn't take any locks and
  2384   // there may be other threads which overwrite the current allocation
  2385   // region field. attempt_allocation(), for example, sets it to NULL
  2386   // and this can happen *after* the NULL check here but before the call
  2387   // to free(), resulting in a SIGSEGV. Note that this doesn't appear
  2388   // to be a problem in the optimized build, since the two loads of the
  2389   // current allocation region field are optimized away.
  2390   HeapRegion* hr = _mutator_alloc_region.get();
  2391   if (hr == NULL) {
  2392     return 0;
  2394   return hr->free();
  2397 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
  2398   switch (cause) {
  2399     case GCCause::_gc_locker:               return GCLockerInvokesConcurrent;
  2400     case GCCause::_java_lang_system_gc:     return ExplicitGCInvokesConcurrent;
  2401     case GCCause::_g1_humongous_allocation: return true;
  2402     default:                                return false;
  2406 #ifndef PRODUCT
  2407 void G1CollectedHeap::allocate_dummy_regions() {
  2408   // Let's fill up most of the region
  2409   size_t word_size = HeapRegion::GrainWords - 1024;
  2410   // And as a result the region we'll allocate will be humongous.
  2411   guarantee(isHumongous(word_size), "sanity");
  2413   for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
  2414     // Let's use the existing mechanism for the allocation
  2415     HeapWord* dummy_obj = humongous_obj_allocate(word_size);
  2416     if (dummy_obj != NULL) {
  2417       MemRegion mr(dummy_obj, word_size);
  2418       CollectedHeap::fill_with_object(mr);
  2419     } else {
  2420       // If we can't allocate once, we probably cannot allocate
  2421       // again. Let's get out of the loop.
  2422       break;
  2426 #endif // !PRODUCT
  2428 void G1CollectedHeap::increment_old_marking_cycles_started() {
  2429   assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
  2430     _old_marking_cycles_started == _old_marking_cycles_completed + 1,
  2431     err_msg("Wrong marking cycle count (started: %d, completed: %d)",
  2432     _old_marking_cycles_started, _old_marking_cycles_completed));
  2434   _old_marking_cycles_started++;
  2437 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) {
  2438   MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
  2440   // We assume that if concurrent == true, then the caller is a
  2441   // concurrent thread that was joined the Suspendible Thread
  2442   // Set. If there's ever a cheap way to check this, we should add an
  2443   // assert here.
  2445   // Given that this method is called at the end of a Full GC or of a
  2446   // concurrent cycle, and those can be nested (i.e., a Full GC can
  2447   // interrupt a concurrent cycle), the number of full collections
  2448   // completed should be either one (in the case where there was no
  2449   // nesting) or two (when a Full GC interrupted a concurrent cycle)
  2450   // behind the number of full collections started.
  2452   // This is the case for the inner caller, i.e. a Full GC.
  2453   assert(concurrent ||
  2454          (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
  2455          (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
  2456          err_msg("for inner caller (Full GC): _old_marking_cycles_started = %u "
  2457                  "is inconsistent with _old_marking_cycles_completed = %u",
  2458                  _old_marking_cycles_started, _old_marking_cycles_completed));
  2460   // This is the case for the outer caller, i.e. the concurrent cycle.
  2461   assert(!concurrent ||
  2462          (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
  2463          err_msg("for outer caller (concurrent cycle): "
  2464                  "_old_marking_cycles_started = %u "
  2465                  "is inconsistent with _old_marking_cycles_completed = %u",
  2466                  _old_marking_cycles_started, _old_marking_cycles_completed));
  2468   _old_marking_cycles_completed += 1;
  2470   // We need to clear the "in_progress" flag in the CM thread before
  2471   // we wake up any waiters (especially when ExplicitInvokesConcurrent
  2472   // is set) so that if a waiter requests another System.gc() it doesn't
  2473   // incorrectly see that a marking cycle is still in progress.
  2474   if (concurrent) {
  2475     _cmThread->clear_in_progress();
  2478   // This notify_all() will ensure that a thread that called
  2479   // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
  2480   // and it's waiting for a full GC to finish will be woken up. It is
  2481   // waiting in VM_G1IncCollectionPause::doit_epilogue().
  2482   FullGCCount_lock->notify_all();
  2485 void G1CollectedHeap::register_concurrent_cycle_start(const Ticks& start_time) {
  2486   _concurrent_cycle_started = true;
  2487   _gc_timer_cm->register_gc_start(start_time);
  2489   _gc_tracer_cm->report_gc_start(gc_cause(), _gc_timer_cm->gc_start());
  2490   trace_heap_before_gc(_gc_tracer_cm);
  2493 void G1CollectedHeap::register_concurrent_cycle_end() {
  2494   if (_concurrent_cycle_started) {
  2495     if (_cm->has_aborted()) {
  2496       _gc_tracer_cm->report_concurrent_mode_failure();
  2499     _gc_timer_cm->register_gc_end();
  2500     _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
  2502     _concurrent_cycle_started = false;
  2506 void G1CollectedHeap::trace_heap_after_concurrent_cycle() {
  2507   if (_concurrent_cycle_started) {
  2508     trace_heap_after_gc(_gc_tracer_cm);
  2512 G1YCType G1CollectedHeap::yc_type() {
  2513   bool is_young = g1_policy()->gcs_are_young();
  2514   bool is_initial_mark = g1_policy()->during_initial_mark_pause();
  2515   bool is_during_mark = mark_in_progress();
  2517   if (is_initial_mark) {
  2518     return InitialMark;
  2519   } else if (is_during_mark) {
  2520     return DuringMark;
  2521   } else if (is_young) {
  2522     return Normal;
  2523   } else {
  2524     return Mixed;
  2528 void G1CollectedHeap::collect(GCCause::Cause cause) {
  2529   assert_heap_not_locked();
  2531   unsigned int gc_count_before;
  2532   unsigned int old_marking_count_before;
  2533   bool retry_gc;
  2535   do {
  2536     retry_gc = false;
  2539       MutexLocker ml(Heap_lock);
  2541       // Read the GC count while holding the Heap_lock
  2542       gc_count_before = total_collections();
  2543       old_marking_count_before = _old_marking_cycles_started;
  2546     if (should_do_concurrent_full_gc(cause)) {
  2547       // Schedule an initial-mark evacuation pause that will start a
  2548       // concurrent cycle. We're setting word_size to 0 which means that
  2549       // we are not requesting a post-GC allocation.
  2550       VM_G1IncCollectionPause op(gc_count_before,
  2551                                  0,     /* word_size */
  2552                                  true,  /* should_initiate_conc_mark */
  2553                                  g1_policy()->max_pause_time_ms(),
  2554                                  cause);
  2556       VMThread::execute(&op);
  2557       if (!op.pause_succeeded()) {
  2558         if (old_marking_count_before == _old_marking_cycles_started) {
  2559           retry_gc = op.should_retry_gc();
  2560         } else {
  2561           // A Full GC happened while we were trying to schedule the
  2562           // initial-mark GC. No point in starting a new cycle given
  2563           // that the whole heap was collected anyway.
  2566         if (retry_gc) {
  2567           if (GC_locker::is_active_and_needs_gc()) {
  2568             GC_locker::stall_until_clear();
  2572     } else {
  2573       if (cause == GCCause::_gc_locker
  2574           DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
  2576         // Schedule a standard evacuation pause. We're setting word_size
  2577         // to 0 which means that we are not requesting a post-GC allocation.
  2578         VM_G1IncCollectionPause op(gc_count_before,
  2579                                    0,     /* word_size */
  2580                                    false, /* should_initiate_conc_mark */
  2581                                    g1_policy()->max_pause_time_ms(),
  2582                                    cause);
  2583         VMThread::execute(&op);
  2584       } else {
  2585         // Schedule a Full GC.
  2586         VM_G1CollectFull op(gc_count_before, old_marking_count_before, cause);
  2587         VMThread::execute(&op);
  2590   } while (retry_gc);
  2593 bool G1CollectedHeap::is_in(const void* p) const {
  2594   if (_g1_committed.contains(p)) {
  2595     // Given that we know that p is in the committed space,
  2596     // heap_region_containing_raw() should successfully
  2597     // return the containing region.
  2598     HeapRegion* hr = heap_region_containing_raw(p);
  2599     return hr->is_in(p);
  2600   } else {
  2601     return false;
  2605 // Iteration functions.
  2607 // Iterates an OopClosure over all ref-containing fields of objects
  2608 // within a HeapRegion.
  2610 class IterateOopClosureRegionClosure: public HeapRegionClosure {
  2611   MemRegion _mr;
  2612   ExtendedOopClosure* _cl;
  2613 public:
  2614   IterateOopClosureRegionClosure(MemRegion mr, ExtendedOopClosure* cl)
  2615     : _mr(mr), _cl(cl) {}
  2616   bool doHeapRegion(HeapRegion* r) {
  2617     if (!r->continuesHumongous()) {
  2618       r->oop_iterate(_cl);
  2620     return false;
  2622 };
  2624 void G1CollectedHeap::oop_iterate(ExtendedOopClosure* cl) {
  2625   IterateOopClosureRegionClosure blk(_g1_committed, cl);
  2626   heap_region_iterate(&blk);
  2629 void G1CollectedHeap::oop_iterate(MemRegion mr, ExtendedOopClosure* cl) {
  2630   IterateOopClosureRegionClosure blk(mr, cl);
  2631   heap_region_iterate(&blk);
  2634 // Iterates an ObjectClosure over all objects within a HeapRegion.
  2636 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
  2637   ObjectClosure* _cl;
  2638 public:
  2639   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
  2640   bool doHeapRegion(HeapRegion* r) {
  2641     if (! r->continuesHumongous()) {
  2642       r->object_iterate(_cl);
  2644     return false;
  2646 };
  2648 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
  2649   IterateObjectClosureRegionClosure blk(cl);
  2650   heap_region_iterate(&blk);
  2653 // Calls a SpaceClosure on a HeapRegion.
  2655 class SpaceClosureRegionClosure: public HeapRegionClosure {
  2656   SpaceClosure* _cl;
  2657 public:
  2658   SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
  2659   bool doHeapRegion(HeapRegion* r) {
  2660     _cl->do_space(r);
  2661     return false;
  2663 };
  2665 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
  2666   SpaceClosureRegionClosure blk(cl);
  2667   heap_region_iterate(&blk);
  2670 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
  2671   _hrs.iterate(cl);
  2674 void
  2675 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
  2676                                                  uint worker_id,
  2677                                                  uint no_of_par_workers,
  2678                                                  jint claim_value) {
  2679   const uint regions = n_regions();
  2680   const uint max_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
  2681                              no_of_par_workers :
  2682                              1);
  2683   assert(UseDynamicNumberOfGCThreads ||
  2684          no_of_par_workers == workers()->total_workers(),
  2685          "Non dynamic should use fixed number of workers");
  2686   // try to spread out the starting points of the workers
  2687   const HeapRegion* start_hr =
  2688                         start_region_for_worker(worker_id, no_of_par_workers);
  2689   const uint start_index = start_hr->hrs_index();
  2691   // each worker will actually look at all regions
  2692   for (uint count = 0; count < regions; ++count) {
  2693     const uint index = (start_index + count) % regions;
  2694     assert(0 <= index && index < regions, "sanity");
  2695     HeapRegion* r = region_at(index);
  2696     // we'll ignore "continues humongous" regions (we'll process them
  2697     // when we come across their corresponding "start humongous"
  2698     // region) and regions already claimed
  2699     if (r->claim_value() == claim_value || r->continuesHumongous()) {
  2700       continue;
  2702     // OK, try to claim it
  2703     if (r->claimHeapRegion(claim_value)) {
  2704       // success!
  2705       assert(!r->continuesHumongous(), "sanity");
  2706       if (r->startsHumongous()) {
  2707         // If the region is "starts humongous" we'll iterate over its
  2708         // "continues humongous" first; in fact we'll do them
  2709         // first. The order is important. In on case, calling the
  2710         // closure on the "starts humongous" region might de-allocate
  2711         // and clear all its "continues humongous" regions and, as a
  2712         // result, we might end up processing them twice. So, we'll do
  2713         // them first (notice: most closures will ignore them anyway) and
  2714         // then we'll do the "starts humongous" region.
  2715         for (uint ch_index = index + 1; ch_index < regions; ++ch_index) {
  2716           HeapRegion* chr = region_at(ch_index);
  2718           // if the region has already been claimed or it's not
  2719           // "continues humongous" we're done
  2720           if (chr->claim_value() == claim_value ||
  2721               !chr->continuesHumongous()) {
  2722             break;
  2725           // No one should have claimed it directly. We can given
  2726           // that we claimed its "starts humongous" region.
  2727           assert(chr->claim_value() != claim_value, "sanity");
  2728           assert(chr->humongous_start_region() == r, "sanity");
  2730           if (chr->claimHeapRegion(claim_value)) {
  2731             // we should always be able to claim it; no one else should
  2732             // be trying to claim this region
  2734             bool res2 = cl->doHeapRegion(chr);
  2735             assert(!res2, "Should not abort");
  2737             // Right now, this holds (i.e., no closure that actually
  2738             // does something with "continues humongous" regions
  2739             // clears them). We might have to weaken it in the future,
  2740             // but let's leave these two asserts here for extra safety.
  2741             assert(chr->continuesHumongous(), "should still be the case");
  2742             assert(chr->humongous_start_region() == r, "sanity");
  2743           } else {
  2744             guarantee(false, "we should not reach here");
  2749       assert(!r->continuesHumongous(), "sanity");
  2750       bool res = cl->doHeapRegion(r);
  2751       assert(!res, "Should not abort");
  2756 class ResetClaimValuesClosure: public HeapRegionClosure {
  2757 public:
  2758   bool doHeapRegion(HeapRegion* r) {
  2759     r->set_claim_value(HeapRegion::InitialClaimValue);
  2760     return false;
  2762 };
  2764 void G1CollectedHeap::reset_heap_region_claim_values() {
  2765   ResetClaimValuesClosure blk;
  2766   heap_region_iterate(&blk);
  2769 void G1CollectedHeap::reset_cset_heap_region_claim_values() {
  2770   ResetClaimValuesClosure blk;
  2771   collection_set_iterate(&blk);
  2774 #ifdef ASSERT
  2775 // This checks whether all regions in the heap have the correct claim
  2776 // value. I also piggy-backed on this a check to ensure that the
  2777 // humongous_start_region() information on "continues humongous"
  2778 // regions is correct.
  2780 class CheckClaimValuesClosure : public HeapRegionClosure {
  2781 private:
  2782   jint _claim_value;
  2783   uint _failures;
  2784   HeapRegion* _sh_region;
  2786 public:
  2787   CheckClaimValuesClosure(jint claim_value) :
  2788     _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
  2789   bool doHeapRegion(HeapRegion* r) {
  2790     if (r->claim_value() != _claim_value) {
  2791       gclog_or_tty->print_cr("Region " HR_FORMAT ", "
  2792                              "claim value = %d, should be %d",
  2793                              HR_FORMAT_PARAMS(r),
  2794                              r->claim_value(), _claim_value);
  2795       ++_failures;
  2797     if (!r->isHumongous()) {
  2798       _sh_region = NULL;
  2799     } else if (r->startsHumongous()) {
  2800       _sh_region = r;
  2801     } else if (r->continuesHumongous()) {
  2802       if (r->humongous_start_region() != _sh_region) {
  2803         gclog_or_tty->print_cr("Region " HR_FORMAT ", "
  2804                                "HS = "PTR_FORMAT", should be "PTR_FORMAT,
  2805                                HR_FORMAT_PARAMS(r),
  2806                                r->humongous_start_region(),
  2807                                _sh_region);
  2808         ++_failures;
  2811     return false;
  2813   uint failures() { return _failures; }
  2814 };
  2816 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
  2817   CheckClaimValuesClosure cl(claim_value);
  2818   heap_region_iterate(&cl);
  2819   return cl.failures() == 0;
  2822 class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {
  2823 private:
  2824   jint _claim_value;
  2825   uint _failures;
  2827 public:
  2828   CheckClaimValuesInCSetHRClosure(jint claim_value) :
  2829     _claim_value(claim_value), _failures(0) { }
  2831   uint failures() { return _failures; }
  2833   bool doHeapRegion(HeapRegion* hr) {
  2834     assert(hr->in_collection_set(), "how?");
  2835     assert(!hr->isHumongous(), "H-region in CSet");
  2836     if (hr->claim_value() != _claim_value) {
  2837       gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "
  2838                              "claim value = %d, should be %d",
  2839                              HR_FORMAT_PARAMS(hr),
  2840                              hr->claim_value(), _claim_value);
  2841       _failures += 1;
  2843     return false;
  2845 };
  2847 bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {
  2848   CheckClaimValuesInCSetHRClosure cl(claim_value);
  2849   collection_set_iterate(&cl);
  2850   return cl.failures() == 0;
  2852 #endif // ASSERT
  2854 // Clear the cached CSet starting regions and (more importantly)
  2855 // the time stamps. Called when we reset the GC time stamp.
  2856 void G1CollectedHeap::clear_cset_start_regions() {
  2857   assert(_worker_cset_start_region != NULL, "sanity");
  2858   assert(_worker_cset_start_region_time_stamp != NULL, "sanity");
  2860   int n_queues = MAX2((int)ParallelGCThreads, 1);
  2861   for (int i = 0; i < n_queues; i++) {
  2862     _worker_cset_start_region[i] = NULL;
  2863     _worker_cset_start_region_time_stamp[i] = 0;
  2867 // Given the id of a worker, obtain or calculate a suitable
  2868 // starting region for iterating over the current collection set.
  2869 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(uint worker_i) {
  2870   assert(get_gc_time_stamp() > 0, "should have been updated by now");
  2872   HeapRegion* result = NULL;
  2873   unsigned gc_time_stamp = get_gc_time_stamp();
  2875   if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) {
  2876     // Cached starting region for current worker was set
  2877     // during the current pause - so it's valid.
  2878     // Note: the cached starting heap region may be NULL
  2879     // (when the collection set is empty).
  2880     result = _worker_cset_start_region[worker_i];
  2881     assert(result == NULL || result->in_collection_set(), "sanity");
  2882     return result;
  2885   // The cached entry was not valid so let's calculate
  2886   // a suitable starting heap region for this worker.
  2888   // We want the parallel threads to start their collection
  2889   // set iteration at different collection set regions to
  2890   // avoid contention.
  2891   // If we have:
  2892   //          n collection set regions
  2893   //          p threads
  2894   // Then thread t will start at region floor ((t * n) / p)
  2896   result = g1_policy()->collection_set();
  2897   if (G1CollectedHeap::use_parallel_gc_threads()) {
  2898     uint cs_size = g1_policy()->cset_region_length();
  2899     uint active_workers = workers()->active_workers();
  2900     assert(UseDynamicNumberOfGCThreads ||
  2901              active_workers == workers()->total_workers(),
  2902              "Unless dynamic should use total workers");
  2904     uint end_ind   = (cs_size * worker_i) / active_workers;
  2905     uint start_ind = 0;
  2907     if (worker_i > 0 &&
  2908         _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) {
  2909       // Previous workers starting region is valid
  2910       // so let's iterate from there
  2911       start_ind = (cs_size * (worker_i - 1)) / active_workers;
  2912       result = _worker_cset_start_region[worker_i - 1];
  2915     for (uint i = start_ind; i < end_ind; i++) {
  2916       result = result->next_in_collection_set();
  2920   // Note: the calculated starting heap region may be NULL
  2921   // (when the collection set is empty).
  2922   assert(result == NULL || result->in_collection_set(), "sanity");
  2923   assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp,
  2924          "should be updated only once per pause");
  2925   _worker_cset_start_region[worker_i] = result;
  2926   OrderAccess::storestore();
  2927   _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp;
  2928   return result;
  2931 HeapRegion* G1CollectedHeap::start_region_for_worker(uint worker_i,
  2932                                                      uint no_of_par_workers) {
  2933   uint worker_num =
  2934            G1CollectedHeap::use_parallel_gc_threads() ? no_of_par_workers : 1U;
  2935   assert(UseDynamicNumberOfGCThreads ||
  2936          no_of_par_workers == workers()->total_workers(),
  2937          "Non dynamic should use fixed number of workers");
  2938   const uint start_index = n_regions() * worker_i / worker_num;
  2939   return region_at(start_index);
  2942 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
  2943   HeapRegion* r = g1_policy()->collection_set();
  2944   while (r != NULL) {
  2945     HeapRegion* next = r->next_in_collection_set();
  2946     if (cl->doHeapRegion(r)) {
  2947       cl->incomplete();
  2948       return;
  2950     r = next;
  2954 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
  2955                                                   HeapRegionClosure *cl) {
  2956   if (r == NULL) {
  2957     // The CSet is empty so there's nothing to do.
  2958     return;
  2961   assert(r->in_collection_set(),
  2962          "Start region must be a member of the collection set.");
  2963   HeapRegion* cur = r;
  2964   while (cur != NULL) {
  2965     HeapRegion* next = cur->next_in_collection_set();
  2966     if (cl->doHeapRegion(cur) && false) {
  2967       cl->incomplete();
  2968       return;
  2970     cur = next;
  2972   cur = g1_policy()->collection_set();
  2973   while (cur != r) {
  2974     HeapRegion* next = cur->next_in_collection_set();
  2975     if (cl->doHeapRegion(cur) && false) {
  2976       cl->incomplete();
  2977       return;
  2979     cur = next;
  2983 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
  2984   return n_regions() > 0 ? region_at(0) : NULL;
  2988 Space* G1CollectedHeap::space_containing(const void* addr) const {
  2989   Space* res = heap_region_containing(addr);
  2990   return res;
  2993 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
  2994   Space* sp = space_containing(addr);
  2995   if (sp != NULL) {
  2996     return sp->block_start(addr);
  2998   return NULL;
  3001 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
  3002   Space* sp = space_containing(addr);
  3003   assert(sp != NULL, "block_size of address outside of heap");
  3004   return sp->block_size(addr);
  3007 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
  3008   Space* sp = space_containing(addr);
  3009   return sp->block_is_obj(addr);
  3012 bool G1CollectedHeap::supports_tlab_allocation() const {
  3013   return true;
  3016 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
  3017   return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes;
  3020 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
  3021   return young_list()->eden_used_bytes();
  3024 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
  3025 // must be smaller than the humongous object limit.
  3026 size_t G1CollectedHeap::max_tlab_size() const {
  3027   return align_size_down(_humongous_object_threshold_in_words - 1, MinObjAlignment);
  3030 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
  3031   // Return the remaining space in the cur alloc region, but not less than
  3032   // the min TLAB size.
  3034   // Also, this value can be at most the humongous object threshold,
  3035   // since we can't allow tlabs to grow big enough to accommodate
  3036   // humongous objects.
  3038   HeapRegion* hr = _mutator_alloc_region.get();
  3039   size_t max_tlab = max_tlab_size() * wordSize;
  3040   if (hr == NULL) {
  3041     return max_tlab;
  3042   } else {
  3043     return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab);
  3047 size_t G1CollectedHeap::max_capacity() const {
  3048   return _g1_reserved.byte_size();
  3051 jlong G1CollectedHeap::millis_since_last_gc() {
  3052   // assert(false, "NYI");
  3053   return 0;
  3056 void G1CollectedHeap::prepare_for_verify() {
  3057   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
  3058     ensure_parsability(false);
  3060   g1_rem_set()->prepare_for_verify();
  3063 bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr,
  3064                                               VerifyOption vo) {
  3065   switch (vo) {
  3066   case VerifyOption_G1UsePrevMarking:
  3067     return hr->obj_allocated_since_prev_marking(obj);
  3068   case VerifyOption_G1UseNextMarking:
  3069     return hr->obj_allocated_since_next_marking(obj);
  3070   case VerifyOption_G1UseMarkWord:
  3071     return false;
  3072   default:
  3073     ShouldNotReachHere();
  3075   return false; // keep some compilers happy
  3078 HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) {
  3079   switch (vo) {
  3080   case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start();
  3081   case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start();
  3082   case VerifyOption_G1UseMarkWord:    return NULL;
  3083   default:                            ShouldNotReachHere();
  3085   return NULL; // keep some compilers happy
  3088 bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) {
  3089   switch (vo) {
  3090   case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj);
  3091   case VerifyOption_G1UseNextMarking: return isMarkedNext(obj);
  3092   case VerifyOption_G1UseMarkWord:    return obj->is_gc_marked();
  3093   default:                            ShouldNotReachHere();
  3095   return false; // keep some compilers happy
  3098 const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) {
  3099   switch (vo) {
  3100   case VerifyOption_G1UsePrevMarking: return "PTAMS";
  3101   case VerifyOption_G1UseNextMarking: return "NTAMS";
  3102   case VerifyOption_G1UseMarkWord:    return "NONE";
  3103   default:                            ShouldNotReachHere();
  3105   return NULL; // keep some compilers happy
  3108 class VerifyRootsClosure: public OopClosure {
  3109 private:
  3110   G1CollectedHeap* _g1h;
  3111   VerifyOption     _vo;
  3112   bool             _failures;
  3113 public:
  3114   // _vo == UsePrevMarking -> use "prev" marking information,
  3115   // _vo == UseNextMarking -> use "next" marking information,
  3116   // _vo == UseMarkWord    -> use mark word from object header.
  3117   VerifyRootsClosure(VerifyOption vo) :
  3118     _g1h(G1CollectedHeap::heap()),
  3119     _vo(vo),
  3120     _failures(false) { }
  3122   bool failures() { return _failures; }
  3124   template <class T> void do_oop_nv(T* p) {
  3125     T heap_oop = oopDesc::load_heap_oop(p);
  3126     if (!oopDesc::is_null(heap_oop)) {
  3127       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  3128       if (_g1h->is_obj_dead_cond(obj, _vo)) {
  3129         gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
  3130                               "points to dead obj "PTR_FORMAT, p, (void*) obj);
  3131         if (_vo == VerifyOption_G1UseMarkWord) {
  3132           gclog_or_tty->print_cr("  Mark word: "PTR_FORMAT, (void*)(obj->mark()));
  3134         obj->print_on(gclog_or_tty);
  3135         _failures = true;
  3140   void do_oop(oop* p)       { do_oop_nv(p); }
  3141   void do_oop(narrowOop* p) { do_oop_nv(p); }
  3142 };
  3144 class G1VerifyCodeRootOopClosure: public OopClosure {
  3145   G1CollectedHeap* _g1h;
  3146   OopClosure* _root_cl;
  3147   nmethod* _nm;
  3148   VerifyOption _vo;
  3149   bool _failures;
  3151   template <class T> void do_oop_work(T* p) {
  3152     // First verify that this root is live
  3153     _root_cl->do_oop(p);
  3155     if (!G1VerifyHeapRegionCodeRoots) {
  3156       // We're not verifying the code roots attached to heap region.
  3157       return;
  3160     // Don't check the code roots during marking verification in a full GC
  3161     if (_vo == VerifyOption_G1UseMarkWord) {
  3162       return;
  3165     // Now verify that the current nmethod (which contains p) is
  3166     // in the code root list of the heap region containing the
  3167     // object referenced by p.
  3169     T heap_oop = oopDesc::load_heap_oop(p);
  3170     if (!oopDesc::is_null(heap_oop)) {
  3171       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  3173       // Now fetch the region containing the object
  3174       HeapRegion* hr = _g1h->heap_region_containing(obj);
  3175       HeapRegionRemSet* hrrs = hr->rem_set();
  3176       // Verify that the strong code root list for this region
  3177       // contains the nmethod
  3178       if (!hrrs->strong_code_roots_list_contains(_nm)) {
  3179         gclog_or_tty->print_cr("Code root location "PTR_FORMAT" "
  3180                               "from nmethod "PTR_FORMAT" not in strong "
  3181                               "code roots for region ["PTR_FORMAT","PTR_FORMAT")",
  3182                               p, _nm, hr->bottom(), hr->end());
  3183         _failures = true;
  3188 public:
  3189   G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
  3190     _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}
  3192   void do_oop(oop* p) { do_oop_work(p); }
  3193   void do_oop(narrowOop* p) { do_oop_work(p); }
  3195   void set_nmethod(nmethod* nm) { _nm = nm; }
  3196   bool failures() { return _failures; }
  3197 };
  3199 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
  3200   G1VerifyCodeRootOopClosure* _oop_cl;
  3202 public:
  3203   G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
  3204     _oop_cl(oop_cl) {}
  3206   void do_code_blob(CodeBlob* cb) {
  3207     nmethod* nm = cb->as_nmethod_or_null();
  3208     if (nm != NULL) {
  3209       _oop_cl->set_nmethod(nm);
  3210       nm->oops_do(_oop_cl);
  3213 };
  3215 class YoungRefCounterClosure : public OopClosure {
  3216   G1CollectedHeap* _g1h;
  3217   int              _count;
  3218  public:
  3219   YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
  3220   void do_oop(oop* p)       { if (_g1h->is_in_young(*p)) { _count++; } }
  3221   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
  3223   int count() { return _count; }
  3224   void reset_count() { _count = 0; };
  3225 };
  3227 class VerifyKlassClosure: public KlassClosure {
  3228   YoungRefCounterClosure _young_ref_counter_closure;
  3229   OopClosure *_oop_closure;
  3230  public:
  3231   VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
  3232   void do_klass(Klass* k) {
  3233     k->oops_do(_oop_closure);
  3235     _young_ref_counter_closure.reset_count();
  3236     k->oops_do(&_young_ref_counter_closure);
  3237     if (_young_ref_counter_closure.count() > 0) {
  3238       guarantee(k->has_modified_oops(), err_msg("Klass %p, has young refs but is not dirty.", k));
  3241 };
  3243 class VerifyLivenessOopClosure: public OopClosure {
  3244   G1CollectedHeap* _g1h;
  3245   VerifyOption _vo;
  3246 public:
  3247   VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
  3248     _g1h(g1h), _vo(vo)
  3249   { }
  3250   void do_oop(narrowOop *p) { do_oop_work(p); }
  3251   void do_oop(      oop *p) { do_oop_work(p); }
  3253   template <class T> void do_oop_work(T *p) {
  3254     oop obj = oopDesc::load_decode_heap_oop(p);
  3255     guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
  3256               "Dead object referenced by a not dead object");
  3258 };
  3260 class VerifyObjsInRegionClosure: public ObjectClosure {
  3261 private:
  3262   G1CollectedHeap* _g1h;
  3263   size_t _live_bytes;
  3264   HeapRegion *_hr;
  3265   VerifyOption _vo;
  3266 public:
  3267   // _vo == UsePrevMarking -> use "prev" marking information,
  3268   // _vo == UseNextMarking -> use "next" marking information,
  3269   // _vo == UseMarkWord    -> use mark word from object header.
  3270   VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
  3271     : _live_bytes(0), _hr(hr), _vo(vo) {
  3272     _g1h = G1CollectedHeap::heap();
  3274   void do_object(oop o) {
  3275     VerifyLivenessOopClosure isLive(_g1h, _vo);
  3276     assert(o != NULL, "Huh?");
  3277     if (!_g1h->is_obj_dead_cond(o, _vo)) {
  3278       // If the object is alive according to the mark word,
  3279       // then verify that the marking information agrees.
  3280       // Note we can't verify the contra-positive of the
  3281       // above: if the object is dead (according to the mark
  3282       // word), it may not be marked, or may have been marked
  3283       // but has since became dead, or may have been allocated
  3284       // since the last marking.
  3285       if (_vo == VerifyOption_G1UseMarkWord) {
  3286         guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
  3289       o->oop_iterate_no_header(&isLive);
  3290       if (!_hr->obj_allocated_since_prev_marking(o)) {
  3291         size_t obj_size = o->size();    // Make sure we don't overflow
  3292         _live_bytes += (obj_size * HeapWordSize);
  3296   size_t live_bytes() { return _live_bytes; }
  3297 };
  3299 class PrintObjsInRegionClosure : public ObjectClosure {
  3300   HeapRegion *_hr;
  3301   G1CollectedHeap *_g1;
  3302 public:
  3303   PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
  3304     _g1 = G1CollectedHeap::heap();
  3305   };
  3307   void do_object(oop o) {
  3308     if (o != NULL) {
  3309       HeapWord *start = (HeapWord *) o;
  3310       size_t word_sz = o->size();
  3311       gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
  3312                           " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
  3313                           (void*) o, word_sz,
  3314                           _g1->isMarkedPrev(o),
  3315                           _g1->isMarkedNext(o),
  3316                           _hr->obj_allocated_since_prev_marking(o));
  3317       HeapWord *end = start + word_sz;
  3318       HeapWord *cur;
  3319       int *val;
  3320       for (cur = start; cur < end; cur++) {
  3321         val = (int *) cur;
  3322         gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
  3326 };
  3328 class VerifyRegionClosure: public HeapRegionClosure {
  3329 private:
  3330   bool             _par;
  3331   VerifyOption     _vo;
  3332   bool             _failures;
  3333 public:
  3334   // _vo == UsePrevMarking -> use "prev" marking information,
  3335   // _vo == UseNextMarking -> use "next" marking information,
  3336   // _vo == UseMarkWord    -> use mark word from object header.
  3337   VerifyRegionClosure(bool par, VerifyOption vo)
  3338     : _par(par),
  3339       _vo(vo),
  3340       _failures(false) {}
  3342   bool failures() {
  3343     return _failures;
  3346   bool doHeapRegion(HeapRegion* r) {
  3347     if (!r->continuesHumongous()) {
  3348       bool failures = false;
  3349       r->verify(_vo, &failures);
  3350       if (failures) {
  3351         _failures = true;
  3352       } else {
  3353         VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
  3354         r->object_iterate(&not_dead_yet_cl);
  3355         if (_vo != VerifyOption_G1UseNextMarking) {
  3356           if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
  3357             gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
  3358                                    "max_live_bytes "SIZE_FORMAT" "
  3359                                    "< calculated "SIZE_FORMAT,
  3360                                    r->bottom(), r->end(),
  3361                                    r->max_live_bytes(),
  3362                                  not_dead_yet_cl.live_bytes());
  3363             _failures = true;
  3365         } else {
  3366           // When vo == UseNextMarking we cannot currently do a sanity
  3367           // check on the live bytes as the calculation has not been
  3368           // finalized yet.
  3372     return false; // stop the region iteration if we hit a failure
  3374 };
  3376 // This is the task used for parallel verification of the heap regions
  3378 class G1ParVerifyTask: public AbstractGangTask {
  3379 private:
  3380   G1CollectedHeap* _g1h;
  3381   VerifyOption     _vo;
  3382   bool             _failures;
  3384 public:
  3385   // _vo == UsePrevMarking -> use "prev" marking information,
  3386   // _vo == UseNextMarking -> use "next" marking information,
  3387   // _vo == UseMarkWord    -> use mark word from object header.
  3388   G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
  3389     AbstractGangTask("Parallel verify task"),
  3390     _g1h(g1h),
  3391     _vo(vo),
  3392     _failures(false) { }
  3394   bool failures() {
  3395     return _failures;
  3398   void work(uint worker_id) {
  3399     HandleMark hm;
  3400     VerifyRegionClosure blk(true, _vo);
  3401     _g1h->heap_region_par_iterate_chunked(&blk, worker_id,
  3402                                           _g1h->workers()->active_workers(),
  3403                                           HeapRegion::ParVerifyClaimValue);
  3404     if (blk.failures()) {
  3405       _failures = true;
  3408 };
  3410 void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
  3411   if (SafepointSynchronize::is_at_safepoint()) {
  3412     assert(Thread::current()->is_VM_thread(),
  3413            "Expected to be executed serially by the VM thread at this point");
  3415     if (!silent) { gclog_or_tty->print("Roots "); }
  3416     VerifyRootsClosure rootsCl(vo);
  3417     G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);
  3418     G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
  3419     VerifyKlassClosure klassCl(this, &rootsCl);
  3421     // We apply the relevant closures to all the oops in the
  3422     // system dictionary, the string table and the code cache.
  3423     const int so = SO_AllClasses | SO_Strings | SO_CodeCache;
  3425     // Need cleared claim bits for the strong roots processing
  3426     ClassLoaderDataGraph::clear_claimed_marks();
  3428     process_strong_roots(true,      // activate StrongRootsScope
  3429                          false,     // we set "is scavenging" to false,
  3430                                     // so we don't reset the dirty cards.
  3431                          ScanningOption(so),  // roots scanning options
  3432                          &rootsCl,
  3433                          &blobsCl,
  3434                          &klassCl
  3435                          );
  3437     bool failures = rootsCl.failures() || codeRootsCl.failures();
  3439     if (vo != VerifyOption_G1UseMarkWord) {
  3440       // If we're verifying during a full GC then the region sets
  3441       // will have been torn down at the start of the GC. Therefore
  3442       // verifying the region sets will fail. So we only verify
  3443       // the region sets when not in a full GC.
  3444       if (!silent) { gclog_or_tty->print("HeapRegionSets "); }
  3445       verify_region_sets();
  3448     if (!silent) { gclog_or_tty->print("HeapRegions "); }
  3449     if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
  3450       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  3451              "sanity check");
  3453       G1ParVerifyTask task(this, vo);
  3454       assert(UseDynamicNumberOfGCThreads ||
  3455         workers()->active_workers() == workers()->total_workers(),
  3456         "If not dynamic should be using all the workers");
  3457       int n_workers = workers()->active_workers();
  3458       set_par_threads(n_workers);
  3459       workers()->run_task(&task);
  3460       set_par_threads(0);
  3461       if (task.failures()) {
  3462         failures = true;
  3465       // Checks that the expected amount of parallel work was done.
  3466       // The implication is that n_workers is > 0.
  3467       assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
  3468              "sanity check");
  3470       reset_heap_region_claim_values();
  3472       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  3473              "sanity check");
  3474     } else {
  3475       VerifyRegionClosure blk(false, vo);
  3476       heap_region_iterate(&blk);
  3477       if (blk.failures()) {
  3478         failures = true;
  3481     if (!silent) gclog_or_tty->print("RemSet ");
  3482     rem_set()->verify();
  3484     if (G1StringDedup::is_enabled()) {
  3485       if (!silent) gclog_or_tty->print("StrDedup ");
  3486       G1StringDedup::verify();
  3489     if (failures) {
  3490       gclog_or_tty->print_cr("Heap:");
  3491       // It helps to have the per-region information in the output to
  3492       // help us track down what went wrong. This is why we call
  3493       // print_extended_on() instead of print_on().
  3494       print_extended_on(gclog_or_tty);
  3495       gclog_or_tty->cr();
  3496 #ifndef PRODUCT
  3497       if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {
  3498         concurrent_mark()->print_reachable("at-verification-failure",
  3499                                            vo, false /* all */);
  3501 #endif
  3502       gclog_or_tty->flush();
  3504     guarantee(!failures, "there should not have been any failures");
  3505   } else {
  3506     if (!silent) {
  3507       gclog_or_tty->print("(SKIPPING Roots, HeapRegionSets, HeapRegions, RemSet");
  3508       if (G1StringDedup::is_enabled()) {
  3509         gclog_or_tty->print(", StrDedup");
  3511       gclog_or_tty->print(") ");
  3516 void G1CollectedHeap::verify(bool silent) {
  3517   verify(silent, VerifyOption_G1UsePrevMarking);
  3520 double G1CollectedHeap::verify(bool guard, const char* msg) {
  3521   double verify_time_ms = 0.0;
  3523   if (guard && total_collections() >= VerifyGCStartAt) {
  3524     double verify_start = os::elapsedTime();
  3525     HandleMark hm;  // Discard invalid handles created during verification
  3526     prepare_for_verify();
  3527     Universe::verify(VerifyOption_G1UsePrevMarking, msg);
  3528     verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
  3531   return verify_time_ms;
  3534 void G1CollectedHeap::verify_before_gc() {
  3535   double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:");
  3536   g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);
  3539 void G1CollectedHeap::verify_after_gc() {
  3540   double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:");
  3541   g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);
  3544 class PrintRegionClosure: public HeapRegionClosure {
  3545   outputStream* _st;
  3546 public:
  3547   PrintRegionClosure(outputStream* st) : _st(st) {}
  3548   bool doHeapRegion(HeapRegion* r) {
  3549     r->print_on(_st);
  3550     return false;
  3552 };
  3554 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
  3555                                        const HeapRegion* hr,
  3556                                        const VerifyOption vo) const {
  3557   switch (vo) {
  3558   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
  3559   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
  3560   case VerifyOption_G1UseMarkWord:    return !obj->is_gc_marked();
  3561   default:                            ShouldNotReachHere();
  3563   return false; // keep some compilers happy
  3566 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
  3567                                        const VerifyOption vo) const {
  3568   switch (vo) {
  3569   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
  3570   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
  3571   case VerifyOption_G1UseMarkWord:    return !obj->is_gc_marked();
  3572   default:                            ShouldNotReachHere();
  3574   return false; // keep some compilers happy
  3577 void G1CollectedHeap::print_on(outputStream* st) const {
  3578   st->print(" %-20s", "garbage-first heap");
  3579   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
  3580             capacity()/K, used_unlocked()/K);
  3581   st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
  3582             _g1_storage.low_boundary(),
  3583             _g1_storage.high(),
  3584             _g1_storage.high_boundary());
  3585   st->cr();
  3586   st->print("  region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
  3587   uint young_regions = _young_list->length();
  3588   st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
  3589             (size_t) young_regions * HeapRegion::GrainBytes / K);
  3590   uint survivor_regions = g1_policy()->recorded_survivor_regions();
  3591   st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
  3592             (size_t) survivor_regions * HeapRegion::GrainBytes / K);
  3593   st->cr();
  3594   MetaspaceAux::print_on(st);
  3597 void G1CollectedHeap::print_extended_on(outputStream* st) const {
  3598   print_on(st);
  3600   // Print the per-region information.
  3601   st->cr();
  3602   st->print_cr("Heap Regions: (Y=young(eden), SU=young(survivor), "
  3603                "HS=humongous(starts), HC=humongous(continues), "
  3604                "CS=collection set, F=free, TS=gc time stamp, "
  3605                "PTAMS=previous top-at-mark-start, "
  3606                "NTAMS=next top-at-mark-start)");
  3607   PrintRegionClosure blk(st);
  3608   heap_region_iterate(&blk);
  3611 void G1CollectedHeap::print_on_error(outputStream* st) const {
  3612   this->CollectedHeap::print_on_error(st);
  3614   if (_cm != NULL) {
  3615     st->cr();
  3616     _cm->print_on_error(st);
  3620 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
  3621   if (G1CollectedHeap::use_parallel_gc_threads()) {
  3622     workers()->print_worker_threads_on(st);
  3624   _cmThread->print_on(st);
  3625   st->cr();
  3626   _cm->print_worker_threads_on(st);
  3627   _cg1r->print_worker_threads_on(st);
  3628   if (G1StringDedup::is_enabled()) {
  3629     G1StringDedup::print_worker_threads_on(st);
  3633 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
  3634   if (G1CollectedHeap::use_parallel_gc_threads()) {
  3635     workers()->threads_do(tc);
  3637   tc->do_thread(_cmThread);
  3638   _cg1r->threads_do(tc);
  3639   if (G1StringDedup::is_enabled()) {
  3640     G1StringDedup::threads_do(tc);
  3644 void G1CollectedHeap::print_tracing_info() const {
  3645   // We'll overload this to mean "trace GC pause statistics."
  3646   if (TraceGen0Time || TraceGen1Time) {
  3647     // The "G1CollectorPolicy" is keeping track of these stats, so delegate
  3648     // to that.
  3649     g1_policy()->print_tracing_info();
  3651   if (G1SummarizeRSetStats) {
  3652     g1_rem_set()->print_summary_info();
  3654   if (G1SummarizeConcMark) {
  3655     concurrent_mark()->print_summary_info();
  3657   g1_policy()->print_yg_surv_rate_info();
  3658   SpecializationStats::print();
  3661 #ifndef PRODUCT
  3662 // Helpful for debugging RSet issues.
  3664 class PrintRSetsClosure : public HeapRegionClosure {
  3665 private:
  3666   const char* _msg;
  3667   size_t _occupied_sum;
  3669 public:
  3670   bool doHeapRegion(HeapRegion* r) {
  3671     HeapRegionRemSet* hrrs = r->rem_set();
  3672     size_t occupied = hrrs->occupied();
  3673     _occupied_sum += occupied;
  3675     gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT,
  3676                            HR_FORMAT_PARAMS(r));
  3677     if (occupied == 0) {
  3678       gclog_or_tty->print_cr("  RSet is empty");
  3679     } else {
  3680       hrrs->print();
  3682     gclog_or_tty->print_cr("----------");
  3683     return false;
  3686   PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
  3687     gclog_or_tty->cr();
  3688     gclog_or_tty->print_cr("========================================");
  3689     gclog_or_tty->print_cr("%s", msg);
  3690     gclog_or_tty->cr();
  3693   ~PrintRSetsClosure() {
  3694     gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum);
  3695     gclog_or_tty->print_cr("========================================");
  3696     gclog_or_tty->cr();
  3698 };
  3700 void G1CollectedHeap::print_cset_rsets() {
  3701   PrintRSetsClosure cl("Printing CSet RSets");
  3702   collection_set_iterate(&cl);
  3705 void G1CollectedHeap::print_all_rsets() {
  3706   PrintRSetsClosure cl("Printing All RSets");;
  3707   heap_region_iterate(&cl);
  3709 #endif // PRODUCT
  3711 G1CollectedHeap* G1CollectedHeap::heap() {
  3712   assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
  3713          "not a garbage-first heap");
  3714   return _g1h;
  3717 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
  3718   // always_do_update_barrier = false;
  3719   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
  3720   // Fill TLAB's and such
  3721   accumulate_statistics_all_tlabs();
  3722   ensure_parsability(true);
  3724   if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) &&
  3725       (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
  3726     g1_rem_set()->print_periodic_summary_info("Before GC RS summary");
  3730 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
  3732   if (G1SummarizeRSetStats &&
  3733       (G1SummarizeRSetStatsPeriod > 0) &&
  3734       // we are at the end of the GC. Total collections has already been increased.
  3735       ((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) {
  3736     g1_rem_set()->print_periodic_summary_info("After GC RS summary");
  3739   // FIXME: what is this about?
  3740   // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
  3741   // is set.
  3742   COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
  3743                         "derived pointer present"));
  3744   // always_do_update_barrier = true;
  3746   resize_all_tlabs();
  3748   // We have just completed a GC. Update the soft reference
  3749   // policy with the new heap occupancy
  3750   Universe::update_heap_info_at_gc();
  3753 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
  3754                                                unsigned int gc_count_before,
  3755                                                bool* succeeded,
  3756                                                GCCause::Cause gc_cause) {
  3757   assert_heap_not_locked_and_not_at_safepoint();
  3758   g1_policy()->record_stop_world_start();
  3759   VM_G1IncCollectionPause op(gc_count_before,
  3760                              word_size,
  3761                              false, /* should_initiate_conc_mark */
  3762                              g1_policy()->max_pause_time_ms(),
  3763                              gc_cause);
  3764   VMThread::execute(&op);
  3766   HeapWord* result = op.result();
  3767   bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
  3768   assert(result == NULL || ret_succeeded,
  3769          "the result should be NULL if the VM did not succeed");
  3770   *succeeded = ret_succeeded;
  3772   assert_heap_not_locked();
  3773   return result;
  3776 void
  3777 G1CollectedHeap::doConcurrentMark() {
  3778   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  3779   if (!_cmThread->in_progress()) {
  3780     _cmThread->set_started();
  3781     CGC_lock->notify();
  3785 size_t G1CollectedHeap::pending_card_num() {
  3786   size_t extra_cards = 0;
  3787   JavaThread *curr = Threads::first();
  3788   while (curr != NULL) {
  3789     DirtyCardQueue& dcq = curr->dirty_card_queue();
  3790     extra_cards += dcq.size();
  3791     curr = curr->next();
  3793   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
  3794   size_t buffer_size = dcqs.buffer_size();
  3795   size_t buffer_num = dcqs.completed_buffers_num();
  3797   // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes
  3798   // in bytes - not the number of 'entries'. We need to convert
  3799   // into a number of cards.
  3800   return (buffer_size * buffer_num + extra_cards) / oopSize;
  3803 size_t G1CollectedHeap::cards_scanned() {
  3804   return g1_rem_set()->cardsScanned();
  3807 void
  3808 G1CollectedHeap::setup_surviving_young_words() {
  3809   assert(_surviving_young_words == NULL, "pre-condition");
  3810   uint array_length = g1_policy()->young_cset_region_length();
  3811   _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC);
  3812   if (_surviving_young_words == NULL) {
  3813     vm_exit_out_of_memory(sizeof(size_t) * array_length, OOM_MALLOC_ERROR,
  3814                           "Not enough space for young surv words summary.");
  3816   memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t));
  3817 #ifdef ASSERT
  3818   for (uint i = 0;  i < array_length; ++i) {
  3819     assert( _surviving_young_words[i] == 0, "memset above" );
  3821 #endif // !ASSERT
  3824 void
  3825 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
  3826   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  3827   uint array_length = g1_policy()->young_cset_region_length();
  3828   for (uint i = 0; i < array_length; ++i) {
  3829     _surviving_young_words[i] += surv_young_words[i];
  3833 void
  3834 G1CollectedHeap::cleanup_surviving_young_words() {
  3835   guarantee( _surviving_young_words != NULL, "pre-condition" );
  3836   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words, mtGC);
  3837   _surviving_young_words = NULL;
  3840 #ifdef ASSERT
  3841 class VerifyCSetClosure: public HeapRegionClosure {
  3842 public:
  3843   bool doHeapRegion(HeapRegion* hr) {
  3844     // Here we check that the CSet region's RSet is ready for parallel
  3845     // iteration. The fields that we'll verify are only manipulated
  3846     // when the region is part of a CSet and is collected. Afterwards,
  3847     // we reset these fields when we clear the region's RSet (when the
  3848     // region is freed) so they are ready when the region is
  3849     // re-allocated. The only exception to this is if there's an
  3850     // evacuation failure and instead of freeing the region we leave
  3851     // it in the heap. In that case, we reset these fields during
  3852     // evacuation failure handling.
  3853     guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");
  3855     // Here's a good place to add any other checks we'd like to
  3856     // perform on CSet regions.
  3857     return false;
  3859 };
  3860 #endif // ASSERT
  3862 #if TASKQUEUE_STATS
  3863 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
  3864   st->print_raw_cr("GC Task Stats");
  3865   st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
  3866   st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
  3869 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
  3870   print_taskqueue_stats_hdr(st);
  3872   TaskQueueStats totals;
  3873   const int n = workers() != NULL ? workers()->total_workers() : 1;
  3874   for (int i = 0; i < n; ++i) {
  3875     st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();
  3876     totals += task_queue(i)->stats;
  3878   st->print_raw("tot "); totals.print(st); st->cr();
  3880   DEBUG_ONLY(totals.verify());
  3883 void G1CollectedHeap::reset_taskqueue_stats() {
  3884   const int n = workers() != NULL ? workers()->total_workers() : 1;
  3885   for (int i = 0; i < n; ++i) {
  3886     task_queue(i)->stats.reset();
  3889 #endif // TASKQUEUE_STATS
  3891 void G1CollectedHeap::log_gc_header() {
  3892   if (!G1Log::fine()) {
  3893     return;
  3896   gclog_or_tty->gclog_stamp(_gc_tracer_stw->gc_id());
  3898   GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
  3899     .append(g1_policy()->gcs_are_young() ? "(young)" : "(mixed)")
  3900     .append(g1_policy()->during_initial_mark_pause() ? " (initial-mark)" : "");
  3902   gclog_or_tty->print("[%s", (const char*)gc_cause_str);
  3905 void G1CollectedHeap::log_gc_footer(double pause_time_sec) {
  3906   if (!G1Log::fine()) {
  3907     return;
  3910   if (G1Log::finer()) {
  3911     if (evacuation_failed()) {
  3912       gclog_or_tty->print(" (to-space exhausted)");
  3914     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
  3915     g1_policy()->phase_times()->note_gc_end();
  3916     g1_policy()->phase_times()->print(pause_time_sec);
  3917     g1_policy()->print_detailed_heap_transition();
  3918   } else {
  3919     if (evacuation_failed()) {
  3920       gclog_or_tty->print("--");
  3922     g1_policy()->print_heap_transition();
  3923     gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
  3925   gclog_or_tty->flush();
  3928 bool
  3929 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
  3930   assert_at_safepoint(true /* should_be_vm_thread */);
  3931   guarantee(!is_gc_active(), "collection is not reentrant");
  3933   if (GC_locker::check_active_before_gc()) {
  3934     return false;
  3937   _gc_timer_stw->register_gc_start();
  3939   _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
  3941   SvcGCMarker sgcm(SvcGCMarker::MINOR);
  3942   ResourceMark rm;
  3944   print_heap_before_gc();
  3945   trace_heap_before_gc(_gc_tracer_stw);
  3947   verify_region_sets_optional();
  3948   verify_dirty_young_regions();
  3950   // This call will decide whether this pause is an initial-mark
  3951   // pause. If it is, during_initial_mark_pause() will return true
  3952   // for the duration of this pause.
  3953   g1_policy()->decide_on_conc_mark_initiation();
  3955   // We do not allow initial-mark to be piggy-backed on a mixed GC.
  3956   assert(!g1_policy()->during_initial_mark_pause() ||
  3957           g1_policy()->gcs_are_young(), "sanity");
  3959   // We also do not allow mixed GCs during marking.
  3960   assert(!mark_in_progress() || g1_policy()->gcs_are_young(), "sanity");
  3962   // Record whether this pause is an initial mark. When the current
  3963   // thread has completed its logging output and it's safe to signal
  3964   // the CM thread, the flag's value in the policy has been reset.
  3965   bool should_start_conc_mark = g1_policy()->during_initial_mark_pause();
  3967   // Inner scope for scope based logging, timers, and stats collection
  3969     EvacuationInfo evacuation_info;
  3971     if (g1_policy()->during_initial_mark_pause()) {
  3972       // We are about to start a marking cycle, so we increment the
  3973       // full collection counter.
  3974       increment_old_marking_cycles_started();
  3975       register_concurrent_cycle_start(_gc_timer_stw->gc_start());
  3978     _gc_tracer_stw->report_yc_type(yc_type());
  3980     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
  3982     int active_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
  3983                                 workers()->active_workers() : 1);
  3984     double pause_start_sec = os::elapsedTime();
  3985     g1_policy()->phase_times()->note_gc_start(active_workers);
  3986     log_gc_header();
  3988     TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
  3989     TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
  3991     // If the secondary_free_list is not empty, append it to the
  3992     // free_list. No need to wait for the cleanup operation to finish;
  3993     // the region allocation code will check the secondary_free_list
  3994     // and wait if necessary. If the G1StressConcRegionFreeing flag is
  3995     // set, skip this step so that the region allocation code has to
  3996     // get entries from the secondary_free_list.
  3997     if (!G1StressConcRegionFreeing) {
  3998       append_secondary_free_list_if_not_empty_with_lock();
  4001     assert(check_young_list_well_formed(), "young list should be well formed");
  4002     assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  4003            "sanity check");
  4005     // Don't dynamically change the number of GC threads this early.  A value of
  4006     // 0 is used to indicate serial work.  When parallel work is done,
  4007     // it will be set.
  4009     { // Call to jvmpi::post_class_unload_events must occur outside of active GC
  4010       IsGCActiveMark x;
  4012       gc_prologue(false);
  4013       increment_total_collections(false /* full gc */);
  4014       increment_gc_time_stamp();
  4016       verify_before_gc();
  4018       COMPILER2_PRESENT(DerivedPointerTable::clear());
  4020       // Please see comment in g1CollectedHeap.hpp and
  4021       // G1CollectedHeap::ref_processing_init() to see how
  4022       // reference processing currently works in G1.
  4024       // Enable discovery in the STW reference processor
  4025       ref_processor_stw()->enable_discovery(true /*verify_disabled*/,
  4026                                             true /*verify_no_refs*/);
  4029         // We want to temporarily turn off discovery by the
  4030         // CM ref processor, if necessary, and turn it back on
  4031         // on again later if we do. Using a scoped
  4032         // NoRefDiscovery object will do this.
  4033         NoRefDiscovery no_cm_discovery(ref_processor_cm());
  4035         // Forget the current alloc region (we might even choose it to be part
  4036         // of the collection set!).
  4037         release_mutator_alloc_region();
  4039         // We should call this after we retire the mutator alloc
  4040         // region(s) so that all the ALLOC / RETIRE events are generated
  4041         // before the start GC event.
  4042         _hr_printer.start_gc(false /* full */, (size_t) total_collections());
  4044         // This timing is only used by the ergonomics to handle our pause target.
  4045         // It is unclear why this should not include the full pause. We will
  4046         // investigate this in CR 7178365.
  4047         //
  4048         // Preserving the old comment here if that helps the investigation:
  4049         //
  4050         // The elapsed time induced by the start time below deliberately elides
  4051         // the possible verification above.
  4052         double sample_start_time_sec = os::elapsedTime();
  4054 #if YOUNG_LIST_VERBOSE
  4055         gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
  4056         _young_list->print();
  4057         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
  4058 #endif // YOUNG_LIST_VERBOSE
  4060         g1_policy()->record_collection_pause_start(sample_start_time_sec);
  4062         double scan_wait_start = os::elapsedTime();
  4063         // We have to wait until the CM threads finish scanning the
  4064         // root regions as it's the only way to ensure that all the
  4065         // objects on them have been correctly scanned before we start
  4066         // moving them during the GC.
  4067         bool waited = _cm->root_regions()->wait_until_scan_finished();
  4068         double wait_time_ms = 0.0;
  4069         if (waited) {
  4070           double scan_wait_end = os::elapsedTime();
  4071           wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
  4073         g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms);
  4075 #if YOUNG_LIST_VERBOSE
  4076         gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
  4077         _young_list->print();
  4078 #endif // YOUNG_LIST_VERBOSE
  4080         if (g1_policy()->during_initial_mark_pause()) {
  4081           concurrent_mark()->checkpointRootsInitialPre();
  4084 #if YOUNG_LIST_VERBOSE
  4085         gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
  4086         _young_list->print();
  4087         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
  4088 #endif // YOUNG_LIST_VERBOSE
  4090         g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info);
  4092         _cm->note_start_of_gc();
  4093         // We should not verify the per-thread SATB buffers given that
  4094         // we have not filtered them yet (we'll do so during the
  4095         // GC). We also call this after finalize_cset() to
  4096         // ensure that the CSet has been finalized.
  4097         _cm->verify_no_cset_oops(true  /* verify_stacks */,
  4098                                  true  /* verify_enqueued_buffers */,
  4099                                  false /* verify_thread_buffers */,
  4100                                  true  /* verify_fingers */);
  4102         if (_hr_printer.is_active()) {
  4103           HeapRegion* hr = g1_policy()->collection_set();
  4104           while (hr != NULL) {
  4105             G1HRPrinter::RegionType type;
  4106             if (!hr->is_young()) {
  4107               type = G1HRPrinter::Old;
  4108             } else if (hr->is_survivor()) {
  4109               type = G1HRPrinter::Survivor;
  4110             } else {
  4111               type = G1HRPrinter::Eden;
  4113             _hr_printer.cset(hr);
  4114             hr = hr->next_in_collection_set();
  4118 #ifdef ASSERT
  4119         VerifyCSetClosure cl;
  4120         collection_set_iterate(&cl);
  4121 #endif // ASSERT
  4123         setup_surviving_young_words();
  4125         // Initialize the GC alloc regions.
  4126         init_gc_alloc_regions(evacuation_info);
  4128         // Actually do the work...
  4129         evacuate_collection_set(evacuation_info);
  4131         // We do this to mainly verify the per-thread SATB buffers
  4132         // (which have been filtered by now) since we didn't verify
  4133         // them earlier. No point in re-checking the stacks / enqueued
  4134         // buffers given that the CSet has not changed since last time
  4135         // we checked.
  4136         _cm->verify_no_cset_oops(false /* verify_stacks */,
  4137                                  false /* verify_enqueued_buffers */,
  4138                                  true  /* verify_thread_buffers */,
  4139                                  true  /* verify_fingers */);
  4141         free_collection_set(g1_policy()->collection_set(), evacuation_info);
  4142         g1_policy()->clear_collection_set();
  4144         cleanup_surviving_young_words();
  4146         // Start a new incremental collection set for the next pause.
  4147         g1_policy()->start_incremental_cset_building();
  4149         // Clear the _cset_fast_test bitmap in anticipation of adding
  4150         // regions to the incremental collection set for the next
  4151         // evacuation pause.
  4152         clear_cset_fast_test();
  4154         _young_list->reset_sampled_info();
  4156         // Don't check the whole heap at this point as the
  4157         // GC alloc regions from this pause have been tagged
  4158         // as survivors and moved on to the survivor list.
  4159         // Survivor regions will fail the !is_young() check.
  4160         assert(check_young_list_empty(false /* check_heap */),
  4161           "young list should be empty");
  4163 #if YOUNG_LIST_VERBOSE
  4164         gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
  4165         _young_list->print();
  4166 #endif // YOUNG_LIST_VERBOSE
  4168         g1_policy()->record_survivor_regions(_young_list->survivor_length(),
  4169                                              _young_list->first_survivor_region(),
  4170                                              _young_list->last_survivor_region());
  4172         _young_list->reset_auxilary_lists();
  4174         if (evacuation_failed()) {
  4175           _summary_bytes_used = recalculate_used();
  4176           uint n_queues = MAX2((int)ParallelGCThreads, 1);
  4177           for (uint i = 0; i < n_queues; i++) {
  4178             if (_evacuation_failed_info_array[i].has_failed()) {
  4179               _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
  4182         } else {
  4183           // The "used" of the the collection set have already been subtracted
  4184           // when they were freed.  Add in the bytes evacuated.
  4185           _summary_bytes_used += g1_policy()->bytes_copied_during_gc();
  4188         if (g1_policy()->during_initial_mark_pause()) {
  4189           // We have to do this before we notify the CM threads that
  4190           // they can start working to make sure that all the
  4191           // appropriate initialization is done on the CM object.
  4192           concurrent_mark()->checkpointRootsInitialPost();
  4193           set_marking_started();
  4194           // Note that we don't actually trigger the CM thread at
  4195           // this point. We do that later when we're sure that
  4196           // the current thread has completed its logging output.
  4199         allocate_dummy_regions();
  4201 #if YOUNG_LIST_VERBOSE
  4202         gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
  4203         _young_list->print();
  4204         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
  4205 #endif // YOUNG_LIST_VERBOSE
  4207         init_mutator_alloc_region();
  4210           size_t expand_bytes = g1_policy()->expansion_amount();
  4211           if (expand_bytes > 0) {
  4212             size_t bytes_before = capacity();
  4213             // No need for an ergo verbose message here,
  4214             // expansion_amount() does this when it returns a value > 0.
  4215             if (!expand(expand_bytes)) {
  4216               // We failed to expand the heap so let's verify that
  4217               // committed/uncommitted amount match the backing store
  4218               assert(capacity() == _g1_storage.committed_size(), "committed size mismatch");
  4219               assert(max_capacity() == _g1_storage.reserved_size(), "reserved size mismatch");
  4224         // We redo the verification but now wrt to the new CSet which
  4225         // has just got initialized after the previous CSet was freed.
  4226         _cm->verify_no_cset_oops(true  /* verify_stacks */,
  4227                                  true  /* verify_enqueued_buffers */,
  4228                                  true  /* verify_thread_buffers */,
  4229                                  true  /* verify_fingers */);
  4230         _cm->note_end_of_gc();
  4232         // This timing is only used by the ergonomics to handle our pause target.
  4233         // It is unclear why this should not include the full pause. We will
  4234         // investigate this in CR 7178365.
  4235         double sample_end_time_sec = os::elapsedTime();
  4236         double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
  4237         g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info);
  4239         MemoryService::track_memory_usage();
  4241         // In prepare_for_verify() below we'll need to scan the deferred
  4242         // update buffers to bring the RSets up-to-date if
  4243         // G1HRRSFlushLogBuffersOnVerify has been set. While scanning
  4244         // the update buffers we'll probably need to scan cards on the
  4245         // regions we just allocated to (i.e., the GC alloc
  4246         // regions). However, during the last GC we called
  4247         // set_saved_mark() on all the GC alloc regions, so card
  4248         // scanning might skip the [saved_mark_word()...top()] area of
  4249         // those regions (i.e., the area we allocated objects into
  4250         // during the last GC). But it shouldn't. Given that
  4251         // saved_mark_word() is conditional on whether the GC time stamp
  4252         // on the region is current or not, by incrementing the GC time
  4253         // stamp here we invalidate all the GC time stamps on all the
  4254         // regions and saved_mark_word() will simply return top() for
  4255         // all the regions. This is a nicer way of ensuring this rather
  4256         // than iterating over the regions and fixing them. In fact, the
  4257         // GC time stamp increment here also ensures that
  4258         // saved_mark_word() will return top() between pauses, i.e.,
  4259         // during concurrent refinement. So we don't need the
  4260         // is_gc_active() check to decided which top to use when
  4261         // scanning cards (see CR 7039627).
  4262         increment_gc_time_stamp();
  4264         verify_after_gc();
  4266         assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
  4267         ref_processor_stw()->verify_no_references_recorded();
  4269         // CM reference discovery will be re-enabled if necessary.
  4272       // We should do this after we potentially expand the heap so
  4273       // that all the COMMIT events are generated before the end GC
  4274       // event, and after we retire the GC alloc regions so that all
  4275       // RETIRE events are generated before the end GC event.
  4276       _hr_printer.end_gc(false /* full */, (size_t) total_collections());
  4278       if (mark_in_progress()) {
  4279         concurrent_mark()->update_g1_committed();
  4282 #ifdef TRACESPINNING
  4283       ParallelTaskTerminator::print_termination_counts();
  4284 #endif
  4286       gc_epilogue(false);
  4289     // Print the remainder of the GC log output.
  4290     log_gc_footer(os::elapsedTime() - pause_start_sec);
  4292     // It is not yet to safe to tell the concurrent mark to
  4293     // start as we have some optional output below. We don't want the
  4294     // output from the concurrent mark thread interfering with this
  4295     // logging output either.
  4297     _hrs.verify_optional();
  4298     verify_region_sets_optional();
  4300     TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());
  4301     TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
  4303     print_heap_after_gc();
  4304     trace_heap_after_gc(_gc_tracer_stw);
  4306     // We must call G1MonitoringSupport::update_sizes() in the same scoping level
  4307     // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
  4308     // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
  4309     // before any GC notifications are raised.
  4310     g1mm()->update_sizes();
  4312     _gc_tracer_stw->report_evacuation_info(&evacuation_info);
  4313     _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold());
  4314     _gc_timer_stw->register_gc_end();
  4315     _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());
  4317   // It should now be safe to tell the concurrent mark thread to start
  4318   // without its logging output interfering with the logging output
  4319   // that came from the pause.
  4321   if (should_start_conc_mark) {
  4322     // CAUTION: after the doConcurrentMark() call below,
  4323     // the concurrent marking thread(s) could be running
  4324     // concurrently with us. Make sure that anything after
  4325     // this point does not assume that we are the only GC thread
  4326     // running. Note: of course, the actual marking work will
  4327     // not start until the safepoint itself is released in
  4328     // ConcurrentGCThread::safepoint_desynchronize().
  4329     doConcurrentMark();
  4332   return true;
  4335 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose)
  4337   size_t gclab_word_size;
  4338   switch (purpose) {
  4339     case GCAllocForSurvived:
  4340       gclab_word_size = _survivor_plab_stats.desired_plab_sz();
  4341       break;
  4342     case GCAllocForTenured:
  4343       gclab_word_size = _old_plab_stats.desired_plab_sz();
  4344       break;
  4345     default:
  4346       assert(false, "unknown GCAllocPurpose");
  4347       gclab_word_size = _old_plab_stats.desired_plab_sz();
  4348       break;
  4351   // Prevent humongous PLAB sizes for two reasons:
  4352   // * PLABs are allocated using a similar paths as oops, but should
  4353   //   never be in a humongous region
  4354   // * Allowing humongous PLABs needlessly churns the region free lists
  4355   return MIN2(_humongous_object_threshold_in_words, gclab_word_size);
  4358 void G1CollectedHeap::init_mutator_alloc_region() {
  4359   assert(_mutator_alloc_region.get() == NULL, "pre-condition");
  4360   _mutator_alloc_region.init();
  4363 void G1CollectedHeap::release_mutator_alloc_region() {
  4364   _mutator_alloc_region.release();
  4365   assert(_mutator_alloc_region.get() == NULL, "post-condition");
  4368 void G1CollectedHeap::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
  4369   assert_at_safepoint(true /* should_be_vm_thread */);
  4371   _survivor_gc_alloc_region.init();
  4372   _old_gc_alloc_region.init();
  4373   HeapRegion* retained_region = _retained_old_gc_alloc_region;
  4374   _retained_old_gc_alloc_region = NULL;
  4376   // We will discard the current GC alloc region if:
  4377   // a) it's in the collection set (it can happen!),
  4378   // b) it's already full (no point in using it),
  4379   // c) it's empty (this means that it was emptied during
  4380   // a cleanup and it should be on the free list now), or
  4381   // d) it's humongous (this means that it was emptied
  4382   // during a cleanup and was added to the free list, but
  4383   // has been subsequently used to allocate a humongous
  4384   // object that may be less than the region size).
  4385   if (retained_region != NULL &&
  4386       !retained_region->in_collection_set() &&
  4387       !(retained_region->top() == retained_region->end()) &&
  4388       !retained_region->is_empty() &&
  4389       !retained_region->isHumongous()) {
  4390     retained_region->set_saved_mark();
  4391     // The retained region was added to the old region set when it was
  4392     // retired. We have to remove it now, since we don't allow regions
  4393     // we allocate to in the region sets. We'll re-add it later, when
  4394     // it's retired again.
  4395     _old_set.remove(retained_region);
  4396     bool during_im = g1_policy()->during_initial_mark_pause();
  4397     retained_region->note_start_of_copying(during_im);
  4398     _old_gc_alloc_region.set(retained_region);
  4399     _hr_printer.reuse(retained_region);
  4400     evacuation_info.set_alloc_regions_used_before(retained_region->used());
  4404 void G1CollectedHeap::release_gc_alloc_regions(uint no_of_gc_workers, EvacuationInfo& evacuation_info) {
  4405   evacuation_info.set_allocation_regions(_survivor_gc_alloc_region.count() +
  4406                                          _old_gc_alloc_region.count());
  4407   _survivor_gc_alloc_region.release();
  4408   // If we have an old GC alloc region to release, we'll save it in
  4409   // _retained_old_gc_alloc_region. If we don't
  4410   // _retained_old_gc_alloc_region will become NULL. This is what we
  4411   // want either way so no reason to check explicitly for either
  4412   // condition.
  4413   _retained_old_gc_alloc_region = _old_gc_alloc_region.release();
  4415   if (ResizePLAB) {
  4416     _survivor_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
  4417     _old_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
  4421 void G1CollectedHeap::abandon_gc_alloc_regions() {
  4422   assert(_survivor_gc_alloc_region.get() == NULL, "pre-condition");
  4423   assert(_old_gc_alloc_region.get() == NULL, "pre-condition");
  4424   _retained_old_gc_alloc_region = NULL;
  4427 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
  4428   _drain_in_progress = false;
  4429   set_evac_failure_closure(cl);
  4430   _evac_failure_scan_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true);
  4433 void G1CollectedHeap::finalize_for_evac_failure() {
  4434   assert(_evac_failure_scan_stack != NULL &&
  4435          _evac_failure_scan_stack->length() == 0,
  4436          "Postcondition");
  4437   assert(!_drain_in_progress, "Postcondition");
  4438   delete _evac_failure_scan_stack;
  4439   _evac_failure_scan_stack = NULL;
  4442 void G1CollectedHeap::remove_self_forwarding_pointers() {
  4443   assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
  4445   double remove_self_forwards_start = os::elapsedTime();
  4447   G1ParRemoveSelfForwardPtrsTask rsfp_task(this);
  4449   if (G1CollectedHeap::use_parallel_gc_threads()) {
  4450     set_par_threads();
  4451     workers()->run_task(&rsfp_task);
  4452     set_par_threads(0);
  4453   } else {
  4454     rsfp_task.work(0);
  4457   assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");
  4459   // Reset the claim values in the regions in the collection set.
  4460   reset_cset_heap_region_claim_values();
  4462   assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
  4464   // Now restore saved marks, if any.
  4465   assert(_objs_with_preserved_marks.size() ==
  4466             _preserved_marks_of_objs.size(), "Both or none.");
  4467   while (!_objs_with_preserved_marks.is_empty()) {
  4468     oop obj = _objs_with_preserved_marks.pop();
  4469     markOop m = _preserved_marks_of_objs.pop();
  4470     obj->set_mark(m);
  4472   _objs_with_preserved_marks.clear(true);
  4473   _preserved_marks_of_objs.clear(true);
  4475   g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0);
  4478 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
  4479   _evac_failure_scan_stack->push(obj);
  4482 void G1CollectedHeap::drain_evac_failure_scan_stack() {
  4483   assert(_evac_failure_scan_stack != NULL, "precondition");
  4485   while (_evac_failure_scan_stack->length() > 0) {
  4486      oop obj = _evac_failure_scan_stack->pop();
  4487      _evac_failure_closure->set_region(heap_region_containing(obj));
  4488      obj->oop_iterate_backwards(_evac_failure_closure);
  4492 oop
  4493 G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state,
  4494                                                oop old) {
  4495   assert(obj_in_cs(old),
  4496          err_msg("obj: "PTR_FORMAT" should still be in the CSet",
  4497                  (HeapWord*) old));
  4498   markOop m = old->mark();
  4499   oop forward_ptr = old->forward_to_atomic(old);
  4500   if (forward_ptr == NULL) {
  4501     // Forward-to-self succeeded.
  4502     assert(_par_scan_state != NULL, "par scan state");
  4503     OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
  4504     uint queue_num = _par_scan_state->queue_num();
  4506     _evacuation_failed = true;
  4507     _evacuation_failed_info_array[queue_num].register_copy_failure(old->size());
  4508     if (_evac_failure_closure != cl) {
  4509       MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
  4510       assert(!_drain_in_progress,
  4511              "Should only be true while someone holds the lock.");
  4512       // Set the global evac-failure closure to the current thread's.
  4513       assert(_evac_failure_closure == NULL, "Or locking has failed.");
  4514       set_evac_failure_closure(cl);
  4515       // Now do the common part.
  4516       handle_evacuation_failure_common(old, m);
  4517       // Reset to NULL.
  4518       set_evac_failure_closure(NULL);
  4519     } else {
  4520       // The lock is already held, and this is recursive.
  4521       assert(_drain_in_progress, "This should only be the recursive case.");
  4522       handle_evacuation_failure_common(old, m);
  4524     return old;
  4525   } else {
  4526     // Forward-to-self failed. Either someone else managed to allocate
  4527     // space for this object (old != forward_ptr) or they beat us in
  4528     // self-forwarding it (old == forward_ptr).
  4529     assert(old == forward_ptr || !obj_in_cs(forward_ptr),
  4530            err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" "
  4531                    "should not be in the CSet",
  4532                    (HeapWord*) old, (HeapWord*) forward_ptr));
  4533     return forward_ptr;
  4537 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
  4538   preserve_mark_if_necessary(old, m);
  4540   HeapRegion* r = heap_region_containing(old);
  4541   if (!r->evacuation_failed()) {
  4542     r->set_evacuation_failed(true);
  4543     _hr_printer.evac_failure(r);
  4546   push_on_evac_failure_scan_stack(old);
  4548   if (!_drain_in_progress) {
  4549     // prevent recursion in copy_to_survivor_space()
  4550     _drain_in_progress = true;
  4551     drain_evac_failure_scan_stack();
  4552     _drain_in_progress = false;
  4556 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
  4557   assert(evacuation_failed(), "Oversaving!");
  4558   // We want to call the "for_promotion_failure" version only in the
  4559   // case of a promotion failure.
  4560   if (m->must_be_preserved_for_promotion_failure(obj)) {
  4561     _objs_with_preserved_marks.push(obj);
  4562     _preserved_marks_of_objs.push(m);
  4566 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
  4567                                                   size_t word_size) {
  4568   if (purpose == GCAllocForSurvived) {
  4569     HeapWord* result = survivor_attempt_allocation(word_size);
  4570     if (result != NULL) {
  4571       return result;
  4572     } else {
  4573       // Let's try to allocate in the old gen in case we can fit the
  4574       // object there.
  4575       return old_attempt_allocation(word_size);
  4577   } else {
  4578     assert(purpose ==  GCAllocForTenured, "sanity");
  4579     HeapWord* result = old_attempt_allocation(word_size);
  4580     if (result != NULL) {
  4581       return result;
  4582     } else {
  4583       // Let's try to allocate in the survivors in case we can fit the
  4584       // object there.
  4585       return survivor_attempt_allocation(word_size);
  4589   ShouldNotReachHere();
  4590   // Trying to keep some compilers happy.
  4591   return NULL;
  4594 G1ParGCAllocBuffer::G1ParGCAllocBuffer(size_t gclab_word_size) :
  4595   ParGCAllocBuffer(gclab_word_size), _retired(false) { }
  4597 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp)
  4598   : _g1h(g1h),
  4599     _refs(g1h->task_queue(queue_num)),
  4600     _dcq(&g1h->dirty_card_queue_set()),
  4601     _ct_bs(g1h->g1_barrier_set()),
  4602     _g1_rem(g1h->g1_rem_set()),
  4603     _hash_seed(17), _queue_num(queue_num),
  4604     _term_attempts(0),
  4605     _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)),
  4606     _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)),
  4607     _age_table(false), _scanner(g1h, this, rp),
  4608     _strong_roots_time(0), _term_time(0),
  4609     _alloc_buffer_waste(0), _undo_waste(0) {
  4610   // we allocate G1YoungSurvRateNumRegions plus one entries, since
  4611   // we "sacrifice" entry 0 to keep track of surviving bytes for
  4612   // non-young regions (where the age is -1)
  4613   // We also add a few elements at the beginning and at the end in
  4614   // an attempt to eliminate cache contention
  4615   uint real_length = 1 + _g1h->g1_policy()->young_cset_region_length();
  4616   uint array_length = PADDING_ELEM_NUM +
  4617                       real_length +
  4618                       PADDING_ELEM_NUM;
  4619   _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length, mtGC);
  4620   if (_surviving_young_words_base == NULL)
  4621     vm_exit_out_of_memory(array_length * sizeof(size_t), OOM_MALLOC_ERROR,
  4622                           "Not enough space for young surv histo.");
  4623   _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
  4624   memset(_surviving_young_words, 0, (size_t) real_length * sizeof(size_t));
  4626   _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer;
  4627   _alloc_buffers[GCAllocForTenured]  = &_tenured_alloc_buffer;
  4629   _start = os::elapsedTime();
  4632 void
  4633 G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st)
  4635   st->print_raw_cr("GC Termination Stats");
  4636   st->print_raw_cr("     elapsed  --strong roots-- -------termination-------"
  4637                    " ------waste (KiB)------");
  4638   st->print_raw_cr("thr     ms        ms      %        ms      %    attempts"
  4639                    "  total   alloc    undo");
  4640   st->print_raw_cr("--- --------- --------- ------ --------- ------ --------"
  4641                    " ------- ------- -------");
  4644 void
  4645 G1ParScanThreadState::print_termination_stats(int i,
  4646                                               outputStream* const st) const
  4648   const double elapsed_ms = elapsed_time() * 1000.0;
  4649   const double s_roots_ms = strong_roots_time() * 1000.0;
  4650   const double term_ms    = term_time() * 1000.0;
  4651   st->print_cr("%3d %9.2f %9.2f %6.2f "
  4652                "%9.2f %6.2f " SIZE_FORMAT_W(8) " "
  4653                SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7),
  4654                i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
  4655                term_ms, term_ms * 100 / elapsed_ms, term_attempts(),
  4656                (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K,
  4657                alloc_buffer_waste() * HeapWordSize / K,
  4658                undo_waste() * HeapWordSize / K);
  4661 #ifdef ASSERT
  4662 bool G1ParScanThreadState::verify_ref(narrowOop* ref) const {
  4663   assert(ref != NULL, "invariant");
  4664   assert(UseCompressedOops, "sanity");
  4665   assert(!has_partial_array_mask(ref), err_msg("ref=" PTR_FORMAT, ref));
  4666   oop p = oopDesc::load_decode_heap_oop(ref);
  4667   assert(_g1h->is_in_g1_reserved(p),
  4668          err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
  4669   return true;
  4672 bool G1ParScanThreadState::verify_ref(oop* ref) const {
  4673   assert(ref != NULL, "invariant");
  4674   if (has_partial_array_mask(ref)) {
  4675     // Must be in the collection set--it's already been copied.
  4676     oop p = clear_partial_array_mask(ref);
  4677     assert(_g1h->obj_in_cs(p),
  4678            err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
  4679   } else {
  4680     oop p = oopDesc::load_decode_heap_oop(ref);
  4681     assert(_g1h->is_in_g1_reserved(p),
  4682            err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
  4684   return true;
  4687 bool G1ParScanThreadState::verify_task(StarTask ref) const {
  4688   if (ref.is_narrow()) {
  4689     return verify_ref((narrowOop*) ref);
  4690   } else {
  4691     return verify_ref((oop*) ref);
  4694 #endif // ASSERT
  4696 void G1ParScanThreadState::trim_queue() {
  4697   assert(_evac_failure_cl != NULL, "not set");
  4699   StarTask ref;
  4700   do {
  4701     // Drain the overflow stack first, so other threads can steal.
  4702     while (refs()->pop_overflow(ref)) {
  4703       deal_with_reference(ref);
  4706     while (refs()->pop_local(ref)) {
  4707       deal_with_reference(ref);
  4709   } while (!refs()->is_empty());
  4712 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1,
  4713                                      G1ParScanThreadState* par_scan_state) :
  4714   _g1(g1), _par_scan_state(par_scan_state),
  4715   _worker_id(par_scan_state->queue_num()) { }
  4717 void G1ParCopyHelper::mark_object(oop obj) {
  4718 #ifdef ASSERT
  4719   HeapRegion* hr = _g1->heap_region_containing(obj);
  4720   assert(hr != NULL, "sanity");
  4721   assert(!hr->in_collection_set(), "should not mark objects in the CSet");
  4722 #endif // ASSERT
  4724   // We know that the object is not moving so it's safe to read its size.
  4725   _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
  4728 void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) {
  4729 #ifdef ASSERT
  4730   assert(from_obj->is_forwarded(), "from obj should be forwarded");
  4731   assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");
  4732   assert(from_obj != to_obj, "should not be self-forwarded");
  4734   HeapRegion* from_hr = _g1->heap_region_containing(from_obj);
  4735   assert(from_hr != NULL, "sanity");
  4736   assert(from_hr->in_collection_set(), "from obj should be in the CSet");
  4738   HeapRegion* to_hr = _g1->heap_region_containing(to_obj);
  4739   assert(to_hr != NULL, "sanity");
  4740   assert(!to_hr->in_collection_set(), "should not mark objects in the CSet");
  4741 #endif // ASSERT
  4743   // The object might be in the process of being copied by another
  4744   // worker so we cannot trust that its to-space image is
  4745   // well-formed. So we have to read its size from its from-space
  4746   // image which we know should not be changing.
  4747   _cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);
  4750 oop G1ParScanThreadState::copy_to_survivor_space(oop const old) {
  4751   size_t word_sz = old->size();
  4752   HeapRegion* from_region = _g1h->heap_region_containing_raw(old);
  4753   // +1 to make the -1 indexes valid...
  4754   int       young_index = from_region->young_index_in_cset()+1;
  4755   assert( (from_region->is_young() && young_index >  0) ||
  4756          (!from_region->is_young() && young_index == 0), "invariant" );
  4757   G1CollectorPolicy* g1p = _g1h->g1_policy();
  4758   markOop m = old->mark();
  4759   int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
  4760                                            : m->age();
  4761   GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
  4762                                                              word_sz);
  4763   HeapWord* obj_ptr = allocate(alloc_purpose, word_sz);
  4764 #ifndef PRODUCT
  4765   // Should this evacuation fail?
  4766   if (_g1h->evacuation_should_fail()) {
  4767     if (obj_ptr != NULL) {
  4768       undo_allocation(alloc_purpose, obj_ptr, word_sz);
  4769       obj_ptr = NULL;
  4772 #endif // !PRODUCT
  4774   if (obj_ptr == NULL) {
  4775     // This will either forward-to-self, or detect that someone else has
  4776     // installed a forwarding pointer.
  4777     return _g1h->handle_evacuation_failure_par(this, old);
  4780   oop obj = oop(obj_ptr);
  4782   // We're going to allocate linearly, so might as well prefetch ahead.
  4783   Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
  4785   oop forward_ptr = old->forward_to_atomic(obj);
  4786   if (forward_ptr == NULL) {
  4787     Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
  4789     // alloc_purpose is just a hint to allocate() above, recheck the type of region
  4790     // we actually allocated from and update alloc_purpose accordingly
  4791     HeapRegion* to_region = _g1h->heap_region_containing_raw(obj_ptr);
  4792     alloc_purpose = to_region->is_young() ? GCAllocForSurvived : GCAllocForTenured;
  4794     if (g1p->track_object_age(alloc_purpose)) {
  4795       // We could simply do obj->incr_age(). However, this causes a
  4796       // performance issue. obj->incr_age() will first check whether
  4797       // the object has a displaced mark by checking its mark word;
  4798       // getting the mark word from the new location of the object
  4799       // stalls. So, given that we already have the mark word and we
  4800       // are about to install it anyway, it's better to increase the
  4801       // age on the mark word, when the object does not have a
  4802       // displaced mark word. We're not expecting many objects to have
  4803       // a displaced marked word, so that case is not optimized
  4804       // further (it could be...) and we simply call obj->incr_age().
  4806       if (m->has_displaced_mark_helper()) {
  4807         // in this case, we have to install the mark word first,
  4808         // otherwise obj looks to be forwarded (the old mark word,
  4809         // which contains the forward pointer, was copied)
  4810         obj->set_mark(m);
  4811         obj->incr_age();
  4812       } else {
  4813         m = m->incr_age();
  4814         obj->set_mark(m);
  4816       age_table()->add(obj, word_sz);
  4817     } else {
  4818       obj->set_mark(m);
  4821     if (G1StringDedup::is_enabled()) {
  4822       G1StringDedup::enqueue_from_evacuation(from_region->is_young(),
  4823                                              to_region->is_young(),
  4824                                              queue_num(),
  4825                                              obj);
  4828     size_t* surv_young_words = surviving_young_words();
  4829     surv_young_words[young_index] += word_sz;
  4831     if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
  4832       // We keep track of the next start index in the length field of
  4833       // the to-space object. The actual length can be found in the
  4834       // length field of the from-space object.
  4835       arrayOop(obj)->set_length(0);
  4836       oop* old_p = set_partial_array_mask(old);
  4837       push_on_queue(old_p);
  4838     } else {
  4839       // No point in using the slower heap_region_containing() method,
  4840       // given that we know obj is in the heap.
  4841       _scanner.set_region(_g1h->heap_region_containing_raw(obj));
  4842       obj->oop_iterate_backwards(&_scanner);
  4844   } else {
  4845     undo_allocation(alloc_purpose, obj_ptr, word_sz);
  4846     obj = forward_ptr;
  4848   return obj;
  4851 template <class T>
  4852 void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) {
  4853   if (_g1->heap_region_containing_raw(new_obj)->is_young()) {
  4854     _scanned_klass->record_modified_oops();
  4858 template <G1Barrier barrier, bool do_mark_object>
  4859 template <class T>
  4860 void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) {
  4861   T heap_oop = oopDesc::load_heap_oop(p);
  4863   if (oopDesc::is_null(heap_oop)) {
  4864     return;
  4867   oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  4869   assert(_worker_id == _par_scan_state->queue_num(), "sanity");
  4871   if (_g1->in_cset_fast_test(obj)) {
  4872     oop forwardee;
  4873     if (obj->is_forwarded()) {
  4874       forwardee = obj->forwardee();
  4875     } else {
  4876       forwardee = _par_scan_state->copy_to_survivor_space(obj);
  4878     assert(forwardee != NULL, "forwardee should not be NULL");
  4879     oopDesc::encode_store_heap_oop(p, forwardee);
  4880     if (do_mark_object && forwardee != obj) {
  4881       // If the object is self-forwarded we don't need to explicitly
  4882       // mark it, the evacuation failure protocol will do so.
  4883       mark_forwarded_object(obj, forwardee);
  4886     if (barrier == G1BarrierKlass) {
  4887       do_klass_barrier(p, forwardee);
  4889   } else {
  4890     // The object is not in collection set. If we're a root scanning
  4891     // closure during an initial mark pause (i.e. do_mark_object will
  4892     // be true) then attempt to mark the object.
  4893     if (do_mark_object) {
  4894       mark_object(obj);
  4898   if (barrier == G1BarrierEvac) {
  4899     _par_scan_state->update_rs(_from, p, _worker_id);
  4903 template void G1ParCopyClosure<G1BarrierEvac, false>::do_oop_work(oop* p);
  4904 template void G1ParCopyClosure<G1BarrierEvac, false>::do_oop_work(narrowOop* p);
  4906 class G1ParEvacuateFollowersClosure : public VoidClosure {
  4907 protected:
  4908   G1CollectedHeap*              _g1h;
  4909   G1ParScanThreadState*         _par_scan_state;
  4910   RefToScanQueueSet*            _queues;
  4911   ParallelTaskTerminator*       _terminator;
  4913   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
  4914   RefToScanQueueSet*      queues()         { return _queues; }
  4915   ParallelTaskTerminator* terminator()     { return _terminator; }
  4917 public:
  4918   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
  4919                                 G1ParScanThreadState* par_scan_state,
  4920                                 RefToScanQueueSet* queues,
  4921                                 ParallelTaskTerminator* terminator)
  4922     : _g1h(g1h), _par_scan_state(par_scan_state),
  4923       _queues(queues), _terminator(terminator) {}
  4925   void do_void();
  4927 private:
  4928   inline bool offer_termination();
  4929 };
  4931 bool G1ParEvacuateFollowersClosure::offer_termination() {
  4932   G1ParScanThreadState* const pss = par_scan_state();
  4933   pss->start_term_time();
  4934   const bool res = terminator()->offer_termination();
  4935   pss->end_term_time();
  4936   return res;
  4939 void G1ParEvacuateFollowersClosure::do_void() {
  4940   StarTask stolen_task;
  4941   G1ParScanThreadState* const pss = par_scan_state();
  4942   pss->trim_queue();
  4944   do {
  4945     while (queues()->steal(pss->queue_num(), pss->hash_seed(), stolen_task)) {
  4946       assert(pss->verify_task(stolen_task), "sanity");
  4947       if (stolen_task.is_narrow()) {
  4948         pss->deal_with_reference((narrowOop*) stolen_task);
  4949       } else {
  4950         pss->deal_with_reference((oop*) stolen_task);
  4953       // We've just processed a reference and we might have made
  4954       // available new entries on the queues. So we have to make sure
  4955       // we drain the queues as necessary.
  4956       pss->trim_queue();
  4958   } while (!offer_termination());
  4960   pss->retire_alloc_buffers();
  4963 class G1KlassScanClosure : public KlassClosure {
  4964  G1ParCopyHelper* _closure;
  4965  bool             _process_only_dirty;
  4966  int              _count;
  4967  public:
  4968   G1KlassScanClosure(G1ParCopyHelper* closure, bool process_only_dirty)
  4969       : _process_only_dirty(process_only_dirty), _closure(closure), _count(0) {}
  4970   void do_klass(Klass* klass) {
  4971     // If the klass has not been dirtied we know that there's
  4972     // no references into  the young gen and we can skip it.
  4973    if (!_process_only_dirty || klass->has_modified_oops()) {
  4974       // Clean the klass since we're going to scavenge all the metadata.
  4975       klass->clear_modified_oops();
  4977       // Tell the closure that this klass is the Klass to scavenge
  4978       // and is the one to dirty if oops are left pointing into the young gen.
  4979       _closure->set_scanned_klass(klass);
  4981       klass->oops_do(_closure);
  4983       _closure->set_scanned_klass(NULL);
  4985     _count++;
  4987 };
  4989 class G1ParTask : public AbstractGangTask {
  4990 protected:
  4991   G1CollectedHeap*       _g1h;
  4992   RefToScanQueueSet      *_queues;
  4993   ParallelTaskTerminator _terminator;
  4994   uint _n_workers;
  4996   Mutex _stats_lock;
  4997   Mutex* stats_lock() { return &_stats_lock; }
  4999   size_t getNCards() {
  5000     return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
  5001       / G1BlockOffsetSharedArray::N_bytes;
  5004 public:
  5005   G1ParTask(G1CollectedHeap* g1h,
  5006             RefToScanQueueSet *task_queues)
  5007     : AbstractGangTask("G1 collection"),
  5008       _g1h(g1h),
  5009       _queues(task_queues),
  5010       _terminator(0, _queues),
  5011       _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
  5012   {}
  5014   RefToScanQueueSet* queues() { return _queues; }
  5016   RefToScanQueue *work_queue(int i) {
  5017     return queues()->queue(i);
  5020   ParallelTaskTerminator* terminator() { return &_terminator; }
  5022   virtual void set_for_termination(int active_workers) {
  5023     // This task calls set_n_termination() in par_non_clean_card_iterate_work()
  5024     // in the young space (_par_seq_tasks) in the G1 heap
  5025     // for SequentialSubTasksDone.
  5026     // This task also uses SubTasksDone in SharedHeap and G1CollectedHeap
  5027     // both of which need setting by set_n_termination().
  5028     _g1h->SharedHeap::set_n_termination(active_workers);
  5029     _g1h->set_n_termination(active_workers);
  5030     terminator()->reset_for_reuse(active_workers);
  5031     _n_workers = active_workers;
  5034   void work(uint worker_id) {
  5035     if (worker_id >= _n_workers) return;  // no work needed this round
  5037     double start_time_ms = os::elapsedTime() * 1000.0;
  5038     _g1h->g1_policy()->phase_times()->record_gc_worker_start_time(worker_id, start_time_ms);
  5041       ResourceMark rm;
  5042       HandleMark   hm;
  5044       ReferenceProcessor*             rp = _g1h->ref_processor_stw();
  5046       G1ParScanThreadState            pss(_g1h, worker_id, rp);
  5047       G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, rp);
  5049       pss.set_evac_failure_closure(&evac_failure_cl);
  5051       G1ParScanExtRootClosure        only_scan_root_cl(_g1h, &pss, rp);
  5052       G1ParScanMetadataClosure       only_scan_metadata_cl(_g1h, &pss, rp);
  5054       G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss, rp);
  5055       G1ParScanAndMarkMetadataClosure scan_mark_metadata_cl(_g1h, &pss, rp);
  5057       bool only_young                 = _g1h->g1_policy()->gcs_are_young();
  5058       G1KlassScanClosure              scan_mark_klasses_cl_s(&scan_mark_metadata_cl, false);
  5059       G1KlassScanClosure              only_scan_klasses_cl_s(&only_scan_metadata_cl, only_young);
  5061       OopClosure*                    scan_root_cl = &only_scan_root_cl;
  5062       G1KlassScanClosure*            scan_klasses_cl = &only_scan_klasses_cl_s;
  5064       if (_g1h->g1_policy()->during_initial_mark_pause()) {
  5065         // We also need to mark copied objects.
  5066         scan_root_cl = &scan_mark_root_cl;
  5067         scan_klasses_cl = &scan_mark_klasses_cl_s;
  5070       G1ParPushHeapRSClosure          push_heap_rs_cl(_g1h, &pss);
  5072       // Don't scan the scavengable methods in the code cache as part
  5073       // of strong root scanning. The code roots that point into a
  5074       // region in the collection set are scanned when we scan the
  5075       // region's RSet.
  5076       int so = SharedHeap::SO_AllClasses | SharedHeap::SO_Strings;
  5078       pss.start_strong_roots();
  5079       _g1h->g1_process_strong_roots(/* is scavenging */ true,
  5080                                     SharedHeap::ScanningOption(so),
  5081                                     scan_root_cl,
  5082                                     &push_heap_rs_cl,
  5083                                     scan_klasses_cl,
  5084                                     worker_id);
  5085       pss.end_strong_roots();
  5088         double start = os::elapsedTime();
  5089         G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
  5090         evac.do_void();
  5091         double elapsed_ms = (os::elapsedTime()-start)*1000.0;
  5092         double term_ms = pss.term_time()*1000.0;
  5093         _g1h->g1_policy()->phase_times()->add_obj_copy_time(worker_id, elapsed_ms-term_ms);
  5094         _g1h->g1_policy()->phase_times()->record_termination(worker_id, term_ms, pss.term_attempts());
  5096       _g1h->g1_policy()->record_thread_age_table(pss.age_table());
  5097       _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
  5099       if (ParallelGCVerbose) {
  5100         MutexLocker x(stats_lock());
  5101         pss.print_termination_stats(worker_id);
  5104       assert(pss.refs()->is_empty(), "should be empty");
  5106       // Close the inner scope so that the ResourceMark and HandleMark
  5107       // destructors are executed here and are included as part of the
  5108       // "GC Worker Time".
  5111     double end_time_ms = os::elapsedTime() * 1000.0;
  5112     _g1h->g1_policy()->phase_times()->record_gc_worker_end_time(worker_id, end_time_ms);
  5114 };
  5116 // *** Common G1 Evacuation Stuff
  5118 // This method is run in a GC worker.
  5120 void
  5121 G1CollectedHeap::
  5122 g1_process_strong_roots(bool is_scavenging,
  5123                         ScanningOption so,
  5124                         OopClosure* scan_non_heap_roots,
  5125                         OopsInHeapRegionClosure* scan_rs,
  5126                         G1KlassScanClosure* scan_klasses,
  5127                         uint worker_i) {
  5129   // First scan the strong roots
  5130   double ext_roots_start = os::elapsedTime();
  5131   double closure_app_time_sec = 0.0;
  5133   BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
  5135   assert(so & SO_CodeCache || scan_rs != NULL, "must scan code roots somehow");
  5136   // Walk the code cache/strong code roots w/o buffering, because StarTask
  5137   // cannot handle unaligned oop locations.
  5138   CodeBlobToOopClosure eager_scan_code_roots(scan_non_heap_roots, true /* do_marking */);
  5140   process_strong_roots(false, // no scoping; this is parallel code
  5141                        is_scavenging, so,
  5142                        &buf_scan_non_heap_roots,
  5143                        &eager_scan_code_roots,
  5144                        scan_klasses
  5145                        );
  5147   // Now the CM ref_processor roots.
  5148   if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
  5149     // We need to treat the discovered reference lists of the
  5150     // concurrent mark ref processor as roots and keep entries
  5151     // (which are added by the marking threads) on them live
  5152     // until they can be processed at the end of marking.
  5153     ref_processor_cm()->weak_oops_do(&buf_scan_non_heap_roots);
  5156   // Finish up any enqueued closure apps (attributed as object copy time).
  5157   buf_scan_non_heap_roots.done();
  5159   double obj_copy_time_sec = buf_scan_non_heap_roots.closure_app_seconds();
  5161   g1_policy()->phase_times()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
  5163   double ext_root_time_ms =
  5164     ((os::elapsedTime() - ext_roots_start) - obj_copy_time_sec) * 1000.0;
  5166   g1_policy()->phase_times()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
  5168   // During conc marking we have to filter the per-thread SATB buffers
  5169   // to make sure we remove any oops into the CSet (which will show up
  5170   // as implicitly live).
  5171   double satb_filtering_ms = 0.0;
  5172   if (!_process_strong_tasks->is_task_claimed(G1H_PS_filter_satb_buffers)) {
  5173     if (mark_in_progress()) {
  5174       double satb_filter_start = os::elapsedTime();
  5176       JavaThread::satb_mark_queue_set().filter_thread_buffers();
  5178       satb_filtering_ms = (os::elapsedTime() - satb_filter_start) * 1000.0;
  5181   g1_policy()->phase_times()->record_satb_filtering_time(worker_i, satb_filtering_ms);
  5183   // If this is an initial mark pause, and we're not scanning
  5184   // the entire code cache, we need to mark the oops in the
  5185   // strong code root lists for the regions that are not in
  5186   // the collection set.
  5187   // Note all threads participate in this set of root tasks.
  5188   double mark_strong_code_roots_ms = 0.0;
  5189   if (g1_policy()->during_initial_mark_pause() && !(so & SO_CodeCache)) {
  5190     double mark_strong_roots_start = os::elapsedTime();
  5191     mark_strong_code_roots(worker_i);
  5192     mark_strong_code_roots_ms = (os::elapsedTime() - mark_strong_roots_start) * 1000.0;
  5194   g1_policy()->phase_times()->record_strong_code_root_mark_time(worker_i, mark_strong_code_roots_ms);
  5196   // Now scan the complement of the collection set.
  5197   if (scan_rs != NULL) {
  5198     g1_rem_set()->oops_into_collection_set_do(scan_rs, &eager_scan_code_roots, worker_i);
  5200   _process_strong_tasks->all_tasks_completed();
  5203 void
  5204 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure) {
  5205   CodeBlobToOopClosure roots_in_blobs(root_closure, /*do_marking=*/ false);
  5206   SharedHeap::process_weak_roots(root_closure, &roots_in_blobs);
  5209 class G1StringSymbolTableUnlinkTask : public AbstractGangTask {
  5210 private:
  5211   BoolObjectClosure* _is_alive;
  5212   int _initial_string_table_size;
  5213   int _initial_symbol_table_size;
  5215   bool  _process_strings;
  5216   int _strings_processed;
  5217   int _strings_removed;
  5219   bool  _process_symbols;
  5220   int _symbols_processed;
  5221   int _symbols_removed;
  5223   bool _do_in_parallel;
  5224 public:
  5225   G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :
  5226     AbstractGangTask("Par String/Symbol table unlink"), _is_alive(is_alive),
  5227     _do_in_parallel(G1CollectedHeap::use_parallel_gc_threads()),
  5228     _process_strings(process_strings), _strings_processed(0), _strings_removed(0),
  5229     _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {
  5231     _initial_string_table_size = StringTable::the_table()->table_size();
  5232     _initial_symbol_table_size = SymbolTable::the_table()->table_size();
  5233     if (process_strings) {
  5234       StringTable::clear_parallel_claimed_index();
  5236     if (process_symbols) {
  5237       SymbolTable::clear_parallel_claimed_index();
  5241   ~G1StringSymbolTableUnlinkTask() {
  5242     guarantee(!_process_strings || !_do_in_parallel || StringTable::parallel_claimed_index() >= _initial_string_table_size,
  5243               err_msg("claim value "INT32_FORMAT" after unlink less than initial string table size "INT32_FORMAT,
  5244                       StringTable::parallel_claimed_index(), _initial_string_table_size));
  5245     guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
  5246               err_msg("claim value "INT32_FORMAT" after unlink less than initial symbol table size "INT32_FORMAT,
  5247                       SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
  5250   void work(uint worker_id) {
  5251     if (_do_in_parallel) {
  5252       int strings_processed = 0;
  5253       int strings_removed = 0;
  5254       int symbols_processed = 0;
  5255       int symbols_removed = 0;
  5256       if (_process_strings) {
  5257         StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed);
  5258         Atomic::add(strings_processed, &_strings_processed);
  5259         Atomic::add(strings_removed, &_strings_removed);
  5261       if (_process_symbols) {
  5262         SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed);
  5263         Atomic::add(symbols_processed, &_symbols_processed);
  5264         Atomic::add(symbols_removed, &_symbols_removed);
  5266     } else {
  5267       if (_process_strings) {
  5268         StringTable::unlink(_is_alive, &_strings_processed, &_strings_removed);
  5270       if (_process_symbols) {
  5271         SymbolTable::unlink(&_symbols_processed, &_symbols_removed);
  5276   size_t strings_processed() const { return (size_t)_strings_processed; }
  5277   size_t strings_removed()   const { return (size_t)_strings_removed; }
  5279   size_t symbols_processed() const { return (size_t)_symbols_processed; }
  5280   size_t symbols_removed()   const { return (size_t)_symbols_removed; }
  5281 };
  5283 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
  5284                                                      bool process_strings, bool process_symbols) {
  5285   uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
  5286                    _g1h->workers()->active_workers() : 1);
  5288   G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
  5289   if (G1CollectedHeap::use_parallel_gc_threads()) {
  5290     set_par_threads(n_workers);
  5291     workers()->run_task(&g1_unlink_task);
  5292     set_par_threads(0);
  5293   } else {
  5294     g1_unlink_task.work(0);
  5296   if (G1TraceStringSymbolTableScrubbing) {
  5297     gclog_or_tty->print_cr("Cleaned string and symbol table, "
  5298                            "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
  5299                            "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
  5300                            g1_unlink_task.strings_processed(), g1_unlink_task.strings_removed(),
  5301                            g1_unlink_task.symbols_processed(), g1_unlink_task.symbols_removed());
  5304   if (G1StringDedup::is_enabled()) {
  5305     G1StringDedup::unlink(is_alive);
  5309 class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
  5310 public:
  5311   bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
  5312     *card_ptr = CardTableModRefBS::dirty_card_val();
  5313     return true;
  5315 };
  5317 void G1CollectedHeap::redirty_logged_cards() {
  5318   guarantee(G1DeferredRSUpdate, "Must only be called when using deferred RS updates.");
  5319   double redirty_logged_cards_start = os::elapsedTime();
  5321   RedirtyLoggedCardTableEntryFastClosure redirty;
  5322   dirty_card_queue_set().set_closure(&redirty);
  5323   dirty_card_queue_set().apply_closure_to_all_completed_buffers();
  5325   DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
  5326   dcq.merge_bufferlists(&dirty_card_queue_set());
  5327   assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
  5329   g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0);
  5332 // Weak Reference Processing support
  5334 // An always "is_alive" closure that is used to preserve referents.
  5335 // If the object is non-null then it's alive.  Used in the preservation
  5336 // of referent objects that are pointed to by reference objects
  5337 // discovered by the CM ref processor.
  5338 class G1AlwaysAliveClosure: public BoolObjectClosure {
  5339   G1CollectedHeap* _g1;
  5340 public:
  5341   G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
  5342   bool do_object_b(oop p) {
  5343     if (p != NULL) {
  5344       return true;
  5346     return false;
  5348 };
  5350 bool G1STWIsAliveClosure::do_object_b(oop p) {
  5351   // An object is reachable if it is outside the collection set,
  5352   // or is inside and copied.
  5353   return !_g1->obj_in_cs(p) || p->is_forwarded();
  5356 // Non Copying Keep Alive closure
  5357 class G1KeepAliveClosure: public OopClosure {
  5358   G1CollectedHeap* _g1;
  5359 public:
  5360   G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
  5361   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
  5362   void do_oop(      oop* p) {
  5363     oop obj = *p;
  5365     if (_g1->obj_in_cs(obj)) {
  5366       assert( obj->is_forwarded(), "invariant" );
  5367       *p = obj->forwardee();
  5370 };
  5372 // Copying Keep Alive closure - can be called from both
  5373 // serial and parallel code as long as different worker
  5374 // threads utilize different G1ParScanThreadState instances
  5375 // and different queues.
  5377 class G1CopyingKeepAliveClosure: public OopClosure {
  5378   G1CollectedHeap*         _g1h;
  5379   OopClosure*              _copy_non_heap_obj_cl;
  5380   OopsInHeapRegionClosure* _copy_metadata_obj_cl;
  5381   G1ParScanThreadState*    _par_scan_state;
  5383 public:
  5384   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
  5385                             OopClosure* non_heap_obj_cl,
  5386                             OopsInHeapRegionClosure* metadata_obj_cl,
  5387                             G1ParScanThreadState* pss):
  5388     _g1h(g1h),
  5389     _copy_non_heap_obj_cl(non_heap_obj_cl),
  5390     _copy_metadata_obj_cl(metadata_obj_cl),
  5391     _par_scan_state(pss)
  5392   {}
  5394   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
  5395   virtual void do_oop(      oop* p) { do_oop_work(p); }
  5397   template <class T> void do_oop_work(T* p) {
  5398     oop obj = oopDesc::load_decode_heap_oop(p);
  5400     if (_g1h->obj_in_cs(obj)) {
  5401       // If the referent object has been forwarded (either copied
  5402       // to a new location or to itself in the event of an
  5403       // evacuation failure) then we need to update the reference
  5404       // field and, if both reference and referent are in the G1
  5405       // heap, update the RSet for the referent.
  5406       //
  5407       // If the referent has not been forwarded then we have to keep
  5408       // it alive by policy. Therefore we have copy the referent.
  5409       //
  5410       // If the reference field is in the G1 heap then we can push
  5411       // on the PSS queue. When the queue is drained (after each
  5412       // phase of reference processing) the object and it's followers
  5413       // will be copied, the reference field set to point to the
  5414       // new location, and the RSet updated. Otherwise we need to
  5415       // use the the non-heap or metadata closures directly to copy
  5416       // the referent object and update the pointer, while avoiding
  5417       // updating the RSet.
  5419       if (_g1h->is_in_g1_reserved(p)) {
  5420         _par_scan_state->push_on_queue(p);
  5421       } else {
  5422         assert(!Metaspace::contains((const void*)p),
  5423                err_msg("Otherwise need to call _copy_metadata_obj_cl->do_oop(p) "
  5424                               PTR_FORMAT, p));
  5425           _copy_non_heap_obj_cl->do_oop(p);
  5429 };
  5431 // Serial drain queue closure. Called as the 'complete_gc'
  5432 // closure for each discovered list in some of the
  5433 // reference processing phases.
  5435 class G1STWDrainQueueClosure: public VoidClosure {
  5436 protected:
  5437   G1CollectedHeap* _g1h;
  5438   G1ParScanThreadState* _par_scan_state;
  5440   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
  5442 public:
  5443   G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
  5444     _g1h(g1h),
  5445     _par_scan_state(pss)
  5446   { }
  5448   void do_void() {
  5449     G1ParScanThreadState* const pss = par_scan_state();
  5450     pss->trim_queue();
  5452 };
  5454 // Parallel Reference Processing closures
  5456 // Implementation of AbstractRefProcTaskExecutor for parallel reference
  5457 // processing during G1 evacuation pauses.
  5459 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
  5460 private:
  5461   G1CollectedHeap*   _g1h;
  5462   RefToScanQueueSet* _queues;
  5463   FlexibleWorkGang*  _workers;
  5464   int                _active_workers;
  5466 public:
  5467   G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
  5468                         FlexibleWorkGang* workers,
  5469                         RefToScanQueueSet *task_queues,
  5470                         int n_workers) :
  5471     _g1h(g1h),
  5472     _queues(task_queues),
  5473     _workers(workers),
  5474     _active_workers(n_workers)
  5476     assert(n_workers > 0, "shouldn't call this otherwise");
  5479   // Executes the given task using concurrent marking worker threads.
  5480   virtual void execute(ProcessTask& task);
  5481   virtual void execute(EnqueueTask& task);
  5482 };
  5484 // Gang task for possibly parallel reference processing
  5486 class G1STWRefProcTaskProxy: public AbstractGangTask {
  5487   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
  5488   ProcessTask&     _proc_task;
  5489   G1CollectedHeap* _g1h;
  5490   RefToScanQueueSet *_task_queues;
  5491   ParallelTaskTerminator* _terminator;
  5493 public:
  5494   G1STWRefProcTaskProxy(ProcessTask& proc_task,
  5495                      G1CollectedHeap* g1h,
  5496                      RefToScanQueueSet *task_queues,
  5497                      ParallelTaskTerminator* terminator) :
  5498     AbstractGangTask("Process reference objects in parallel"),
  5499     _proc_task(proc_task),
  5500     _g1h(g1h),
  5501     _task_queues(task_queues),
  5502     _terminator(terminator)
  5503   {}
  5505   virtual void work(uint worker_id) {
  5506     // The reference processing task executed by a single worker.
  5507     ResourceMark rm;
  5508     HandleMark   hm;
  5510     G1STWIsAliveClosure is_alive(_g1h);
  5512     G1ParScanThreadState            pss(_g1h, worker_id, NULL);
  5513     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
  5515     pss.set_evac_failure_closure(&evac_failure_cl);
  5517     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
  5518     G1ParScanMetadataClosure       only_copy_metadata_cl(_g1h, &pss, NULL);
  5520     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
  5521     G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(_g1h, &pss, NULL);
  5523     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
  5524     OopsInHeapRegionClosure*       copy_metadata_cl = &only_copy_metadata_cl;
  5526     if (_g1h->g1_policy()->during_initial_mark_pause()) {
  5527       // We also need to mark copied objects.
  5528       copy_non_heap_cl = &copy_mark_non_heap_cl;
  5529       copy_metadata_cl = &copy_mark_metadata_cl;
  5532     // Keep alive closure.
  5533     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_metadata_cl, &pss);
  5535     // Complete GC closure
  5536     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);
  5538     // Call the reference processing task's work routine.
  5539     _proc_task.work(worker_id, is_alive, keep_alive, drain_queue);
  5541     // Note we cannot assert that the refs array is empty here as not all
  5542     // of the processing tasks (specifically phase2 - pp2_work) execute
  5543     // the complete_gc closure (which ordinarily would drain the queue) so
  5544     // the queue may not be empty.
  5546 };
  5548 // Driver routine for parallel reference processing.
  5549 // Creates an instance of the ref processing gang
  5550 // task and has the worker threads execute it.
  5551 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {
  5552   assert(_workers != NULL, "Need parallel worker threads.");
  5554   ParallelTaskTerminator terminator(_active_workers, _queues);
  5555   G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator);
  5557   _g1h->set_par_threads(_active_workers);
  5558   _workers->run_task(&proc_task_proxy);
  5559   _g1h->set_par_threads(0);
  5562 // Gang task for parallel reference enqueueing.
  5564 class G1STWRefEnqueueTaskProxy: public AbstractGangTask {
  5565   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
  5566   EnqueueTask& _enq_task;
  5568 public:
  5569   G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) :
  5570     AbstractGangTask("Enqueue reference objects in parallel"),
  5571     _enq_task(enq_task)
  5572   { }
  5574   virtual void work(uint worker_id) {
  5575     _enq_task.work(worker_id);
  5577 };
  5579 // Driver routine for parallel reference enqueueing.
  5580 // Creates an instance of the ref enqueueing gang
  5581 // task and has the worker threads execute it.
  5583 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
  5584   assert(_workers != NULL, "Need parallel worker threads.");
  5586   G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task);
  5588   _g1h->set_par_threads(_active_workers);
  5589   _workers->run_task(&enq_task_proxy);
  5590   _g1h->set_par_threads(0);
  5593 // End of weak reference support closures
  5595 // Abstract task used to preserve (i.e. copy) any referent objects
  5596 // that are in the collection set and are pointed to by reference
  5597 // objects discovered by the CM ref processor.
  5599 class G1ParPreserveCMReferentsTask: public AbstractGangTask {
  5600 protected:
  5601   G1CollectedHeap* _g1h;
  5602   RefToScanQueueSet      *_queues;
  5603   ParallelTaskTerminator _terminator;
  5604   uint _n_workers;
  5606 public:
  5607   G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h,int workers, RefToScanQueueSet *task_queues) :
  5608     AbstractGangTask("ParPreserveCMReferents"),
  5609     _g1h(g1h),
  5610     _queues(task_queues),
  5611     _terminator(workers, _queues),
  5612     _n_workers(workers)
  5613   { }
  5615   void work(uint worker_id) {
  5616     ResourceMark rm;
  5617     HandleMark   hm;
  5619     G1ParScanThreadState            pss(_g1h, worker_id, NULL);
  5620     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
  5622     pss.set_evac_failure_closure(&evac_failure_cl);
  5624     assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
  5627     G1ParScanExtRootClosure        only_copy_non_heap_cl(_g1h, &pss, NULL);
  5628     G1ParScanMetadataClosure       only_copy_metadata_cl(_g1h, &pss, NULL);
  5630     G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
  5631     G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(_g1h, &pss, NULL);
  5633     OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
  5634     OopsInHeapRegionClosure*       copy_metadata_cl = &only_copy_metadata_cl;
  5636     if (_g1h->g1_policy()->during_initial_mark_pause()) {
  5637       // We also need to mark copied objects.
  5638       copy_non_heap_cl = &copy_mark_non_heap_cl;
  5639       copy_metadata_cl = &copy_mark_metadata_cl;
  5642     // Is alive closure
  5643     G1AlwaysAliveClosure always_alive(_g1h);
  5645     // Copying keep alive closure. Applied to referent objects that need
  5646     // to be copied.
  5647     G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_metadata_cl, &pss);
  5649     ReferenceProcessor* rp = _g1h->ref_processor_cm();
  5651     uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q();
  5652     uint stride = MIN2(MAX2(_n_workers, 1U), limit);
  5654     // limit is set using max_num_q() - which was set using ParallelGCThreads.
  5655     // So this must be true - but assert just in case someone decides to
  5656     // change the worker ids.
  5657     assert(0 <= worker_id && worker_id < limit, "sanity");
  5658     assert(!rp->discovery_is_atomic(), "check this code");
  5660     // Select discovered lists [i, i+stride, i+2*stride,...,limit)
  5661     for (uint idx = worker_id; idx < limit; idx += stride) {
  5662       DiscoveredList& ref_list = rp->discovered_refs()[idx];
  5664       DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive);
  5665       while (iter.has_next()) {
  5666         // Since discovery is not atomic for the CM ref processor, we
  5667         // can see some null referent objects.
  5668         iter.load_ptrs(DEBUG_ONLY(true));
  5669         oop ref = iter.obj();
  5671         // This will filter nulls.
  5672         if (iter.is_referent_alive()) {
  5673           iter.make_referent_alive();
  5675         iter.move_to_next();
  5679     // Drain the queue - which may cause stealing
  5680     G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);
  5681     drain_queue.do_void();
  5682     // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure
  5683     assert(pss.refs()->is_empty(), "should be");
  5685 };
  5687 // Weak Reference processing during an evacuation pause (part 1).
  5688 void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
  5689   double ref_proc_start = os::elapsedTime();
  5691   ReferenceProcessor* rp = _ref_processor_stw;
  5692   assert(rp->discovery_enabled(), "should have been enabled");
  5694   // Any reference objects, in the collection set, that were 'discovered'
  5695   // by the CM ref processor should have already been copied (either by
  5696   // applying the external root copy closure to the discovered lists, or
  5697   // by following an RSet entry).
  5698   //
  5699   // But some of the referents, that are in the collection set, that these
  5700   // reference objects point to may not have been copied: the STW ref
  5701   // processor would have seen that the reference object had already
  5702   // been 'discovered' and would have skipped discovering the reference,
  5703   // but would not have treated the reference object as a regular oop.
  5704   // As a result the copy closure would not have been applied to the
  5705   // referent object.
  5706   //
  5707   // We need to explicitly copy these referent objects - the references
  5708   // will be processed at the end of remarking.
  5709   //
  5710   // We also need to do this copying before we process the reference
  5711   // objects discovered by the STW ref processor in case one of these
  5712   // referents points to another object which is also referenced by an
  5713   // object discovered by the STW ref processor.
  5715   assert(!G1CollectedHeap::use_parallel_gc_threads() ||
  5716            no_of_gc_workers == workers()->active_workers(),
  5717            "Need to reset active GC workers");
  5719   set_par_threads(no_of_gc_workers);
  5720   G1ParPreserveCMReferentsTask keep_cm_referents(this,
  5721                                                  no_of_gc_workers,
  5722                                                  _task_queues);
  5724   if (G1CollectedHeap::use_parallel_gc_threads()) {
  5725     workers()->run_task(&keep_cm_referents);
  5726   } else {
  5727     keep_cm_referents.work(0);
  5730   set_par_threads(0);
  5732   // Closure to test whether a referent is alive.
  5733   G1STWIsAliveClosure is_alive(this);
  5735   // Even when parallel reference processing is enabled, the processing
  5736   // of JNI refs is serial and performed serially by the current thread
  5737   // rather than by a worker. The following PSS will be used for processing
  5738   // JNI refs.
  5740   // Use only a single queue for this PSS.
  5741   G1ParScanThreadState            pss(this, 0, NULL);
  5743   // We do not embed a reference processor in the copying/scanning
  5744   // closures while we're actually processing the discovered
  5745   // reference objects.
  5746   G1ParScanHeapEvacFailureClosure evac_failure_cl(this, &pss, NULL);
  5748   pss.set_evac_failure_closure(&evac_failure_cl);
  5750   assert(pss.refs()->is_empty(), "pre-condition");
  5752   G1ParScanExtRootClosure        only_copy_non_heap_cl(this, &pss, NULL);
  5753   G1ParScanMetadataClosure       only_copy_metadata_cl(this, &pss, NULL);
  5755   G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);
  5756   G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(this, &pss, NULL);
  5758   OopClosure*                    copy_non_heap_cl = &only_copy_non_heap_cl;
  5759   OopsInHeapRegionClosure*       copy_metadata_cl = &only_copy_metadata_cl;
  5761   if (_g1h->g1_policy()->during_initial_mark_pause()) {
  5762     // We also need to mark copied objects.
  5763     copy_non_heap_cl = &copy_mark_non_heap_cl;
  5764     copy_metadata_cl = &copy_mark_metadata_cl;
  5767   // Keep alive closure.
  5768   G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, copy_metadata_cl, &pss);
  5770   // Serial Complete GC closure
  5771   G1STWDrainQueueClosure drain_queue(this, &pss);
  5773   // Setup the soft refs policy...
  5774   rp->setup_policy(false);
  5776   ReferenceProcessorStats stats;
  5777   if (!rp->processing_is_mt()) {
  5778     // Serial reference processing...
  5779     stats = rp->process_discovered_references(&is_alive,
  5780                                               &keep_alive,
  5781                                               &drain_queue,
  5782                                               NULL,
  5783                                               _gc_timer_stw,
  5784                                               _gc_tracer_stw->gc_id());
  5785   } else {
  5786     // Parallel reference processing
  5787     assert(rp->num_q() == no_of_gc_workers, "sanity");
  5788     assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
  5790     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
  5791     stats = rp->process_discovered_references(&is_alive,
  5792                                               &keep_alive,
  5793                                               &drain_queue,
  5794                                               &par_task_executor,
  5795                                               _gc_timer_stw,
  5796                                               _gc_tracer_stw->gc_id());
  5799   _gc_tracer_stw->report_gc_reference_stats(stats);
  5800   // We have completed copying any necessary live referent objects
  5801   // (that were not copied during the actual pause) so we can
  5802   // retire any active alloc buffers
  5803   pss.retire_alloc_buffers();
  5804   assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
  5806   double ref_proc_time = os::elapsedTime() - ref_proc_start;
  5807   g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
  5810 // Weak Reference processing during an evacuation pause (part 2).
  5811 void G1CollectedHeap::enqueue_discovered_references(uint no_of_gc_workers) {
  5812   double ref_enq_start = os::elapsedTime();
  5814   ReferenceProcessor* rp = _ref_processor_stw;
  5815   assert(!rp->discovery_enabled(), "should have been disabled as part of processing");
  5817   // Now enqueue any remaining on the discovered lists on to
  5818   // the pending list.
  5819   if (!rp->processing_is_mt()) {
  5820     // Serial reference processing...
  5821     rp->enqueue_discovered_references();
  5822   } else {
  5823     // Parallel reference enqueueing
  5825     assert(no_of_gc_workers == workers()->active_workers(),
  5826            "Need to reset active workers");
  5827     assert(rp->num_q() == no_of_gc_workers, "sanity");
  5828     assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
  5830     G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
  5831     rp->enqueue_discovered_references(&par_task_executor);
  5834   rp->verify_no_references_recorded();
  5835   assert(!rp->discovery_enabled(), "should have been disabled");
  5837   // FIXME
  5838   // CM's reference processing also cleans up the string and symbol tables.
  5839   // Should we do that here also? We could, but it is a serial operation
  5840   // and could significantly increase the pause time.
  5842   double ref_enq_time = os::elapsedTime() - ref_enq_start;
  5843   g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0);
  5846 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {
  5847   _expand_heap_after_alloc_failure = true;
  5848   _evacuation_failed = false;
  5850   // Should G1EvacuationFailureALot be in effect for this GC?
  5851   NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
  5853   g1_rem_set()->prepare_for_oops_into_collection_set_do();
  5855   // Disable the hot card cache.
  5856   G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
  5857   hot_card_cache->reset_hot_cache_claimed_index();
  5858   hot_card_cache->set_use_cache(false);
  5860   uint n_workers;
  5861   if (G1CollectedHeap::use_parallel_gc_threads()) {
  5862     n_workers =
  5863       AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
  5864                                      workers()->active_workers(),
  5865                                      Threads::number_of_non_daemon_threads());
  5866     assert(UseDynamicNumberOfGCThreads ||
  5867            n_workers == workers()->total_workers(),
  5868            "If not dynamic should be using all the  workers");
  5869     workers()->set_active_workers(n_workers);
  5870     set_par_threads(n_workers);
  5871   } else {
  5872     assert(n_par_threads() == 0,
  5873            "Should be the original non-parallel value");
  5874     n_workers = 1;
  5877   G1ParTask g1_par_task(this, _task_queues);
  5879   init_for_evac_failure(NULL);
  5881   rem_set()->prepare_for_younger_refs_iterate(true);
  5883   assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
  5884   double start_par_time_sec = os::elapsedTime();
  5885   double end_par_time_sec;
  5888     StrongRootsScope srs(this);
  5890     if (G1CollectedHeap::use_parallel_gc_threads()) {
  5891       // The individual threads will set their evac-failure closures.
  5892       if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();
  5893       // These tasks use ShareHeap::_process_strong_tasks
  5894       assert(UseDynamicNumberOfGCThreads ||
  5895              workers()->active_workers() == workers()->total_workers(),
  5896              "If not dynamic should be using all the  workers");
  5897       workers()->run_task(&g1_par_task);
  5898     } else {
  5899       g1_par_task.set_for_termination(n_workers);
  5900       g1_par_task.work(0);
  5902     end_par_time_sec = os::elapsedTime();
  5904     // Closing the inner scope will execute the destructor
  5905     // for the StrongRootsScope object. We record the current
  5906     // elapsed time before closing the scope so that time
  5907     // taken for the SRS destructor is NOT included in the
  5908     // reported parallel time.
  5911   double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0;
  5912   g1_policy()->phase_times()->record_par_time(par_time_ms);
  5914   double code_root_fixup_time_ms =
  5915         (os::elapsedTime() - end_par_time_sec) * 1000.0;
  5916   g1_policy()->phase_times()->record_code_root_fixup_time(code_root_fixup_time_ms);
  5918   set_par_threads(0);
  5920   // Process any discovered reference objects - we have
  5921   // to do this _before_ we retire the GC alloc regions
  5922   // as we may have to copy some 'reachable' referent
  5923   // objects (and their reachable sub-graphs) that were
  5924   // not copied during the pause.
  5925   process_discovered_references(n_workers);
  5927   // Weak root processing.
  5929     G1STWIsAliveClosure is_alive(this);
  5930     G1KeepAliveClosure keep_alive(this);
  5931     JNIHandles::weak_oops_do(&is_alive, &keep_alive);
  5932     if (G1StringDedup::is_enabled()) {
  5933       G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive);
  5937   release_gc_alloc_regions(n_workers, evacuation_info);
  5938   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
  5940   // Reset and re-enable the hot card cache.
  5941   // Note the counts for the cards in the regions in the
  5942   // collection set are reset when the collection set is freed.
  5943   hot_card_cache->reset_hot_cache();
  5944   hot_card_cache->set_use_cache(true);
  5946   // Migrate the strong code roots attached to each region in
  5947   // the collection set. Ideally we would like to do this
  5948   // after we have finished the scanning/evacuation of the
  5949   // strong code roots for a particular heap region.
  5950   migrate_strong_code_roots();
  5952   purge_code_root_memory();
  5954   if (g1_policy()->during_initial_mark_pause()) {
  5955     // Reset the claim values set during marking the strong code roots
  5956     reset_heap_region_claim_values();
  5959   finalize_for_evac_failure();
  5961   if (evacuation_failed()) {
  5962     remove_self_forwarding_pointers();
  5964     // Reset the G1EvacuationFailureALot counters and flags
  5965     // Note: the values are reset only when an actual
  5966     // evacuation failure occurs.
  5967     NOT_PRODUCT(reset_evacuation_should_fail();)
  5970   // Enqueue any remaining references remaining on the STW
  5971   // reference processor's discovered lists. We need to do
  5972   // this after the card table is cleaned (and verified) as
  5973   // the act of enqueueing entries on to the pending list
  5974   // will log these updates (and dirty their associated
  5975   // cards). We need these updates logged to update any
  5976   // RSets.
  5977   enqueue_discovered_references(n_workers);
  5979   if (G1DeferredRSUpdate) {
  5980     redirty_logged_cards();
  5982   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
  5985 void G1CollectedHeap::free_region(HeapRegion* hr,
  5986                                   FreeRegionList* free_list,
  5987                                   bool par,
  5988                                   bool locked) {
  5989   assert(!hr->isHumongous(), "this is only for non-humongous regions");
  5990   assert(!hr->is_empty(), "the region should not be empty");
  5991   assert(free_list != NULL, "pre-condition");
  5993   // Clear the card counts for this region.
  5994   // Note: we only need to do this if the region is not young
  5995   // (since we don't refine cards in young regions).
  5996   if (!hr->is_young()) {
  5997     _cg1r->hot_card_cache()->reset_card_counts(hr);
  5999   hr->hr_clear(par, true /* clear_space */, locked /* locked */);
  6000   free_list->add_ordered(hr);
  6003 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
  6004                                      FreeRegionList* free_list,
  6005                                      bool par) {
  6006   assert(hr->startsHumongous(), "this is only for starts humongous regions");
  6007   assert(free_list != NULL, "pre-condition");
  6009   size_t hr_capacity = hr->capacity();
  6010   // We need to read this before we make the region non-humongous,
  6011   // otherwise the information will be gone.
  6012   uint last_index = hr->last_hc_index();
  6013   hr->set_notHumongous();
  6014   free_region(hr, free_list, par);
  6016   uint i = hr->hrs_index() + 1;
  6017   while (i < last_index) {
  6018     HeapRegion* curr_hr = region_at(i);
  6019     assert(curr_hr->continuesHumongous(), "invariant");
  6020     curr_hr->set_notHumongous();
  6021     free_region(curr_hr, free_list, par);
  6022     i += 1;
  6026 void G1CollectedHeap::remove_from_old_sets(const HeapRegionSetCount& old_regions_removed,
  6027                                        const HeapRegionSetCount& humongous_regions_removed) {
  6028   if (old_regions_removed.length() > 0 || humongous_regions_removed.length() > 0) {
  6029     MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
  6030     _old_set.bulk_remove(old_regions_removed);
  6031     _humongous_set.bulk_remove(humongous_regions_removed);
  6036 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
  6037   assert(list != NULL, "list can't be null");
  6038   if (!list->is_empty()) {
  6039     MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
  6040     _free_list.add_ordered(list);
  6044 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
  6045   assert(_summary_bytes_used >= bytes,
  6046          err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" should be >= bytes: "SIZE_FORMAT,
  6047                   _summary_bytes_used, bytes));
  6048   _summary_bytes_used -= bytes;
  6051 class G1ParCleanupCTTask : public AbstractGangTask {
  6052   G1SATBCardTableModRefBS* _ct_bs;
  6053   G1CollectedHeap* _g1h;
  6054   HeapRegion* volatile _su_head;
  6055 public:
  6056   G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs,
  6057                      G1CollectedHeap* g1h) :
  6058     AbstractGangTask("G1 Par Cleanup CT Task"),
  6059     _ct_bs(ct_bs), _g1h(g1h) { }
  6061   void work(uint worker_id) {
  6062     HeapRegion* r;
  6063     while (r = _g1h->pop_dirty_cards_region()) {
  6064       clear_cards(r);
  6068   void clear_cards(HeapRegion* r) {
  6069     // Cards of the survivors should have already been dirtied.
  6070     if (!r->is_survivor()) {
  6071       _ct_bs->clear(MemRegion(r->bottom(), r->end()));
  6074 };
  6076 #ifndef PRODUCT
  6077 class G1VerifyCardTableCleanup: public HeapRegionClosure {
  6078   G1CollectedHeap* _g1h;
  6079   G1SATBCardTableModRefBS* _ct_bs;
  6080 public:
  6081   G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs)
  6082     : _g1h(g1h), _ct_bs(ct_bs) { }
  6083   virtual bool doHeapRegion(HeapRegion* r) {
  6084     if (r->is_survivor()) {
  6085       _g1h->verify_dirty_region(r);
  6086     } else {
  6087       _g1h->verify_not_dirty_region(r);
  6089     return false;
  6091 };
  6093 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {
  6094   // All of the region should be clean.
  6095   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
  6096   MemRegion mr(hr->bottom(), hr->end());
  6097   ct_bs->verify_not_dirty_region(mr);
  6100 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {
  6101   // We cannot guarantee that [bottom(),end()] is dirty.  Threads
  6102   // dirty allocated blocks as they allocate them. The thread that
  6103   // retires each region and replaces it with a new one will do a
  6104   // maximal allocation to fill in [pre_dummy_top(),end()] but will
  6105   // not dirty that area (one less thing to have to do while holding
  6106   // a lock). So we can only verify that [bottom(),pre_dummy_top()]
  6107   // is dirty.
  6108   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
  6109   MemRegion mr(hr->bottom(), hr->pre_dummy_top());
  6110   if (hr->is_young()) {
  6111     ct_bs->verify_g1_young_region(mr);
  6112   } else {
  6113     ct_bs->verify_dirty_region(mr);
  6117 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {
  6118   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
  6119   for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {
  6120     verify_dirty_region(hr);
  6124 void G1CollectedHeap::verify_dirty_young_regions() {
  6125   verify_dirty_young_list(_young_list->first_region());
  6127 #endif
  6129 void G1CollectedHeap::cleanUpCardTable() {
  6130   G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
  6131   double start = os::elapsedTime();
  6134     // Iterate over the dirty cards region list.
  6135     G1ParCleanupCTTask cleanup_task(ct_bs, this);
  6137     if (G1CollectedHeap::use_parallel_gc_threads()) {
  6138       set_par_threads();
  6139       workers()->run_task(&cleanup_task);
  6140       set_par_threads(0);
  6141     } else {
  6142       while (_dirty_cards_region_list) {
  6143         HeapRegion* r = _dirty_cards_region_list;
  6144         cleanup_task.clear_cards(r);
  6145         _dirty_cards_region_list = r->get_next_dirty_cards_region();
  6146         if (_dirty_cards_region_list == r) {
  6147           // The last region.
  6148           _dirty_cards_region_list = NULL;
  6150         r->set_next_dirty_cards_region(NULL);
  6153 #ifndef PRODUCT
  6154     if (G1VerifyCTCleanup || VerifyAfterGC) {
  6155       G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
  6156       heap_region_iterate(&cleanup_verifier);
  6158 #endif
  6161   double elapsed = os::elapsedTime() - start;
  6162   g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0);
  6165 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) {
  6166   size_t pre_used = 0;
  6167   FreeRegionList local_free_list("Local List for CSet Freeing");
  6169   double young_time_ms     = 0.0;
  6170   double non_young_time_ms = 0.0;
  6172   // Since the collection set is a superset of the the young list,
  6173   // all we need to do to clear the young list is clear its
  6174   // head and length, and unlink any young regions in the code below
  6175   _young_list->clear();
  6177   G1CollectorPolicy* policy = g1_policy();
  6179   double start_sec = os::elapsedTime();
  6180   bool non_young = true;
  6182   HeapRegion* cur = cs_head;
  6183   int age_bound = -1;
  6184   size_t rs_lengths = 0;
  6186   while (cur != NULL) {
  6187     assert(!is_on_master_free_list(cur), "sanity");
  6188     if (non_young) {
  6189       if (cur->is_young()) {
  6190         double end_sec = os::elapsedTime();
  6191         double elapsed_ms = (end_sec - start_sec) * 1000.0;
  6192         non_young_time_ms += elapsed_ms;
  6194         start_sec = os::elapsedTime();
  6195         non_young = false;
  6197     } else {
  6198       if (!cur->is_young()) {
  6199         double end_sec = os::elapsedTime();
  6200         double elapsed_ms = (end_sec - start_sec) * 1000.0;
  6201         young_time_ms += elapsed_ms;
  6203         start_sec = os::elapsedTime();
  6204         non_young = true;
  6208     rs_lengths += cur->rem_set()->occupied_locked();
  6210     HeapRegion* next = cur->next_in_collection_set();
  6211     assert(cur->in_collection_set(), "bad CS");
  6212     cur->set_next_in_collection_set(NULL);
  6213     cur->set_in_collection_set(false);
  6215     if (cur->is_young()) {
  6216       int index = cur->young_index_in_cset();
  6217       assert(index != -1, "invariant");
  6218       assert((uint) index < policy->young_cset_region_length(), "invariant");
  6219       size_t words_survived = _surviving_young_words[index];
  6220       cur->record_surv_words_in_group(words_survived);
  6222       // At this point the we have 'popped' cur from the collection set
  6223       // (linked via next_in_collection_set()) but it is still in the
  6224       // young list (linked via next_young_region()). Clear the
  6225       // _next_young_region field.
  6226       cur->set_next_young_region(NULL);
  6227     } else {
  6228       int index = cur->young_index_in_cset();
  6229       assert(index == -1, "invariant");
  6232     assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
  6233             (!cur->is_young() && cur->young_index_in_cset() == -1),
  6234             "invariant" );
  6236     if (!cur->evacuation_failed()) {
  6237       MemRegion used_mr = cur->used_region();
  6239       // And the region is empty.
  6240       assert(!used_mr.is_empty(), "Should not have empty regions in a CS.");
  6241       pre_used += cur->used();
  6242       free_region(cur, &local_free_list, false /* par */, true /* locked */);
  6243     } else {
  6244       cur->uninstall_surv_rate_group();
  6245       if (cur->is_young()) {
  6246         cur->set_young_index_in_cset(-1);
  6248       cur->set_not_young();
  6249       cur->set_evacuation_failed(false);
  6250       // The region is now considered to be old.
  6251       _old_set.add(cur);
  6252       evacuation_info.increment_collectionset_used_after(cur->used());
  6254     cur = next;
  6257   evacuation_info.set_regions_freed(local_free_list.length());
  6258   policy->record_max_rs_lengths(rs_lengths);
  6259   policy->cset_regions_freed();
  6261   double end_sec = os::elapsedTime();
  6262   double elapsed_ms = (end_sec - start_sec) * 1000.0;
  6264   if (non_young) {
  6265     non_young_time_ms += elapsed_ms;
  6266   } else {
  6267     young_time_ms += elapsed_ms;
  6270   prepend_to_freelist(&local_free_list);
  6271   decrement_summary_bytes(pre_used);
  6272   policy->phase_times()->record_young_free_cset_time_ms(young_time_ms);
  6273   policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms);
  6276 // This routine is similar to the above but does not record
  6277 // any policy statistics or update free lists; we are abandoning
  6278 // the current incremental collection set in preparation of a
  6279 // full collection. After the full GC we will start to build up
  6280 // the incremental collection set again.
  6281 // This is only called when we're doing a full collection
  6282 // and is immediately followed by the tearing down of the young list.
  6284 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
  6285   HeapRegion* cur = cs_head;
  6287   while (cur != NULL) {
  6288     HeapRegion* next = cur->next_in_collection_set();
  6289     assert(cur->in_collection_set(), "bad CS");
  6290     cur->set_next_in_collection_set(NULL);
  6291     cur->set_in_collection_set(false);
  6292     cur->set_young_index_in_cset(-1);
  6293     cur = next;
  6297 void G1CollectedHeap::set_free_regions_coming() {
  6298   if (G1ConcRegionFreeingVerbose) {
  6299     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
  6300                            "setting free regions coming");
  6303   assert(!free_regions_coming(), "pre-condition");
  6304   _free_regions_coming = true;
  6307 void G1CollectedHeap::reset_free_regions_coming() {
  6308   assert(free_regions_coming(), "pre-condition");
  6311     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
  6312     _free_regions_coming = false;
  6313     SecondaryFreeList_lock->notify_all();
  6316   if (G1ConcRegionFreeingVerbose) {
  6317     gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
  6318                            "reset free regions coming");
  6322 void G1CollectedHeap::wait_while_free_regions_coming() {
  6323   // Most of the time we won't have to wait, so let's do a quick test
  6324   // first before we take the lock.
  6325   if (!free_regions_coming()) {
  6326     return;
  6329   if (G1ConcRegionFreeingVerbose) {
  6330     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
  6331                            "waiting for free regions");
  6335     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
  6336     while (free_regions_coming()) {
  6337       SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
  6341   if (G1ConcRegionFreeingVerbose) {
  6342     gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
  6343                            "done waiting for free regions");
  6347 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
  6348   assert(heap_lock_held_for_gc(),
  6349               "the heap lock should already be held by or for this thread");
  6350   _young_list->push_region(hr);
  6353 class NoYoungRegionsClosure: public HeapRegionClosure {
  6354 private:
  6355   bool _success;
  6356 public:
  6357   NoYoungRegionsClosure() : _success(true) { }
  6358   bool doHeapRegion(HeapRegion* r) {
  6359     if (r->is_young()) {
  6360       gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
  6361                              r->bottom(), r->end());
  6362       _success = false;
  6364     return false;
  6366   bool success() { return _success; }
  6367 };
  6369 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
  6370   bool ret = _young_list->check_list_empty(check_sample);
  6372   if (check_heap) {
  6373     NoYoungRegionsClosure closure;
  6374     heap_region_iterate(&closure);
  6375     ret = ret && closure.success();
  6378   return ret;
  6381 class TearDownRegionSetsClosure : public HeapRegionClosure {
  6382 private:
  6383   HeapRegionSet *_old_set;
  6385 public:
  6386   TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }
  6388   bool doHeapRegion(HeapRegion* r) {
  6389     if (r->is_empty()) {
  6390       // We ignore empty regions, we'll empty the free list afterwards
  6391     } else if (r->is_young()) {
  6392       // We ignore young regions, we'll empty the young list afterwards
  6393     } else if (r->isHumongous()) {
  6394       // We ignore humongous regions, we're not tearing down the
  6395       // humongous region set
  6396     } else {
  6397       // The rest should be old
  6398       _old_set->remove(r);
  6400     return false;
  6403   ~TearDownRegionSetsClosure() {
  6404     assert(_old_set->is_empty(), "post-condition");
  6406 };
  6408 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {
  6409   assert_at_safepoint(true /* should_be_vm_thread */);
  6411   if (!free_list_only) {
  6412     TearDownRegionSetsClosure cl(&_old_set);
  6413     heap_region_iterate(&cl);
  6415     // Note that emptying the _young_list is postponed and instead done as
  6416     // the first step when rebuilding the regions sets again. The reason for
  6417     // this is that during a full GC string deduplication needs to know if
  6418     // a collected region was young or old when the full GC was initiated.
  6420   _free_list.remove_all();
  6423 class RebuildRegionSetsClosure : public HeapRegionClosure {
  6424 private:
  6425   bool            _free_list_only;
  6426   HeapRegionSet*   _old_set;
  6427   FreeRegionList* _free_list;
  6428   size_t          _total_used;
  6430 public:
  6431   RebuildRegionSetsClosure(bool free_list_only,
  6432                            HeapRegionSet* old_set, FreeRegionList* free_list) :
  6433     _free_list_only(free_list_only),
  6434     _old_set(old_set), _free_list(free_list), _total_used(0) {
  6435     assert(_free_list->is_empty(), "pre-condition");
  6436     if (!free_list_only) {
  6437       assert(_old_set->is_empty(), "pre-condition");
  6441   bool doHeapRegion(HeapRegion* r) {
  6442     if (r->continuesHumongous()) {
  6443       return false;
  6446     if (r->is_empty()) {
  6447       // Add free regions to the free list
  6448       _free_list->add_as_tail(r);
  6449     } else if (!_free_list_only) {
  6450       assert(!r->is_young(), "we should not come across young regions");
  6452       if (r->isHumongous()) {
  6453         // We ignore humongous regions, we left the humongous set unchanged
  6454       } else {
  6455         // The rest should be old, add them to the old set
  6456         _old_set->add(r);
  6458       _total_used += r->used();
  6461     return false;
  6464   size_t total_used() {
  6465     return _total_used;
  6467 };
  6469 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
  6470   assert_at_safepoint(true /* should_be_vm_thread */);
  6472   if (!free_list_only) {
  6473     _young_list->empty_list();
  6476   RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_free_list);
  6477   heap_region_iterate(&cl);
  6479   if (!free_list_only) {
  6480     _summary_bytes_used = cl.total_used();
  6482   assert(_summary_bytes_used == recalculate_used(),
  6483          err_msg("inconsistent _summary_bytes_used, "
  6484                  "value: "SIZE_FORMAT" recalculated: "SIZE_FORMAT,
  6485                  _summary_bytes_used, recalculate_used()));
  6488 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
  6489   _refine_cte_cl->set_concurrent(concurrent);
  6492 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
  6493   HeapRegion* hr = heap_region_containing(p);
  6494   if (hr == NULL) {
  6495     return false;
  6496   } else {
  6497     return hr->is_in(p);
  6501 // Methods for the mutator alloc region
  6503 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
  6504                                                       bool force) {
  6505   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
  6506   assert(!force || g1_policy()->can_expand_young_list(),
  6507          "if force is true we should be able to expand the young list");
  6508   bool young_list_full = g1_policy()->is_young_list_full();
  6509   if (force || !young_list_full) {
  6510     HeapRegion* new_alloc_region = new_region(word_size,
  6511                                               false /* is_old */,
  6512                                               false /* do_expand */);
  6513     if (new_alloc_region != NULL) {
  6514       set_region_short_lived_locked(new_alloc_region);
  6515       _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
  6516       return new_alloc_region;
  6519   return NULL;
  6522 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
  6523                                                   size_t allocated_bytes) {
  6524   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
  6525   assert(alloc_region->is_young(), "all mutator alloc regions should be young");
  6527   g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
  6528   _summary_bytes_used += allocated_bytes;
  6529   _hr_printer.retire(alloc_region);
  6530   // We update the eden sizes here, when the region is retired,
  6531   // instead of when it's allocated, since this is the point that its
  6532   // used space has been recored in _summary_bytes_used.
  6533   g1mm()->update_eden_size();
  6536 HeapRegion* MutatorAllocRegion::allocate_new_region(size_t word_size,
  6537                                                     bool force) {
  6538   return _g1h->new_mutator_alloc_region(word_size, force);
  6541 void G1CollectedHeap::set_par_threads() {
  6542   // Don't change the number of workers.  Use the value previously set
  6543   // in the workgroup.
  6544   assert(G1CollectedHeap::use_parallel_gc_threads(), "shouldn't be here otherwise");
  6545   uint n_workers = workers()->active_workers();
  6546   assert(UseDynamicNumberOfGCThreads ||
  6547            n_workers == workers()->total_workers(),
  6548       "Otherwise should be using the total number of workers");
  6549   if (n_workers == 0) {
  6550     assert(false, "Should have been set in prior evacuation pause.");
  6551     n_workers = ParallelGCThreads;
  6552     workers()->set_active_workers(n_workers);
  6554   set_par_threads(n_workers);
  6557 void MutatorAllocRegion::retire_region(HeapRegion* alloc_region,
  6558                                        size_t allocated_bytes) {
  6559   _g1h->retire_mutator_alloc_region(alloc_region, allocated_bytes);
  6562 // Methods for the GC alloc regions
  6564 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,
  6565                                                  uint count,
  6566                                                  GCAllocPurpose ap) {
  6567   assert(FreeList_lock->owned_by_self(), "pre-condition");
  6569   if (count < g1_policy()->max_regions(ap)) {
  6570     bool survivor = (ap == GCAllocForSurvived);
  6571     HeapRegion* new_alloc_region = new_region(word_size,
  6572                                               !survivor,
  6573                                               true /* do_expand */);
  6574     if (new_alloc_region != NULL) {
  6575       // We really only need to do this for old regions given that we
  6576       // should never scan survivors. But it doesn't hurt to do it
  6577       // for survivors too.
  6578       new_alloc_region->set_saved_mark();
  6579       if (survivor) {
  6580         new_alloc_region->set_survivor();
  6581         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
  6582       } else {
  6583         _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
  6585       bool during_im = g1_policy()->during_initial_mark_pause();
  6586       new_alloc_region->note_start_of_copying(during_im);
  6587       return new_alloc_region;
  6588     } else {
  6589       g1_policy()->note_alloc_region_limit_reached(ap);
  6592   return NULL;
  6595 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
  6596                                              size_t allocated_bytes,
  6597                                              GCAllocPurpose ap) {
  6598   bool during_im = g1_policy()->during_initial_mark_pause();
  6599   alloc_region->note_end_of_copying(during_im);
  6600   g1_policy()->record_bytes_copied_during_gc(allocated_bytes);
  6601   if (ap == GCAllocForSurvived) {
  6602     young_list()->add_survivor_region(alloc_region);
  6603   } else {
  6604     _old_set.add(alloc_region);
  6606   _hr_printer.retire(alloc_region);
  6609 HeapRegion* SurvivorGCAllocRegion::allocate_new_region(size_t word_size,
  6610                                                        bool force) {
  6611   assert(!force, "not supported for GC alloc regions");
  6612   return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForSurvived);
  6615 void SurvivorGCAllocRegion::retire_region(HeapRegion* alloc_region,
  6616                                           size_t allocated_bytes) {
  6617   _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
  6618                                GCAllocForSurvived);
  6621 HeapRegion* OldGCAllocRegion::allocate_new_region(size_t word_size,
  6622                                                   bool force) {
  6623   assert(!force, "not supported for GC alloc regions");
  6624   return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForTenured);
  6627 void OldGCAllocRegion::retire_region(HeapRegion* alloc_region,
  6628                                      size_t allocated_bytes) {
  6629   _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
  6630                                GCAllocForTenured);
  6632 // Heap region set verification
  6634 class VerifyRegionListsClosure : public HeapRegionClosure {
  6635 private:
  6636   HeapRegionSet*   _old_set;
  6637   HeapRegionSet*   _humongous_set;
  6638   FreeRegionList*  _free_list;
  6640 public:
  6641   HeapRegionSetCount _old_count;
  6642   HeapRegionSetCount _humongous_count;
  6643   HeapRegionSetCount _free_count;
  6645   VerifyRegionListsClosure(HeapRegionSet* old_set,
  6646                            HeapRegionSet* humongous_set,
  6647                            FreeRegionList* free_list) :
  6648     _old_set(old_set), _humongous_set(humongous_set), _free_list(free_list),
  6649     _old_count(), _humongous_count(), _free_count(){ }
  6651   bool doHeapRegion(HeapRegion* hr) {
  6652     if (hr->continuesHumongous()) {
  6653       return false;
  6656     if (hr->is_young()) {
  6657       // TODO
  6658     } else if (hr->startsHumongous()) {
  6659       assert(hr->containing_set() == _humongous_set, err_msg("Heap region %u is starts humongous but not in humongous set.", hr->region_num()));
  6660       _humongous_count.increment(1u, hr->capacity());
  6661     } else if (hr->is_empty()) {
  6662       assert(hr->containing_set() == _free_list, err_msg("Heap region %u is empty but not on the free list.", hr->region_num()));
  6663       _free_count.increment(1u, hr->capacity());
  6664     } else {
  6665       assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->region_num()));
  6666       _old_count.increment(1u, hr->capacity());
  6668     return false;
  6671   void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, FreeRegionList* free_list) {
  6672     guarantee(old_set->length() == _old_count.length(), err_msg("Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count.length()));
  6673     guarantee(old_set->total_capacity_bytes() == _old_count.capacity(), err_msg("Old set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
  6674         old_set->total_capacity_bytes(), _old_count.capacity()));
  6676     guarantee(humongous_set->length() == _humongous_count.length(), err_msg("Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count.length()));
  6677     guarantee(humongous_set->total_capacity_bytes() == _humongous_count.capacity(), err_msg("Hum set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
  6678         humongous_set->total_capacity_bytes(), _humongous_count.capacity()));
  6680     guarantee(free_list->length() == _free_count.length(), err_msg("Free list count mismatch. Expected %u, actual %u.", free_list->length(), _free_count.length()));
  6681     guarantee(free_list->total_capacity_bytes() == _free_count.capacity(), err_msg("Free list capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
  6682         free_list->total_capacity_bytes(), _free_count.capacity()));
  6684 };
  6686 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
  6687                                              HeapWord* bottom) {
  6688   HeapWord* end = bottom + HeapRegion::GrainWords;
  6689   MemRegion mr(bottom, end);
  6690   assert(_g1_reserved.contains(mr), "invariant");
  6691   // This might return NULL if the allocation fails
  6692   return new HeapRegion(hrs_index, _bot_shared, mr);
  6695 void G1CollectedHeap::verify_region_sets() {
  6696   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
  6698   // First, check the explicit lists.
  6699   _free_list.verify_list();
  6701     // Given that a concurrent operation might be adding regions to
  6702     // the secondary free list we have to take the lock before
  6703     // verifying it.
  6704     MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
  6705     _secondary_free_list.verify_list();
  6708   // If a concurrent region freeing operation is in progress it will
  6709   // be difficult to correctly attributed any free regions we come
  6710   // across to the correct free list given that they might belong to
  6711   // one of several (free_list, secondary_free_list, any local lists,
  6712   // etc.). So, if that's the case we will skip the rest of the
  6713   // verification operation. Alternatively, waiting for the concurrent
  6714   // operation to complete will have a non-trivial effect on the GC's
  6715   // operation (no concurrent operation will last longer than the
  6716   // interval between two calls to verification) and it might hide
  6717   // any issues that we would like to catch during testing.
  6718   if (free_regions_coming()) {
  6719     return;
  6722   // Make sure we append the secondary_free_list on the free_list so
  6723   // that all free regions we will come across can be safely
  6724   // attributed to the free_list.
  6725   append_secondary_free_list_if_not_empty_with_lock();
  6727   // Finally, make sure that the region accounting in the lists is
  6728   // consistent with what we see in the heap.
  6730   VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_free_list);
  6731   heap_region_iterate(&cl);
  6732   cl.verify_counts(&_old_set, &_humongous_set, &_free_list);
  6735 // Optimized nmethod scanning
  6737 class RegisterNMethodOopClosure: public OopClosure {
  6738   G1CollectedHeap* _g1h;
  6739   nmethod* _nm;
  6741   template <class T> void do_oop_work(T* p) {
  6742     T heap_oop = oopDesc::load_heap_oop(p);
  6743     if (!oopDesc::is_null(heap_oop)) {
  6744       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  6745       HeapRegion* hr = _g1h->heap_region_containing(obj);
  6746       assert(!hr->continuesHumongous(),
  6747              err_msg("trying to add code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
  6748                      " starting at "HR_FORMAT,
  6749                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
  6751       // HeapRegion::add_strong_code_root() avoids adding duplicate
  6752       // entries but having duplicates is  OK since we "mark" nmethods
  6753       // as visited when we scan the strong code root lists during the GC.
  6754       hr->add_strong_code_root(_nm);
  6755       assert(hr->rem_set()->strong_code_roots_list_contains(_nm),
  6756              err_msg("failed to add code root "PTR_FORMAT" to remembered set of region "HR_FORMAT,
  6757                      _nm, HR_FORMAT_PARAMS(hr)));
  6761 public:
  6762   RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
  6763     _g1h(g1h), _nm(nm) {}
  6765   void do_oop(oop* p)       { do_oop_work(p); }
  6766   void do_oop(narrowOop* p) { do_oop_work(p); }
  6767 };
  6769 class UnregisterNMethodOopClosure: public OopClosure {
  6770   G1CollectedHeap* _g1h;
  6771   nmethod* _nm;
  6773   template <class T> void do_oop_work(T* p) {
  6774     T heap_oop = oopDesc::load_heap_oop(p);
  6775     if (!oopDesc::is_null(heap_oop)) {
  6776       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  6777       HeapRegion* hr = _g1h->heap_region_containing(obj);
  6778       assert(!hr->continuesHumongous(),
  6779              err_msg("trying to remove code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
  6780                      " starting at "HR_FORMAT,
  6781                      _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
  6783       hr->remove_strong_code_root(_nm);
  6784       assert(!hr->rem_set()->strong_code_roots_list_contains(_nm),
  6785              err_msg("failed to remove code root "PTR_FORMAT" of region "HR_FORMAT,
  6786                      _nm, HR_FORMAT_PARAMS(hr)));
  6790 public:
  6791   UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
  6792     _g1h(g1h), _nm(nm) {}
  6794   void do_oop(oop* p)       { do_oop_work(p); }
  6795   void do_oop(narrowOop* p) { do_oop_work(p); }
  6796 };
  6798 void G1CollectedHeap::register_nmethod(nmethod* nm) {
  6799   CollectedHeap::register_nmethod(nm);
  6801   guarantee(nm != NULL, "sanity");
  6802   RegisterNMethodOopClosure reg_cl(this, nm);
  6803   nm->oops_do(&reg_cl);
  6806 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
  6807   CollectedHeap::unregister_nmethod(nm);
  6809   guarantee(nm != NULL, "sanity");
  6810   UnregisterNMethodOopClosure reg_cl(this, nm);
  6811   nm->oops_do(&reg_cl, true);
  6814 class MigrateCodeRootsHeapRegionClosure: public HeapRegionClosure {
  6815 public:
  6816   bool doHeapRegion(HeapRegion *hr) {
  6817     assert(!hr->isHumongous(),
  6818            err_msg("humongous region "HR_FORMAT" should not have been added to collection set",
  6819                    HR_FORMAT_PARAMS(hr)));
  6820     hr->migrate_strong_code_roots();
  6821     return false;
  6823 };
  6825 void G1CollectedHeap::migrate_strong_code_roots() {
  6826   MigrateCodeRootsHeapRegionClosure cl;
  6827   double migrate_start = os::elapsedTime();
  6828   collection_set_iterate(&cl);
  6829   double migration_time_ms = (os::elapsedTime() - migrate_start) * 1000.0;
  6830   g1_policy()->phase_times()->record_strong_code_root_migration_time(migration_time_ms);
  6833 void G1CollectedHeap::purge_code_root_memory() {
  6834   double purge_start = os::elapsedTime();
  6835   G1CodeRootSet::purge_chunks(G1CodeRootsChunkCacheKeepPercent);
  6836   double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0;
  6837   g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms);
  6840 // Mark all the code roots that point into regions *not* in the
  6841 // collection set.
  6842 //
  6843 // Note we do not want to use a "marking" CodeBlobToOopClosure while
  6844 // walking the the code roots lists of regions not in the collection
  6845 // set. Suppose we have an nmethod (M) that points to objects in two
  6846 // separate regions - one in the collection set (R1) and one not (R2).
  6847 // Using a "marking" CodeBlobToOopClosure here would result in "marking"
  6848 // nmethod M when walking the code roots for R1. When we come to scan
  6849 // the code roots for R2, we would see that M is already marked and it
  6850 // would be skipped and the objects in R2 that are referenced from M
  6851 // would not be evacuated.
  6853 class MarkStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
  6855   class MarkStrongCodeRootOopClosure: public OopClosure {
  6856     ConcurrentMark* _cm;
  6857     HeapRegion* _hr;
  6858     uint _worker_id;
  6860     template <class T> void do_oop_work(T* p) {
  6861       T heap_oop = oopDesc::load_heap_oop(p);
  6862       if (!oopDesc::is_null(heap_oop)) {
  6863         oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
  6864         // Only mark objects in the region (which is assumed
  6865         // to be not in the collection set).
  6866         if (_hr->is_in(obj)) {
  6867           _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
  6872   public:
  6873     MarkStrongCodeRootOopClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id) :
  6874       _cm(cm), _hr(hr), _worker_id(worker_id) {
  6875       assert(!_hr->in_collection_set(), "sanity");
  6878     void do_oop(narrowOop* p) { do_oop_work(p); }
  6879     void do_oop(oop* p)       { do_oop_work(p); }
  6880   };
  6882   MarkStrongCodeRootOopClosure _oop_cl;
  6884 public:
  6885   MarkStrongCodeRootCodeBlobClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id):
  6886     _oop_cl(cm, hr, worker_id) {}
  6888   void do_code_blob(CodeBlob* cb) {
  6889     nmethod* nm = (cb == NULL) ? NULL : cb->as_nmethod_or_null();
  6890     if (nm != NULL) {
  6891       nm->oops_do(&_oop_cl);
  6894 };
  6896 class MarkStrongCodeRootsHRClosure: public HeapRegionClosure {
  6897   G1CollectedHeap* _g1h;
  6898   uint _worker_id;
  6900 public:
  6901   MarkStrongCodeRootsHRClosure(G1CollectedHeap* g1h, uint worker_id) :
  6902     _g1h(g1h), _worker_id(worker_id) {}
  6904   bool doHeapRegion(HeapRegion *hr) {
  6905     HeapRegionRemSet* hrrs = hr->rem_set();
  6906     if (hr->continuesHumongous()) {
  6907       // Code roots should never be attached to a continuation of a humongous region
  6908       assert(hrrs->strong_code_roots_list_length() == 0,
  6909              err_msg("code roots should never be attached to continuations of humongous region "HR_FORMAT
  6910                      " starting at "HR_FORMAT", but has "SIZE_FORMAT,
  6911                      HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()),
  6912                      hrrs->strong_code_roots_list_length()));
  6913       return false;
  6916     if (hr->in_collection_set()) {
  6917       // Don't mark code roots into regions in the collection set here.
  6918       // They will be marked when we scan them.
  6919       return false;
  6922     MarkStrongCodeRootCodeBlobClosure cb_cl(_g1h->concurrent_mark(), hr, _worker_id);
  6923     hr->strong_code_roots_do(&cb_cl);
  6924     return false;
  6926 };
  6928 void G1CollectedHeap::mark_strong_code_roots(uint worker_id) {
  6929   MarkStrongCodeRootsHRClosure cl(this, worker_id);
  6930   if (G1CollectedHeap::use_parallel_gc_threads()) {
  6931     heap_region_par_iterate_chunked(&cl,
  6932                                     worker_id,
  6933                                     workers()->active_workers(),
  6934                                     HeapRegion::ParMarkRootClaimValue);
  6935   } else {
  6936     heap_region_iterate(&cl);
  6940 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
  6941   G1CollectedHeap* _g1h;
  6943 public:
  6944   RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
  6945     _g1h(g1h) {}
  6947   void do_code_blob(CodeBlob* cb) {
  6948     nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
  6949     if (nm == NULL) {
  6950       return;
  6953     if (ScavengeRootsInCode) {
  6954       _g1h->register_nmethod(nm);
  6957 };
  6959 void G1CollectedHeap::rebuild_strong_code_roots() {
  6960   RebuildStrongCodeRootClosure blob_cl(this);
  6961   CodeCache::blobs_do(&blob_cl);

mercurial