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

Fri, 27 Feb 2009 13:27:09 -0800

author
twisti
date
Fri, 27 Feb 2009 13:27:09 -0800
changeset 1040
98cb887364d3
parent 981
05c6d52fa7a9
child 1042
d8c7fa77a6dc
permissions
-rw-r--r--

6810672: Comment typos
Summary: I have collected some typos I have found while looking at the code.
Reviewed-by: kvn, never

     1 /*
     2  * Copyright 2001-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 #include "incls/_precompiled.incl"
    26 #include "incls/_g1CollectedHeap.cpp.incl"
    28 // turn it on so that the contents of the young list (scan-only /
    29 // to-be-collected) are printed at "strategic" points before / during
    30 // / after the collection --- this is useful for debugging
    31 #define SCAN_ONLY_VERBOSE 0
    32 // CURRENT STATUS
    33 // This file is under construction.  Search for "FIXME".
    35 // INVARIANTS/NOTES
    36 //
    37 // All allocation activity covered by the G1CollectedHeap interface is
    38 //   serialized by acquiring the HeapLock.  This happens in
    39 //   mem_allocate_work, which all such allocation functions call.
    40 //   (Note that this does not apply to TLAB allocation, which is not part
    41 //   of this interface: it is done by clients of this interface.)
    43 // Local to this file.
    45 // Finds the first HeapRegion.
    46 // No longer used, but might be handy someday.
    48 class FindFirstRegionClosure: public HeapRegionClosure {
    49   HeapRegion* _a_region;
    50 public:
    51   FindFirstRegionClosure() : _a_region(NULL) {}
    52   bool doHeapRegion(HeapRegion* r) {
    53     _a_region = r;
    54     return true;
    55   }
    56   HeapRegion* result() { return _a_region; }
    57 };
    60 class RefineCardTableEntryClosure: public CardTableEntryClosure {
    61   SuspendibleThreadSet* _sts;
    62   G1RemSet* _g1rs;
    63   ConcurrentG1Refine* _cg1r;
    64   bool _concurrent;
    65 public:
    66   RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
    67                               G1RemSet* g1rs,
    68                               ConcurrentG1Refine* cg1r) :
    69     _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
    70   {}
    71   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
    72     _g1rs->concurrentRefineOneCard(card_ptr, worker_i);
    73     if (_concurrent && _sts->should_yield()) {
    74       // Caller will actually yield.
    75       return false;
    76     }
    77     // Otherwise, we finished successfully; return true.
    78     return true;
    79   }
    80   void set_concurrent(bool b) { _concurrent = b; }
    81 };
    84 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
    85   int _calls;
    86   G1CollectedHeap* _g1h;
    87   CardTableModRefBS* _ctbs;
    88   int _histo[256];
    89 public:
    90   ClearLoggedCardTableEntryClosure() :
    91     _calls(0)
    92   {
    93     _g1h = G1CollectedHeap::heap();
    94     _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
    95     for (int i = 0; i < 256; i++) _histo[i] = 0;
    96   }
    97   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
    98     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
    99       _calls++;
   100       unsigned char* ujb = (unsigned char*)card_ptr;
   101       int ind = (int)(*ujb);
   102       _histo[ind]++;
   103       *card_ptr = -1;
   104     }
   105     return true;
   106   }
   107   int calls() { return _calls; }
   108   void print_histo() {
   109     gclog_or_tty->print_cr("Card table value histogram:");
   110     for (int i = 0; i < 256; i++) {
   111       if (_histo[i] != 0) {
   112         gclog_or_tty->print_cr("  %d: %d", i, _histo[i]);
   113       }
   114     }
   115   }
   116 };
   118 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
   119   int _calls;
   120   G1CollectedHeap* _g1h;
   121   CardTableModRefBS* _ctbs;
   122 public:
   123   RedirtyLoggedCardTableEntryClosure() :
   124     _calls(0)
   125   {
   126     _g1h = G1CollectedHeap::heap();
   127     _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
   128   }
   129   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
   130     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
   131       _calls++;
   132       *card_ptr = 0;
   133     }
   134     return true;
   135   }
   136   int calls() { return _calls; }
   137 };
   139 YoungList::YoungList(G1CollectedHeap* g1h)
   140   : _g1h(g1h), _head(NULL),
   141     _scan_only_head(NULL), _scan_only_tail(NULL), _curr_scan_only(NULL),
   142     _length(0), _scan_only_length(0),
   143     _last_sampled_rs_lengths(0),
   144     _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0)
   145 {
   146   guarantee( check_list_empty(false), "just making sure..." );
   147 }
   149 void YoungList::push_region(HeapRegion *hr) {
   150   assert(!hr->is_young(), "should not already be young");
   151   assert(hr->get_next_young_region() == NULL, "cause it should!");
   153   hr->set_next_young_region(_head);
   154   _head = hr;
   156   hr->set_young();
   157   double yg_surv_rate = _g1h->g1_policy()->predict_yg_surv_rate((int)_length);
   158   ++_length;
   159 }
   161 void YoungList::add_survivor_region(HeapRegion* hr) {
   162   assert(hr->is_survivor(), "should be flagged as survivor region");
   163   assert(hr->get_next_young_region() == NULL, "cause it should!");
   165   hr->set_next_young_region(_survivor_head);
   166   if (_survivor_head == NULL) {
   167     _survivor_tail = hr;
   168   }
   169   _survivor_head = hr;
   171   ++_survivor_length;
   172 }
   174 HeapRegion* YoungList::pop_region() {
   175   while (_head != NULL) {
   176     assert( length() > 0, "list should not be empty" );
   177     HeapRegion* ret = _head;
   178     _head = ret->get_next_young_region();
   179     ret->set_next_young_region(NULL);
   180     --_length;
   181     assert(ret->is_young(), "region should be very young");
   183     // Replace 'Survivor' region type with 'Young'. So the region will
   184     // be treated as a young region and will not be 'confused' with
   185     // newly created survivor regions.
   186     if (ret->is_survivor()) {
   187       ret->set_young();
   188     }
   190     if (!ret->is_scan_only()) {
   191       return ret;
   192     }
   194     // scan-only, we'll add it to the scan-only list
   195     if (_scan_only_tail == NULL) {
   196       guarantee( _scan_only_head == NULL, "invariant" );
   198       _scan_only_head = ret;
   199       _curr_scan_only = ret;
   200     } else {
   201       guarantee( _scan_only_head != NULL, "invariant" );
   202       _scan_only_tail->set_next_young_region(ret);
   203     }
   204     guarantee( ret->get_next_young_region() == NULL, "invariant" );
   205     _scan_only_tail = ret;
   207     // no need to be tagged as scan-only any more
   208     ret->set_young();
   210     ++_scan_only_length;
   211   }
   212   assert( length() == 0, "list should be empty" );
   213   return NULL;
   214 }
   216 void YoungList::empty_list(HeapRegion* list) {
   217   while (list != NULL) {
   218     HeapRegion* next = list->get_next_young_region();
   219     list->set_next_young_region(NULL);
   220     list->uninstall_surv_rate_group();
   221     list->set_not_young();
   222     list = next;
   223   }
   224 }
   226 void YoungList::empty_list() {
   227   assert(check_list_well_formed(), "young list should be well formed");
   229   empty_list(_head);
   230   _head = NULL;
   231   _length = 0;
   233   empty_list(_scan_only_head);
   234   _scan_only_head = NULL;
   235   _scan_only_tail = NULL;
   236   _scan_only_length = 0;
   237   _curr_scan_only = NULL;
   239   empty_list(_survivor_head);
   240   _survivor_head = NULL;
   241   _survivor_tail = NULL;
   242   _survivor_length = 0;
   244   _last_sampled_rs_lengths = 0;
   246   assert(check_list_empty(false), "just making sure...");
   247 }
   249 bool YoungList::check_list_well_formed() {
   250   bool ret = true;
   252   size_t length = 0;
   253   HeapRegion* curr = _head;
   254   HeapRegion* last = NULL;
   255   while (curr != NULL) {
   256     if (!curr->is_young() || curr->is_scan_only()) {
   257       gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
   258                              "incorrectly tagged (%d, %d)",
   259                              curr->bottom(), curr->end(),
   260                              curr->is_young(), curr->is_scan_only());
   261       ret = false;
   262     }
   263     ++length;
   264     last = curr;
   265     curr = curr->get_next_young_region();
   266   }
   267   ret = ret && (length == _length);
   269   if (!ret) {
   270     gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
   271     gclog_or_tty->print_cr("###   list has %d entries, _length is %d",
   272                            length, _length);
   273   }
   275   bool scan_only_ret = true;
   276   length = 0;
   277   curr = _scan_only_head;
   278   last = NULL;
   279   while (curr != NULL) {
   280     if (!curr->is_young() || curr->is_scan_only()) {
   281       gclog_or_tty->print_cr("### SCAN-ONLY REGION "PTR_FORMAT"-"PTR_FORMAT" "
   282                              "incorrectly tagged (%d, %d)",
   283                              curr->bottom(), curr->end(),
   284                              curr->is_young(), curr->is_scan_only());
   285       scan_only_ret = false;
   286     }
   287     ++length;
   288     last = curr;
   289     curr = curr->get_next_young_region();
   290   }
   291   scan_only_ret = scan_only_ret && (length == _scan_only_length);
   293   if ( (last != _scan_only_tail) ||
   294        (_scan_only_head == NULL && _scan_only_tail != NULL) ||
   295        (_scan_only_head != NULL && _scan_only_tail == NULL) ) {
   296      gclog_or_tty->print_cr("## _scan_only_tail is set incorrectly");
   297      scan_only_ret = false;
   298   }
   300   if (_curr_scan_only != NULL && _curr_scan_only != _scan_only_head) {
   301     gclog_or_tty->print_cr("### _curr_scan_only is set incorrectly");
   302     scan_only_ret = false;
   303    }
   305   if (!scan_only_ret) {
   306     gclog_or_tty->print_cr("### SCAN-ONLY LIST seems not well formed!");
   307     gclog_or_tty->print_cr("###   list has %d entries, _scan_only_length is %d",
   308                   length, _scan_only_length);
   309   }
   311   return ret && scan_only_ret;
   312 }
   314 bool YoungList::check_list_empty(bool ignore_scan_only_list,
   315                                  bool check_sample) {
   316   bool ret = true;
   318   if (_length != 0) {
   319     gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %d",
   320                   _length);
   321     ret = false;
   322   }
   323   if (check_sample && _last_sampled_rs_lengths != 0) {
   324     gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
   325     ret = false;
   326   }
   327   if (_head != NULL) {
   328     gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
   329     ret = false;
   330   }
   331   if (!ret) {
   332     gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
   333   }
   335   if (ignore_scan_only_list)
   336     return ret;
   338   bool scan_only_ret = true;
   339   if (_scan_only_length != 0) {
   340     gclog_or_tty->print_cr("### SCAN-ONLY LIST should have 0 length, not %d",
   341                   _scan_only_length);
   342     scan_only_ret = false;
   343   }
   344   if (_scan_only_head != NULL) {
   345     gclog_or_tty->print_cr("### SCAN-ONLY LIST does not have a NULL head");
   346      scan_only_ret = false;
   347   }
   348   if (_scan_only_tail != NULL) {
   349     gclog_or_tty->print_cr("### SCAN-ONLY LIST does not have a NULL tail");
   350     scan_only_ret = false;
   351   }
   352   if (!scan_only_ret) {
   353     gclog_or_tty->print_cr("### SCAN-ONLY LIST does not seem empty");
   354   }
   356   return ret && scan_only_ret;
   357 }
   359 void
   360 YoungList::rs_length_sampling_init() {
   361   _sampled_rs_lengths = 0;
   362   _curr               = _head;
   363 }
   365 bool
   366 YoungList::rs_length_sampling_more() {
   367   return _curr != NULL;
   368 }
   370 void
   371 YoungList::rs_length_sampling_next() {
   372   assert( _curr != NULL, "invariant" );
   373   _sampled_rs_lengths += _curr->rem_set()->occupied();
   374   _curr = _curr->get_next_young_region();
   375   if (_curr == NULL) {
   376     _last_sampled_rs_lengths = _sampled_rs_lengths;
   377     // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
   378   }
   379 }
   381 void
   382 YoungList::reset_auxilary_lists() {
   383   // We could have just "moved" the scan-only list to the young list.
   384   // However, the scan-only list is ordered according to the region
   385   // age in descending order, so, by moving one entry at a time, we
   386   // ensure that it is recreated in ascending order.
   388   guarantee( is_empty(), "young list should be empty" );
   389   assert(check_list_well_formed(), "young list should be well formed");
   391   // Add survivor regions to SurvRateGroup.
   392   _g1h->g1_policy()->note_start_adding_survivor_regions();
   393   _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
   394   for (HeapRegion* curr = _survivor_head;
   395        curr != NULL;
   396        curr = curr->get_next_young_region()) {
   397     _g1h->g1_policy()->set_region_survivors(curr);
   398   }
   399   _g1h->g1_policy()->note_stop_adding_survivor_regions();
   401   if (_survivor_head != NULL) {
   402     _head           = _survivor_head;
   403     _length         = _survivor_length + _scan_only_length;
   404     _survivor_tail->set_next_young_region(_scan_only_head);
   405   } else {
   406     _head           = _scan_only_head;
   407     _length         = _scan_only_length;
   408   }
   410   for (HeapRegion* curr = _scan_only_head;
   411        curr != NULL;
   412        curr = curr->get_next_young_region()) {
   413     curr->recalculate_age_in_surv_rate_group();
   414   }
   415   _scan_only_head   = NULL;
   416   _scan_only_tail   = NULL;
   417   _scan_only_length = 0;
   418   _curr_scan_only   = NULL;
   420   _survivor_head    = NULL;
   421   _survivor_tail   = NULL;
   422   _survivor_length  = 0;
   423   _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
   425   assert(check_list_well_formed(), "young list should be well formed");
   426 }
   428 void YoungList::print() {
   429   HeapRegion* lists[] = {_head,   _scan_only_head, _survivor_head};
   430   const char* names[] = {"YOUNG", "SCAN-ONLY",     "SURVIVOR"};
   432   for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
   433     gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
   434     HeapRegion *curr = lists[list];
   435     if (curr == NULL)
   436       gclog_or_tty->print_cr("  empty");
   437     while (curr != NULL) {
   438       gclog_or_tty->print_cr("  [%08x-%08x], t: %08x, P: %08x, N: %08x, C: %08x, "
   439                              "age: %4d, y: %d, s-o: %d, surv: %d",
   440                              curr->bottom(), curr->end(),
   441                              curr->top(),
   442                              curr->prev_top_at_mark_start(),
   443                              curr->next_top_at_mark_start(),
   444                              curr->top_at_conc_mark_count(),
   445                              curr->age_in_surv_rate_group_cond(),
   446                              curr->is_young(),
   447                              curr->is_scan_only(),
   448                              curr->is_survivor());
   449       curr = curr->get_next_young_region();
   450     }
   451   }
   453   gclog_or_tty->print_cr("");
   454 }
   456 void G1CollectedHeap::stop_conc_gc_threads() {
   457   _cg1r->cg1rThread()->stop();
   458   _czft->stop();
   459   _cmThread->stop();
   460 }
   463 void G1CollectedHeap::check_ct_logs_at_safepoint() {
   464   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
   465   CardTableModRefBS* ct_bs = (CardTableModRefBS*)barrier_set();
   467   // Count the dirty cards at the start.
   468   CountNonCleanMemRegionClosure count1(this);
   469   ct_bs->mod_card_iterate(&count1);
   470   int orig_count = count1.n();
   472   // First clear the logged cards.
   473   ClearLoggedCardTableEntryClosure clear;
   474   dcqs.set_closure(&clear);
   475   dcqs.apply_closure_to_all_completed_buffers();
   476   dcqs.iterate_closure_all_threads(false);
   477   clear.print_histo();
   479   // Now ensure that there's no dirty cards.
   480   CountNonCleanMemRegionClosure count2(this);
   481   ct_bs->mod_card_iterate(&count2);
   482   if (count2.n() != 0) {
   483     gclog_or_tty->print_cr("Card table has %d entries; %d originally",
   484                            count2.n(), orig_count);
   485   }
   486   guarantee(count2.n() == 0, "Card table should be clean.");
   488   RedirtyLoggedCardTableEntryClosure redirty;
   489   JavaThread::dirty_card_queue_set().set_closure(&redirty);
   490   dcqs.apply_closure_to_all_completed_buffers();
   491   dcqs.iterate_closure_all_threads(false);
   492   gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
   493                          clear.calls(), orig_count);
   494   guarantee(redirty.calls() == clear.calls(),
   495             "Or else mechanism is broken.");
   497   CountNonCleanMemRegionClosure count3(this);
   498   ct_bs->mod_card_iterate(&count3);
   499   if (count3.n() != orig_count) {
   500     gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
   501                            orig_count, count3.n());
   502     guarantee(count3.n() >= orig_count, "Should have restored them all.");
   503   }
   505   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
   506 }
   508 // Private class members.
   510 G1CollectedHeap* G1CollectedHeap::_g1h;
   512 // Private methods.
   514 // Finds a HeapRegion that can be used to allocate a given size of block.
   517 HeapRegion* G1CollectedHeap::newAllocRegion_work(size_t word_size,
   518                                                  bool do_expand,
   519                                                  bool zero_filled) {
   520   ConcurrentZFThread::note_region_alloc();
   521   HeapRegion* res = alloc_free_region_from_lists(zero_filled);
   522   if (res == NULL && do_expand) {
   523     expand(word_size * HeapWordSize);
   524     res = alloc_free_region_from_lists(zero_filled);
   525     assert(res == NULL ||
   526            (!res->isHumongous() &&
   527             (!zero_filled ||
   528              res->zero_fill_state() == HeapRegion::Allocated)),
   529            "Alloc Regions must be zero filled (and non-H)");
   530   }
   531   if (res != NULL && res->is_empty()) _free_regions--;
   532   assert(res == NULL ||
   533          (!res->isHumongous() &&
   534           (!zero_filled ||
   535            res->zero_fill_state() == HeapRegion::Allocated)),
   536          "Non-young alloc Regions must be zero filled (and non-H)");
   538   if (G1TraceRegions) {
   539     if (res != NULL) {
   540       gclog_or_tty->print_cr("new alloc region %d:["PTR_FORMAT", "PTR_FORMAT"], "
   541                              "top "PTR_FORMAT,
   542                              res->hrs_index(), res->bottom(), res->end(), res->top());
   543     }
   544   }
   546   return res;
   547 }
   549 HeapRegion* G1CollectedHeap::newAllocRegionWithExpansion(int purpose,
   550                                                          size_t word_size,
   551                                                          bool zero_filled) {
   552   HeapRegion* alloc_region = NULL;
   553   if (_gc_alloc_region_counts[purpose] < g1_policy()->max_regions(purpose)) {
   554     alloc_region = newAllocRegion_work(word_size, true, zero_filled);
   555     if (purpose == GCAllocForSurvived && alloc_region != NULL) {
   556       alloc_region->set_survivor();
   557     }
   558     ++_gc_alloc_region_counts[purpose];
   559   } else {
   560     g1_policy()->note_alloc_region_limit_reached(purpose);
   561   }
   562   return alloc_region;
   563 }
   565 // If could fit into free regions w/o expansion, try.
   566 // Otherwise, if can expand, do so.
   567 // Otherwise, if using ex regions might help, try with ex given back.
   568 HeapWord* G1CollectedHeap::humongousObjAllocate(size_t word_size) {
   569   assert(regions_accounted_for(), "Region leakage!");
   571   // We can't allocate H regions while cleanupComplete is running, since
   572   // some of the regions we find to be empty might not yet be added to the
   573   // unclean list.  (If we're already at a safepoint, this call is
   574   // unnecessary, not to mention wrong.)
   575   if (!SafepointSynchronize::is_at_safepoint())
   576     wait_for_cleanup_complete();
   578   size_t num_regions =
   579     round_to(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
   581   // Special case if < one region???
   583   // Remember the ft size.
   584   size_t x_size = expansion_regions();
   586   HeapWord* res = NULL;
   587   bool eliminated_allocated_from_lists = false;
   589   // Can the allocation potentially fit in the free regions?
   590   if (free_regions() >= num_regions) {
   591     res = _hrs->obj_allocate(word_size);
   592   }
   593   if (res == NULL) {
   594     // Try expansion.
   595     size_t fs = _hrs->free_suffix();
   596     if (fs + x_size >= num_regions) {
   597       expand((num_regions - fs) * HeapRegion::GrainBytes);
   598       res = _hrs->obj_allocate(word_size);
   599       assert(res != NULL, "This should have worked.");
   600     } else {
   601       // Expansion won't help.  Are there enough free regions if we get rid
   602       // of reservations?
   603       size_t avail = free_regions();
   604       if (avail >= num_regions) {
   605         res = _hrs->obj_allocate(word_size);
   606         if (res != NULL) {
   607           remove_allocated_regions_from_lists();
   608           eliminated_allocated_from_lists = true;
   609         }
   610       }
   611     }
   612   }
   613   if (res != NULL) {
   614     // Increment by the number of regions allocated.
   615     // FIXME: Assumes regions all of size GrainBytes.
   616 #ifndef PRODUCT
   617     mr_bs()->verify_clean_region(MemRegion(res, res + num_regions *
   618                                            HeapRegion::GrainWords));
   619 #endif
   620     if (!eliminated_allocated_from_lists)
   621       remove_allocated_regions_from_lists();
   622     _summary_bytes_used += word_size * HeapWordSize;
   623     _free_regions -= num_regions;
   624     _num_humongous_regions += (int) num_regions;
   625   }
   626   assert(regions_accounted_for(), "Region Leakage");
   627   return res;
   628 }
   630 HeapWord*
   631 G1CollectedHeap::attempt_allocation_slow(size_t word_size,
   632                                          bool permit_collection_pause) {
   633   HeapWord* res = NULL;
   634   HeapRegion* allocated_young_region = NULL;
   636   assert( SafepointSynchronize::is_at_safepoint() ||
   637           Heap_lock->owned_by_self(), "pre condition of the call" );
   639   if (isHumongous(word_size)) {
   640     // Allocation of a humongous object can, in a sense, complete a
   641     // partial region, if the previous alloc was also humongous, and
   642     // caused the test below to succeed.
   643     if (permit_collection_pause)
   644       do_collection_pause_if_appropriate(word_size);
   645     res = humongousObjAllocate(word_size);
   646     assert(_cur_alloc_region == NULL
   647            || !_cur_alloc_region->isHumongous(),
   648            "Prevent a regression of this bug.");
   650   } else {
   651     // We may have concurrent cleanup working at the time. Wait for it
   652     // to complete. In the future we would probably want to make the
   653     // concurrent cleanup truly concurrent by decoupling it from the
   654     // allocation.
   655     if (!SafepointSynchronize::is_at_safepoint())
   656       wait_for_cleanup_complete();
   657     // If we do a collection pause, this will be reset to a non-NULL
   658     // value.  If we don't, nulling here ensures that we allocate a new
   659     // region below.
   660     if (_cur_alloc_region != NULL) {
   661       // We're finished with the _cur_alloc_region.
   662       _summary_bytes_used += _cur_alloc_region->used();
   663       _cur_alloc_region = NULL;
   664     }
   665     assert(_cur_alloc_region == NULL, "Invariant.");
   666     // Completion of a heap region is perhaps a good point at which to do
   667     // a collection pause.
   668     if (permit_collection_pause)
   669       do_collection_pause_if_appropriate(word_size);
   670     // Make sure we have an allocation region available.
   671     if (_cur_alloc_region == NULL) {
   672       if (!SafepointSynchronize::is_at_safepoint())
   673         wait_for_cleanup_complete();
   674       bool next_is_young = should_set_young_locked();
   675       // If the next region is not young, make sure it's zero-filled.
   676       _cur_alloc_region = newAllocRegion(word_size, !next_is_young);
   677       if (_cur_alloc_region != NULL) {
   678         _summary_bytes_used -= _cur_alloc_region->used();
   679         if (next_is_young) {
   680           set_region_short_lived_locked(_cur_alloc_region);
   681           allocated_young_region = _cur_alloc_region;
   682         }
   683       }
   684     }
   685     assert(_cur_alloc_region == NULL || !_cur_alloc_region->isHumongous(),
   686            "Prevent a regression of this bug.");
   688     // Now retry the allocation.
   689     if (_cur_alloc_region != NULL) {
   690       res = _cur_alloc_region->allocate(word_size);
   691     }
   692   }
   694   // NOTE: fails frequently in PRT
   695   assert(regions_accounted_for(), "Region leakage!");
   697   if (res != NULL) {
   698     if (!SafepointSynchronize::is_at_safepoint()) {
   699       assert( permit_collection_pause, "invariant" );
   700       assert( Heap_lock->owned_by_self(), "invariant" );
   701       Heap_lock->unlock();
   702     }
   704     if (allocated_young_region != NULL) {
   705       HeapRegion* hr = allocated_young_region;
   706       HeapWord* bottom = hr->bottom();
   707       HeapWord* end = hr->end();
   708       MemRegion mr(bottom, end);
   709       ((CardTableModRefBS*)_g1h->barrier_set())->dirty(mr);
   710     }
   711   }
   713   assert( SafepointSynchronize::is_at_safepoint() ||
   714           (res == NULL && Heap_lock->owned_by_self()) ||
   715           (res != NULL && !Heap_lock->owned_by_self()),
   716           "post condition of the call" );
   718   return res;
   719 }
   721 HeapWord*
   722 G1CollectedHeap::mem_allocate(size_t word_size,
   723                               bool   is_noref,
   724                               bool   is_tlab,
   725                               bool* gc_overhead_limit_was_exceeded) {
   726   debug_only(check_for_valid_allocation_state());
   727   assert(no_gc_in_progress(), "Allocation during gc not allowed");
   728   HeapWord* result = NULL;
   730   // Loop until the allocation is satisified,
   731   // or unsatisfied after GC.
   732   for (int try_count = 1; /* return or throw */; try_count += 1) {
   733     int gc_count_before;
   734     {
   735       Heap_lock->lock();
   736       result = attempt_allocation(word_size);
   737       if (result != NULL) {
   738         // attempt_allocation should have unlocked the heap lock
   739         assert(is_in(result), "result not in heap");
   740         return result;
   741       }
   742       // Read the gc count while the heap lock is held.
   743       gc_count_before = SharedHeap::heap()->total_collections();
   744       Heap_lock->unlock();
   745     }
   747     // Create the garbage collection operation...
   748     VM_G1CollectForAllocation op(word_size,
   749                                  gc_count_before);
   751     // ...and get the VM thread to execute it.
   752     VMThread::execute(&op);
   753     if (op.prologue_succeeded()) {
   754       result = op.result();
   755       assert(result == NULL || is_in(result), "result not in heap");
   756       return result;
   757     }
   759     // Give a warning if we seem to be looping forever.
   760     if ((QueuedAllocationWarningCount > 0) &&
   761         (try_count % QueuedAllocationWarningCount == 0)) {
   762       warning("G1CollectedHeap::mem_allocate_work retries %d times",
   763               try_count);
   764     }
   765   }
   766 }
   768 void G1CollectedHeap::abandon_cur_alloc_region() {
   769   if (_cur_alloc_region != NULL) {
   770     // We're finished with the _cur_alloc_region.
   771     if (_cur_alloc_region->is_empty()) {
   772       _free_regions++;
   773       free_region(_cur_alloc_region);
   774     } else {
   775       _summary_bytes_used += _cur_alloc_region->used();
   776     }
   777     _cur_alloc_region = NULL;
   778   }
   779 }
   781 class PostMCRemSetClearClosure: public HeapRegionClosure {
   782   ModRefBarrierSet* _mr_bs;
   783 public:
   784   PostMCRemSetClearClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
   785   bool doHeapRegion(HeapRegion* r) {
   786     r->reset_gc_time_stamp();
   787     if (r->continuesHumongous())
   788       return false;
   789     HeapRegionRemSet* hrrs = r->rem_set();
   790     if (hrrs != NULL) hrrs->clear();
   791     // You might think here that we could clear just the cards
   792     // corresponding to the used region.  But no: if we leave a dirty card
   793     // in a region we might allocate into, then it would prevent that card
   794     // from being enqueued, and cause it to be missed.
   795     // Re: the performance cost: we shouldn't be doing full GC anyway!
   796     _mr_bs->clear(MemRegion(r->bottom(), r->end()));
   797     return false;
   798   }
   799 };
   802 class PostMCRemSetInvalidateClosure: public HeapRegionClosure {
   803   ModRefBarrierSet* _mr_bs;
   804 public:
   805   PostMCRemSetInvalidateClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
   806   bool doHeapRegion(HeapRegion* r) {
   807     if (r->continuesHumongous()) return false;
   808     if (r->used_region().word_size() != 0) {
   809       _mr_bs->invalidate(r->used_region(), true /*whole heap*/);
   810     }
   811     return false;
   812   }
   813 };
   815 void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs,
   816                                     size_t word_size) {
   817   ResourceMark rm;
   819   if (full && DisableExplicitGC) {
   820     gclog_or_tty->print("\n\n\nDisabling Explicit GC\n\n\n");
   821     return;
   822   }
   824   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
   825   assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
   827   if (GC_locker::is_active()) {
   828     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
   829   }
   831   {
   832     IsGCActiveMark x;
   834     // Timing
   835     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
   836     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
   837     TraceTime t(full ? "Full GC (System.gc())" : "Full GC", PrintGC, true, gclog_or_tty);
   839     double start = os::elapsedTime();
   840     GCOverheadReporter::recordSTWStart(start);
   841     g1_policy()->record_full_collection_start();
   843     gc_prologue(true);
   844     increment_total_collections();
   846     size_t g1h_prev_used = used();
   847     assert(used() == recalculate_used(), "Should be equal");
   849     if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
   850       HandleMark hm;  // Discard invalid handles created during verification
   851       prepare_for_verify();
   852       gclog_or_tty->print(" VerifyBeforeGC:");
   853       Universe::verify(true);
   854     }
   855     assert(regions_accounted_for(), "Region leakage!");
   857     COMPILER2_PRESENT(DerivedPointerTable::clear());
   859     // We want to discover references, but not process them yet.
   860     // This mode is disabled in
   861     // instanceRefKlass::process_discovered_references if the
   862     // generation does some collection work, or
   863     // instanceRefKlass::enqueue_discovered_references if the
   864     // generation returns without doing any work.
   865     ref_processor()->disable_discovery();
   866     ref_processor()->abandon_partial_discovery();
   867     ref_processor()->verify_no_references_recorded();
   869     // Abandon current iterations of concurrent marking and concurrent
   870     // refinement, if any are in progress.
   871     concurrent_mark()->abort();
   873     // Make sure we'll choose a new allocation region afterwards.
   874     abandon_cur_alloc_region();
   875     assert(_cur_alloc_region == NULL, "Invariant.");
   876     g1_rem_set()->as_HRInto_G1RemSet()->cleanupHRRS();
   877     tear_down_region_lists();
   878     set_used_regions_to_need_zero_fill();
   879     if (g1_policy()->in_young_gc_mode()) {
   880       empty_young_list();
   881       g1_policy()->set_full_young_gcs(true);
   882     }
   884     // Temporarily make reference _discovery_ single threaded (non-MT).
   885     ReferenceProcessorMTMutator rp_disc_ser(ref_processor(), false);
   887     // Temporarily make refs discovery atomic
   888     ReferenceProcessorAtomicMutator rp_disc_atomic(ref_processor(), true);
   890     // Temporarily clear _is_alive_non_header
   891     ReferenceProcessorIsAliveMutator rp_is_alive_null(ref_processor(), NULL);
   893     ref_processor()->enable_discovery();
   894     ref_processor()->setup_policy(clear_all_soft_refs);
   896     // Do collection work
   897     {
   898       HandleMark hm;  // Discard invalid handles created during gc
   899       G1MarkSweep::invoke_at_safepoint(ref_processor(), clear_all_soft_refs);
   900     }
   901     // Because freeing humongous regions may have added some unclean
   902     // regions, it is necessary to tear down again before rebuilding.
   903     tear_down_region_lists();
   904     rebuild_region_lists();
   906     _summary_bytes_used = recalculate_used();
   908     ref_processor()->enqueue_discovered_references();
   910     COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
   912     if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
   913       HandleMark hm;  // Discard invalid handles created during verification
   914       gclog_or_tty->print(" VerifyAfterGC:");
   915       Universe::verify(false);
   916     }
   917     NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
   919     reset_gc_time_stamp();
   920     // Since everything potentially moved, we will clear all remembered
   921     // sets, and clear all cards.  Later we will also cards in the used
   922     // portion of the heap after the resizing (which could be a shrinking.)
   923     // We will also reset the GC time stamps of the regions.
   924     PostMCRemSetClearClosure rs_clear(mr_bs());
   925     heap_region_iterate(&rs_clear);
   927     // Resize the heap if necessary.
   928     resize_if_necessary_after_full_collection(full ? 0 : word_size);
   930     // Since everything potentially moved, we will clear all remembered
   931     // sets, but also dirty all cards corresponding to used regions.
   932     PostMCRemSetInvalidateClosure rs_invalidate(mr_bs());
   933     heap_region_iterate(&rs_invalidate);
   934     if (_cg1r->use_cache()) {
   935       _cg1r->clear_and_record_card_counts();
   936       _cg1r->clear_hot_cache();
   937     }
   939     if (PrintGC) {
   940       print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity());
   941     }
   943     if (true) { // FIXME
   944       // Ask the permanent generation to adjust size for full collections
   945       perm()->compute_new_size();
   946     }
   948     double end = os::elapsedTime();
   949     GCOverheadReporter::recordSTWEnd(end);
   950     g1_policy()->record_full_collection_end();
   952 #ifdef TRACESPINNING
   953     ParallelTaskTerminator::print_termination_counts();
   954 #endif
   956     gc_epilogue(true);
   958     // Abandon concurrent refinement.  This must happen last: in the
   959     // dirty-card logging system, some cards may be dirty by weak-ref
   960     // processing, and may be enqueued.  But the whole card table is
   961     // dirtied, so this should abandon those logs, and set "do_traversal"
   962     // to true.
   963     concurrent_g1_refine()->set_pya_restart();
   965     assert(regions_accounted_for(), "Region leakage!");
   966   }
   968   if (g1_policy()->in_young_gc_mode()) {
   969     _young_list->reset_sampled_info();
   970     assert( check_young_list_empty(false, false),
   971             "young list should be empty at this point");
   972   }
   973 }
   975 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
   976   do_collection(true, clear_all_soft_refs, 0);
   977 }
   979 // This code is mostly copied from TenuredGeneration.
   980 void
   981 G1CollectedHeap::
   982 resize_if_necessary_after_full_collection(size_t word_size) {
   983   assert(MinHeapFreeRatio <= MaxHeapFreeRatio, "sanity check");
   985   // Include the current allocation, if any, and bytes that will be
   986   // pre-allocated to support collections, as "used".
   987   const size_t used_after_gc = used();
   988   const size_t capacity_after_gc = capacity();
   989   const size_t free_after_gc = capacity_after_gc - used_after_gc;
   991   // We don't have floating point command-line arguments
   992   const double minimum_free_percentage = (double) MinHeapFreeRatio / 100;
   993   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
   994   const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100;
   995   const double minimum_used_percentage = 1.0 - maximum_free_percentage;
   997   size_t minimum_desired_capacity = (size_t) (used_after_gc / maximum_used_percentage);
   998   size_t maximum_desired_capacity = (size_t) (used_after_gc / minimum_used_percentage);
  1000   // Don't shrink less than the initial size.
  1001   minimum_desired_capacity =
  1002     MAX2(minimum_desired_capacity,
  1003          collector_policy()->initial_heap_byte_size());
  1004   maximum_desired_capacity =
  1005     MAX2(maximum_desired_capacity,
  1006          collector_policy()->initial_heap_byte_size());
  1008   // We are failing here because minimum_desired_capacity is
  1009   assert(used_after_gc <= minimum_desired_capacity, "sanity check");
  1010   assert(minimum_desired_capacity <= maximum_desired_capacity, "sanity check");
  1012   if (PrintGC && Verbose) {
  1013     const double free_percentage = ((double)free_after_gc) / capacity();
  1014     gclog_or_tty->print_cr("Computing new size after full GC ");
  1015     gclog_or_tty->print_cr("  "
  1016                            "  minimum_free_percentage: %6.2f",
  1017                            minimum_free_percentage);
  1018     gclog_or_tty->print_cr("  "
  1019                            "  maximum_free_percentage: %6.2f",
  1020                            maximum_free_percentage);
  1021     gclog_or_tty->print_cr("  "
  1022                            "  capacity: %6.1fK"
  1023                            "  minimum_desired_capacity: %6.1fK"
  1024                            "  maximum_desired_capacity: %6.1fK",
  1025                            capacity() / (double) K,
  1026                            minimum_desired_capacity / (double) K,
  1027                            maximum_desired_capacity / (double) K);
  1028     gclog_or_tty->print_cr("  "
  1029                            "   free_after_gc   : %6.1fK"
  1030                            "   used_after_gc   : %6.1fK",
  1031                            free_after_gc / (double) K,
  1032                            used_after_gc / (double) K);
  1033     gclog_or_tty->print_cr("  "
  1034                            "   free_percentage: %6.2f",
  1035                            free_percentage);
  1037   if (capacity() < minimum_desired_capacity) {
  1038     // Don't expand unless it's significant
  1039     size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
  1040     expand(expand_bytes);
  1041     if (PrintGC && Verbose) {
  1042       gclog_or_tty->print_cr("    expanding:"
  1043                              "  minimum_desired_capacity: %6.1fK"
  1044                              "  expand_bytes: %6.1fK",
  1045                              minimum_desired_capacity / (double) K,
  1046                              expand_bytes / (double) K);
  1049     // No expansion, now see if we want to shrink
  1050   } else if (capacity() > maximum_desired_capacity) {
  1051     // Capacity too large, compute shrinking size
  1052     size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
  1053     shrink(shrink_bytes);
  1054     if (PrintGC && Verbose) {
  1055       gclog_or_tty->print_cr("  "
  1056                              "  shrinking:"
  1057                              "  initSize: %.1fK"
  1058                              "  maximum_desired_capacity: %.1fK",
  1059                              collector_policy()->initial_heap_byte_size() / (double) K,
  1060                              maximum_desired_capacity / (double) K);
  1061       gclog_or_tty->print_cr("  "
  1062                              "  shrink_bytes: %.1fK",
  1063                              shrink_bytes / (double) K);
  1069 HeapWord*
  1070 G1CollectedHeap::satisfy_failed_allocation(size_t word_size) {
  1071   HeapWord* result = NULL;
  1073   // In a G1 heap, we're supposed to keep allocation from failing by
  1074   // incremental pauses.  Therefore, at least for now, we'll favor
  1075   // expansion over collection.  (This might change in the future if we can
  1076   // do something smarter than full collection to satisfy a failed alloc.)
  1078   result = expand_and_allocate(word_size);
  1079   if (result != NULL) {
  1080     assert(is_in(result), "result not in heap");
  1081     return result;
  1084   // OK, I guess we have to try collection.
  1086   do_collection(false, false, word_size);
  1088   result = attempt_allocation(word_size, /*permit_collection_pause*/false);
  1090   if (result != NULL) {
  1091     assert(is_in(result), "result not in heap");
  1092     return result;
  1095   // Try collecting soft references.
  1096   do_collection(false, true, word_size);
  1097   result = attempt_allocation(word_size, /*permit_collection_pause*/false);
  1098   if (result != NULL) {
  1099     assert(is_in(result), "result not in heap");
  1100     return result;
  1103   // What else?  We might try synchronous finalization later.  If the total
  1104   // space available is large enough for the allocation, then a more
  1105   // complete compaction phase than we've tried so far might be
  1106   // appropriate.
  1107   return NULL;
  1110 // Attempting to expand the heap sufficiently
  1111 // to support an allocation of the given "word_size".  If
  1112 // successful, perform the allocation and return the address of the
  1113 // allocated block, or else "NULL".
  1115 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
  1116   size_t expand_bytes = word_size * HeapWordSize;
  1117   if (expand_bytes < MinHeapDeltaBytes) {
  1118     expand_bytes = MinHeapDeltaBytes;
  1120   expand(expand_bytes);
  1121   assert(regions_accounted_for(), "Region leakage!");
  1122   HeapWord* result = attempt_allocation(word_size, false /* permit_collection_pause */);
  1123   return result;
  1126 size_t G1CollectedHeap::free_region_if_totally_empty(HeapRegion* hr) {
  1127   size_t pre_used = 0;
  1128   size_t cleared_h_regions = 0;
  1129   size_t freed_regions = 0;
  1130   UncleanRegionList local_list;
  1131   free_region_if_totally_empty_work(hr, pre_used, cleared_h_regions,
  1132                                     freed_regions, &local_list);
  1134   finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
  1135                           &local_list);
  1136   return pre_used;
  1139 void
  1140 G1CollectedHeap::free_region_if_totally_empty_work(HeapRegion* hr,
  1141                                                    size_t& pre_used,
  1142                                                    size_t& cleared_h,
  1143                                                    size_t& freed_regions,
  1144                                                    UncleanRegionList* list,
  1145                                                    bool par) {
  1146   assert(!hr->continuesHumongous(), "should have filtered these out");
  1147   size_t res = 0;
  1148   if (!hr->popular() && hr->used() > 0 && hr->garbage_bytes() == hr->used()) {
  1149     if (!hr->is_young()) {
  1150       if (G1PolicyVerbose > 0)
  1151         gclog_or_tty->print_cr("Freeing empty region "PTR_FORMAT "(" SIZE_FORMAT " bytes)"
  1152                                " during cleanup", hr, hr->used());
  1153       free_region_work(hr, pre_used, cleared_h, freed_regions, list, par);
  1158 // FIXME: both this and shrink could probably be more efficient by
  1159 // doing one "VirtualSpace::expand_by" call rather than several.
  1160 void G1CollectedHeap::expand(size_t expand_bytes) {
  1161   size_t old_mem_size = _g1_storage.committed_size();
  1162   // We expand by a minimum of 1K.
  1163   expand_bytes = MAX2(expand_bytes, (size_t)K);
  1164   size_t aligned_expand_bytes =
  1165     ReservedSpace::page_align_size_up(expand_bytes);
  1166   aligned_expand_bytes = align_size_up(aligned_expand_bytes,
  1167                                        HeapRegion::GrainBytes);
  1168   expand_bytes = aligned_expand_bytes;
  1169   while (expand_bytes > 0) {
  1170     HeapWord* base = (HeapWord*)_g1_storage.high();
  1171     // Commit more storage.
  1172     bool successful = _g1_storage.expand_by(HeapRegion::GrainBytes);
  1173     if (!successful) {
  1174         expand_bytes = 0;
  1175     } else {
  1176       expand_bytes -= HeapRegion::GrainBytes;
  1177       // Expand the committed region.
  1178       HeapWord* high = (HeapWord*) _g1_storage.high();
  1179       _g1_committed.set_end(high);
  1180       // Create a new HeapRegion.
  1181       MemRegion mr(base, high);
  1182       bool is_zeroed = !_g1_max_committed.contains(base);
  1183       HeapRegion* hr = new HeapRegion(_bot_shared, mr, is_zeroed);
  1185       // Now update max_committed if necessary.
  1186       _g1_max_committed.set_end(MAX2(_g1_max_committed.end(), high));
  1188       // Add it to the HeapRegionSeq.
  1189       _hrs->insert(hr);
  1190       // Set the zero-fill state, according to whether it's already
  1191       // zeroed.
  1193         MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  1194         if (is_zeroed) {
  1195           hr->set_zero_fill_complete();
  1196           put_free_region_on_list_locked(hr);
  1197         } else {
  1198           hr->set_zero_fill_needed();
  1199           put_region_on_unclean_list_locked(hr);
  1202       _free_regions++;
  1203       // And we used up an expansion region to create it.
  1204       _expansion_regions--;
  1205       // Tell the cardtable about it.
  1206       Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
  1207       // And the offset table as well.
  1208       _bot_shared->resize(_g1_committed.word_size());
  1211   if (Verbose && PrintGC) {
  1212     size_t new_mem_size = _g1_storage.committed_size();
  1213     gclog_or_tty->print_cr("Expanding garbage-first heap from %ldK by %ldK to %ldK",
  1214                            old_mem_size/K, aligned_expand_bytes/K,
  1215                            new_mem_size/K);
  1219 void G1CollectedHeap::shrink_helper(size_t shrink_bytes)
  1221   size_t old_mem_size = _g1_storage.committed_size();
  1222   size_t aligned_shrink_bytes =
  1223     ReservedSpace::page_align_size_down(shrink_bytes);
  1224   aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
  1225                                          HeapRegion::GrainBytes);
  1226   size_t num_regions_deleted = 0;
  1227   MemRegion mr = _hrs->shrink_by(aligned_shrink_bytes, num_regions_deleted);
  1229   assert(mr.end() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
  1230   if (mr.byte_size() > 0)
  1231     _g1_storage.shrink_by(mr.byte_size());
  1232   assert(mr.start() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
  1234   _g1_committed.set_end(mr.start());
  1235   _free_regions -= num_regions_deleted;
  1236   _expansion_regions += num_regions_deleted;
  1238   // Tell the cardtable about it.
  1239   Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
  1241   // And the offset table as well.
  1242   _bot_shared->resize(_g1_committed.word_size());
  1244   HeapRegionRemSet::shrink_heap(n_regions());
  1246   if (Verbose && PrintGC) {
  1247     size_t new_mem_size = _g1_storage.committed_size();
  1248     gclog_or_tty->print_cr("Shrinking garbage-first heap from %ldK by %ldK to %ldK",
  1249                            old_mem_size/K, aligned_shrink_bytes/K,
  1250                            new_mem_size/K);
  1254 void G1CollectedHeap::shrink(size_t shrink_bytes) {
  1255   release_gc_alloc_regions();
  1256   tear_down_region_lists();  // We will rebuild them in a moment.
  1257   shrink_helper(shrink_bytes);
  1258   rebuild_region_lists();
  1261 // Public methods.
  1263 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
  1264 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
  1265 #endif // _MSC_VER
  1268 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
  1269   SharedHeap(policy_),
  1270   _g1_policy(policy_),
  1271   _ref_processor(NULL),
  1272   _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
  1273   _bot_shared(NULL),
  1274   _par_alloc_during_gc_lock(Mutex::leaf, "par alloc during GC lock"),
  1275   _objs_with_preserved_marks(NULL), _preserved_marks_of_objs(NULL),
  1276   _evac_failure_scan_stack(NULL) ,
  1277   _mark_in_progress(false),
  1278   _cg1r(NULL), _czft(NULL), _summary_bytes_used(0),
  1279   _cur_alloc_region(NULL),
  1280   _refine_cte_cl(NULL),
  1281   _free_region_list(NULL), _free_region_list_size(0),
  1282   _free_regions(0),
  1283   _popular_object_boundary(NULL),
  1284   _cur_pop_hr_index(0),
  1285   _popular_regions_to_be_evacuated(NULL),
  1286   _pop_obj_rc_at_copy(),
  1287   _full_collection(false),
  1288   _unclean_region_list(),
  1289   _unclean_regions_coming(false),
  1290   _young_list(new YoungList(this)),
  1291   _gc_time_stamp(0),
  1292   _surviving_young_words(NULL),
  1293   _in_cset_fast_test(NULL),
  1294   _in_cset_fast_test_base(NULL)
  1296   _g1h = this; // To catch bugs.
  1297   if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
  1298     vm_exit_during_initialization("Failed necessary allocation.");
  1300   int n_queues = MAX2((int)ParallelGCThreads, 1);
  1301   _task_queues = new RefToScanQueueSet(n_queues);
  1303   int n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
  1304   assert(n_rem_sets > 0, "Invariant.");
  1306   HeapRegionRemSetIterator** iter_arr =
  1307     NEW_C_HEAP_ARRAY(HeapRegionRemSetIterator*, n_queues);
  1308   for (int i = 0; i < n_queues; i++) {
  1309     iter_arr[i] = new HeapRegionRemSetIterator();
  1311   _rem_set_iterator = iter_arr;
  1313   for (int i = 0; i < n_queues; i++) {
  1314     RefToScanQueue* q = new RefToScanQueue();
  1315     q->initialize();
  1316     _task_queues->register_queue(i, q);
  1319   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
  1320     _gc_alloc_regions[ap]       = NULL;
  1321     _gc_alloc_region_counts[ap] = 0;
  1323   guarantee(_task_queues != NULL, "task_queues allocation failure.");
  1326 jint G1CollectedHeap::initialize() {
  1327   os::enable_vtime();
  1329   // Necessary to satisfy locking discipline assertions.
  1331   MutexLocker x(Heap_lock);
  1333   // While there are no constraints in the GC code that HeapWordSize
  1334   // be any particular value, there are multiple other areas in the
  1335   // system which believe this to be true (e.g. oop->object_size in some
  1336   // cases incorrectly returns the size in wordSize units rather than
  1337   // HeapWordSize).
  1338   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
  1340   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
  1341   size_t max_byte_size = collector_policy()->max_heap_byte_size();
  1343   // Ensure that the sizes are properly aligned.
  1344   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
  1345   Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
  1347   // We allocate this in any case, but only do no work if the command line
  1348   // param is off.
  1349   _cg1r = new ConcurrentG1Refine();
  1351   // Reserve the maximum.
  1352   PermanentGenerationSpec* pgs = collector_policy()->permanent_generation();
  1353   // Includes the perm-gen.
  1354   ReservedSpace heap_rs(max_byte_size + pgs->max_size(),
  1355                         HeapRegion::GrainBytes,
  1356                         false /*ism*/);
  1358   if (!heap_rs.is_reserved()) {
  1359     vm_exit_during_initialization("Could not reserve enough space for object heap");
  1360     return JNI_ENOMEM;
  1363   // It is important to do this in a way such that concurrent readers can't
  1364   // temporarily think somethings in the heap.  (I've actually seen this
  1365   // happen in asserts: DLD.)
  1366   _reserved.set_word_size(0);
  1367   _reserved.set_start((HeapWord*)heap_rs.base());
  1368   _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
  1370   _expansion_regions = max_byte_size/HeapRegion::GrainBytes;
  1372   _num_humongous_regions = 0;
  1374   // Create the gen rem set (and barrier set) for the entire reserved region.
  1375   _rem_set = collector_policy()->create_rem_set(_reserved, 2);
  1376   set_barrier_set(rem_set()->bs());
  1377   if (barrier_set()->is_a(BarrierSet::ModRef)) {
  1378     _mr_bs = (ModRefBarrierSet*)_barrier_set;
  1379   } else {
  1380     vm_exit_during_initialization("G1 requires a mod ref bs.");
  1381     return JNI_ENOMEM;
  1384   // Also create a G1 rem set.
  1385   if (G1UseHRIntoRS) {
  1386     if (mr_bs()->is_a(BarrierSet::CardTableModRef)) {
  1387       _g1_rem_set = new HRInto_G1RemSet(this, (CardTableModRefBS*)mr_bs());
  1388     } else {
  1389       vm_exit_during_initialization("G1 requires a cardtable mod ref bs.");
  1390       return JNI_ENOMEM;
  1392   } else {
  1393     _g1_rem_set = new StupidG1RemSet(this);
  1396   // Carve out the G1 part of the heap.
  1398   ReservedSpace g1_rs   = heap_rs.first_part(max_byte_size);
  1399   _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
  1400                            g1_rs.size()/HeapWordSize);
  1401   ReservedSpace perm_gen_rs = heap_rs.last_part(max_byte_size);
  1403   _perm_gen = pgs->init(perm_gen_rs, pgs->init_size(), rem_set());
  1405   _g1_storage.initialize(g1_rs, 0);
  1406   _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
  1407   _g1_max_committed = _g1_committed;
  1408   _hrs = new HeapRegionSeq(_expansion_regions);
  1409   guarantee(_hrs != NULL, "Couldn't allocate HeapRegionSeq");
  1410   guarantee(_cur_alloc_region == NULL, "from constructor");
  1412   _bot_shared = new G1BlockOffsetSharedArray(_reserved,
  1413                                              heap_word_size(init_byte_size));
  1415   _g1h = this;
  1417   // Create the ConcurrentMark data structure and thread.
  1418   // (Must do this late, so that "max_regions" is defined.)
  1419   _cm       = new ConcurrentMark(heap_rs, (int) max_regions());
  1420   _cmThread = _cm->cmThread();
  1422   // ...and the concurrent zero-fill thread, if necessary.
  1423   if (G1ConcZeroFill) {
  1424     _czft = new ConcurrentZFThread();
  1429   // Allocate the popular regions; take them off free lists.
  1430   size_t pop_byte_size = G1NumPopularRegions * HeapRegion::GrainBytes;
  1431   expand(pop_byte_size);
  1432   _popular_object_boundary =
  1433     _g1_reserved.start() + (G1NumPopularRegions * HeapRegion::GrainWords);
  1434   for (int i = 0; i < G1NumPopularRegions; i++) {
  1435     HeapRegion* hr = newAllocRegion(HeapRegion::GrainWords);
  1436     //    assert(hr != NULL && hr->bottom() < _popular_object_boundary,
  1437     //     "Should be enough, and all should be below boundary.");
  1438     hr->set_popular(true);
  1440   assert(_cur_pop_hr_index == 0, "Start allocating at the first region.");
  1442   // Initialize the from_card cache structure of HeapRegionRemSet.
  1443   HeapRegionRemSet::init_heap(max_regions());
  1445   // Now expand into the rest of the initial heap size.
  1446   expand(init_byte_size - pop_byte_size);
  1448   // Perform any initialization actions delegated to the policy.
  1449   g1_policy()->init();
  1451   g1_policy()->note_start_of_mark_thread();
  1453   _refine_cte_cl =
  1454     new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
  1455                                     g1_rem_set(),
  1456                                     concurrent_g1_refine());
  1457   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
  1459   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
  1460                                                SATB_Q_FL_lock,
  1461                                                0,
  1462                                                Shared_SATB_Q_lock);
  1463   if (G1RSBarrierUseQueue) {
  1464     JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
  1465                                                   DirtyCardQ_FL_lock,
  1466                                                   G1DirtyCardQueueMax,
  1467                                                   Shared_DirtyCardQ_lock);
  1469   // In case we're keeping closure specialization stats, initialize those
  1470   // counts and that mechanism.
  1471   SpecializationStats::clear();
  1473   _gc_alloc_region_list = NULL;
  1475   // Do later initialization work for concurrent refinement.
  1476   _cg1r->init();
  1478   const char* group_names[] = { "CR", "ZF", "CM", "CL" };
  1479   GCOverheadReporter::initGCOverheadReporter(4, group_names);
  1481   return JNI_OK;
  1484 void G1CollectedHeap::ref_processing_init() {
  1485   SharedHeap::ref_processing_init();
  1486   MemRegion mr = reserved_region();
  1487   _ref_processor = ReferenceProcessor::create_ref_processor(
  1488                                          mr,    // span
  1489                                          false, // Reference discovery is not atomic
  1490                                                 // (though it shouldn't matter here.)
  1491                                          true,  // mt_discovery
  1492                                          NULL,  // is alive closure: need to fill this in for efficiency
  1493                                          ParallelGCThreads,
  1494                                          ParallelRefProcEnabled,
  1495                                          true); // Setting next fields of discovered
  1496                                                 // lists requires a barrier.
  1499 size_t G1CollectedHeap::capacity() const {
  1500   return _g1_committed.byte_size();
  1503 void G1CollectedHeap::iterate_dirty_card_closure(bool concurrent,
  1504                                                  int worker_i) {
  1505   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
  1506   int n_completed_buffers = 0;
  1507   while (dcqs.apply_closure_to_completed_buffer(worker_i, 0, true)) {
  1508     n_completed_buffers++;
  1510   g1_policy()->record_update_rs_processed_buffers(worker_i,
  1511                                                   (double) n_completed_buffers);
  1512   dcqs.clear_n_completed_buffers();
  1513   // Finish up the queue...
  1514   if (worker_i == 0) concurrent_g1_refine()->clean_up_cache(worker_i,
  1515                                                             g1_rem_set());
  1516   assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
  1520 // Computes the sum of the storage used by the various regions.
  1522 size_t G1CollectedHeap::used() const {
  1523   assert(Heap_lock->owner() != NULL,
  1524          "Should be owned on this thread's behalf.");
  1525   size_t result = _summary_bytes_used;
  1526   if (_cur_alloc_region != NULL)
  1527     result += _cur_alloc_region->used();
  1528   return result;
  1531 class SumUsedClosure: public HeapRegionClosure {
  1532   size_t _used;
  1533 public:
  1534   SumUsedClosure() : _used(0) {}
  1535   bool doHeapRegion(HeapRegion* r) {
  1536     if (!r->continuesHumongous()) {
  1537       _used += r->used();
  1539     return false;
  1541   size_t result() { return _used; }
  1542 };
  1544 size_t G1CollectedHeap::recalculate_used() const {
  1545   SumUsedClosure blk;
  1546   _hrs->iterate(&blk);
  1547   return blk.result();
  1550 #ifndef PRODUCT
  1551 class SumUsedRegionsClosure: public HeapRegionClosure {
  1552   size_t _num;
  1553 public:
  1554   // _num is set to 1 to account for the popular region
  1555   SumUsedRegionsClosure() : _num(G1NumPopularRegions) {}
  1556   bool doHeapRegion(HeapRegion* r) {
  1557     if (r->continuesHumongous() || r->used() > 0 || r->is_gc_alloc_region()) {
  1558       _num += 1;
  1560     return false;
  1562   size_t result() { return _num; }
  1563 };
  1565 size_t G1CollectedHeap::recalculate_used_regions() const {
  1566   SumUsedRegionsClosure blk;
  1567   _hrs->iterate(&blk);
  1568   return blk.result();
  1570 #endif // PRODUCT
  1572 size_t G1CollectedHeap::unsafe_max_alloc() {
  1573   if (_free_regions > 0) return HeapRegion::GrainBytes;
  1574   // otherwise, is there space in the current allocation region?
  1576   // We need to store the current allocation region in a local variable
  1577   // here. The problem is that this method doesn't take any locks and
  1578   // there may be other threads which overwrite the current allocation
  1579   // region field. attempt_allocation(), for example, sets it to NULL
  1580   // and this can happen *after* the NULL check here but before the call
  1581   // to free(), resulting in a SIGSEGV. Note that this doesn't appear
  1582   // to be a problem in the optimized build, since the two loads of the
  1583   // current allocation region field are optimized away.
  1584   HeapRegion* car = _cur_alloc_region;
  1586   // FIXME: should iterate over all regions?
  1587   if (car == NULL) {
  1588     return 0;
  1590   return car->free();
  1593 void G1CollectedHeap::collect(GCCause::Cause cause) {
  1594   // The caller doesn't have the Heap_lock
  1595   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
  1596   MutexLocker ml(Heap_lock);
  1597   collect_locked(cause);
  1600 void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
  1601   assert(Thread::current()->is_VM_thread(), "Precondition#1");
  1602   assert(Heap_lock->is_locked(), "Precondition#2");
  1603   GCCauseSetter gcs(this, cause);
  1604   switch (cause) {
  1605     case GCCause::_heap_inspection:
  1606     case GCCause::_heap_dump: {
  1607       HandleMark hm;
  1608       do_full_collection(false);         // don't clear all soft refs
  1609       break;
  1611     default: // XXX FIX ME
  1612       ShouldNotReachHere(); // Unexpected use of this function
  1617 void G1CollectedHeap::collect_locked(GCCause::Cause cause) {
  1618   // Don't want to do a GC until cleanup is completed.
  1619   wait_for_cleanup_complete();
  1621   // Read the GC count while holding the Heap_lock
  1622   int gc_count_before = SharedHeap::heap()->total_collections();
  1624     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
  1625     VM_G1CollectFull op(gc_count_before, cause);
  1626     VMThread::execute(&op);
  1630 bool G1CollectedHeap::is_in(const void* p) const {
  1631   if (_g1_committed.contains(p)) {
  1632     HeapRegion* hr = _hrs->addr_to_region(p);
  1633     return hr->is_in(p);
  1634   } else {
  1635     return _perm_gen->as_gen()->is_in(p);
  1639 // Iteration functions.
  1641 // Iterates an OopClosure over all ref-containing fields of objects
  1642 // within a HeapRegion.
  1644 class IterateOopClosureRegionClosure: public HeapRegionClosure {
  1645   MemRegion _mr;
  1646   OopClosure* _cl;
  1647 public:
  1648   IterateOopClosureRegionClosure(MemRegion mr, OopClosure* cl)
  1649     : _mr(mr), _cl(cl) {}
  1650   bool doHeapRegion(HeapRegion* r) {
  1651     if (! r->continuesHumongous()) {
  1652       r->oop_iterate(_cl);
  1654     return false;
  1656 };
  1658 void G1CollectedHeap::oop_iterate(OopClosure* cl) {
  1659   IterateOopClosureRegionClosure blk(_g1_committed, cl);
  1660   _hrs->iterate(&blk);
  1663 void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl) {
  1664   IterateOopClosureRegionClosure blk(mr, cl);
  1665   _hrs->iterate(&blk);
  1668 // Iterates an ObjectClosure over all objects within a HeapRegion.
  1670 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
  1671   ObjectClosure* _cl;
  1672 public:
  1673   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
  1674   bool doHeapRegion(HeapRegion* r) {
  1675     if (! r->continuesHumongous()) {
  1676       r->object_iterate(_cl);
  1678     return false;
  1680 };
  1682 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
  1683   IterateObjectClosureRegionClosure blk(cl);
  1684   _hrs->iterate(&blk);
  1687 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
  1688   // FIXME: is this right?
  1689   guarantee(false, "object_iterate_since_last_GC not supported by G1 heap");
  1692 // Calls a SpaceClosure on a HeapRegion.
  1694 class SpaceClosureRegionClosure: public HeapRegionClosure {
  1695   SpaceClosure* _cl;
  1696 public:
  1697   SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
  1698   bool doHeapRegion(HeapRegion* r) {
  1699     _cl->do_space(r);
  1700     return false;
  1702 };
  1704 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
  1705   SpaceClosureRegionClosure blk(cl);
  1706   _hrs->iterate(&blk);
  1709 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) {
  1710   _hrs->iterate(cl);
  1713 void G1CollectedHeap::heap_region_iterate_from(HeapRegion* r,
  1714                                                HeapRegionClosure* cl) {
  1715   _hrs->iterate_from(r, cl);
  1718 void
  1719 G1CollectedHeap::heap_region_iterate_from(int idx, HeapRegionClosure* cl) {
  1720   _hrs->iterate_from(idx, cl);
  1723 HeapRegion* G1CollectedHeap::region_at(size_t idx) { return _hrs->at(idx); }
  1725 void
  1726 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
  1727                                                  int worker,
  1728                                                  jint claim_value) {
  1729   const size_t regions = n_regions();
  1730   const size_t worker_num = (ParallelGCThreads > 0 ? ParallelGCThreads : 1);
  1731   // try to spread out the starting points of the workers
  1732   const size_t start_index = regions / worker_num * (size_t) worker;
  1734   // each worker will actually look at all regions
  1735   for (size_t count = 0; count < regions; ++count) {
  1736     const size_t index = (start_index + count) % regions;
  1737     assert(0 <= index && index < regions, "sanity");
  1738     HeapRegion* r = region_at(index);
  1739     // we'll ignore "continues humongous" regions (we'll process them
  1740     // when we come across their corresponding "start humongous"
  1741     // region) and regions already claimed
  1742     if (r->claim_value() == claim_value || r->continuesHumongous()) {
  1743       continue;
  1745     // OK, try to claim it
  1746     if (r->claimHeapRegion(claim_value)) {
  1747       // success!
  1748       assert(!r->continuesHumongous(), "sanity");
  1749       if (r->startsHumongous()) {
  1750         // If the region is "starts humongous" we'll iterate over its
  1751         // "continues humongous" first; in fact we'll do them
  1752         // first. The order is important. In on case, calling the
  1753         // closure on the "starts humongous" region might de-allocate
  1754         // and clear all its "continues humongous" regions and, as a
  1755         // result, we might end up processing them twice. So, we'll do
  1756         // them first (notice: most closures will ignore them anyway) and
  1757         // then we'll do the "starts humongous" region.
  1758         for (size_t ch_index = index + 1; ch_index < regions; ++ch_index) {
  1759           HeapRegion* chr = region_at(ch_index);
  1761           // if the region has already been claimed or it's not
  1762           // "continues humongous" we're done
  1763           if (chr->claim_value() == claim_value ||
  1764               !chr->continuesHumongous()) {
  1765             break;
  1768           // Noone should have claimed it directly. We can given
  1769           // that we claimed its "starts humongous" region.
  1770           assert(chr->claim_value() != claim_value, "sanity");
  1771           assert(chr->humongous_start_region() == r, "sanity");
  1773           if (chr->claimHeapRegion(claim_value)) {
  1774             // we should always be able to claim it; noone else should
  1775             // be trying to claim this region
  1777             bool res2 = cl->doHeapRegion(chr);
  1778             assert(!res2, "Should not abort");
  1780             // Right now, this holds (i.e., no closure that actually
  1781             // does something with "continues humongous" regions
  1782             // clears them). We might have to weaken it in the future,
  1783             // but let's leave these two asserts here for extra safety.
  1784             assert(chr->continuesHumongous(), "should still be the case");
  1785             assert(chr->humongous_start_region() == r, "sanity");
  1786           } else {
  1787             guarantee(false, "we should not reach here");
  1792       assert(!r->continuesHumongous(), "sanity");
  1793       bool res = cl->doHeapRegion(r);
  1794       assert(!res, "Should not abort");
  1799 class ResetClaimValuesClosure: public HeapRegionClosure {
  1800 public:
  1801   bool doHeapRegion(HeapRegion* r) {
  1802     r->set_claim_value(HeapRegion::InitialClaimValue);
  1803     return false;
  1805 };
  1807 void
  1808 G1CollectedHeap::reset_heap_region_claim_values() {
  1809   ResetClaimValuesClosure blk;
  1810   heap_region_iterate(&blk);
  1813 #ifdef ASSERT
  1814 // This checks whether all regions in the heap have the correct claim
  1815 // value. I also piggy-backed on this a check to ensure that the
  1816 // humongous_start_region() information on "continues humongous"
  1817 // regions is correct.
  1819 class CheckClaimValuesClosure : public HeapRegionClosure {
  1820 private:
  1821   jint _claim_value;
  1822   size_t _failures;
  1823   HeapRegion* _sh_region;
  1824 public:
  1825   CheckClaimValuesClosure(jint claim_value) :
  1826     _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
  1827   bool doHeapRegion(HeapRegion* r) {
  1828     if (r->claim_value() != _claim_value) {
  1829       gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
  1830                              "claim value = %d, should be %d",
  1831                              r->bottom(), r->end(), r->claim_value(),
  1832                              _claim_value);
  1833       ++_failures;
  1835     if (!r->isHumongous()) {
  1836       _sh_region = NULL;
  1837     } else if (r->startsHumongous()) {
  1838       _sh_region = r;
  1839     } else if (r->continuesHumongous()) {
  1840       if (r->humongous_start_region() != _sh_region) {
  1841         gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
  1842                                "HS = "PTR_FORMAT", should be "PTR_FORMAT,
  1843                                r->bottom(), r->end(),
  1844                                r->humongous_start_region(),
  1845                                _sh_region);
  1846         ++_failures;
  1849     return false;
  1851   size_t failures() {
  1852     return _failures;
  1854 };
  1856 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
  1857   CheckClaimValuesClosure cl(claim_value);
  1858   heap_region_iterate(&cl);
  1859   return cl.failures() == 0;
  1861 #endif // ASSERT
  1863 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
  1864   HeapRegion* r = g1_policy()->collection_set();
  1865   while (r != NULL) {
  1866     HeapRegion* next = r->next_in_collection_set();
  1867     if (cl->doHeapRegion(r)) {
  1868       cl->incomplete();
  1869       return;
  1871     r = next;
  1875 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
  1876                                                   HeapRegionClosure *cl) {
  1877   assert(r->in_collection_set(),
  1878          "Start region must be a member of the collection set.");
  1879   HeapRegion* cur = r;
  1880   while (cur != NULL) {
  1881     HeapRegion* next = cur->next_in_collection_set();
  1882     if (cl->doHeapRegion(cur) && false) {
  1883       cl->incomplete();
  1884       return;
  1886     cur = next;
  1888   cur = g1_policy()->collection_set();
  1889   while (cur != r) {
  1890     HeapRegion* next = cur->next_in_collection_set();
  1891     if (cl->doHeapRegion(cur) && false) {
  1892       cl->incomplete();
  1893       return;
  1895     cur = next;
  1899 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
  1900   return _hrs->length() > 0 ? _hrs->at(0) : NULL;
  1904 Space* G1CollectedHeap::space_containing(const void* addr) const {
  1905   Space* res = heap_region_containing(addr);
  1906   if (res == NULL)
  1907     res = perm_gen()->space_containing(addr);
  1908   return res;
  1911 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
  1912   Space* sp = space_containing(addr);
  1913   if (sp != NULL) {
  1914     return sp->block_start(addr);
  1916   return NULL;
  1919 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
  1920   Space* sp = space_containing(addr);
  1921   assert(sp != NULL, "block_size of address outside of heap");
  1922   return sp->block_size(addr);
  1925 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
  1926   Space* sp = space_containing(addr);
  1927   return sp->block_is_obj(addr);
  1930 bool G1CollectedHeap::supports_tlab_allocation() const {
  1931   return true;
  1934 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
  1935   return HeapRegion::GrainBytes;
  1938 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
  1939   // Return the remaining space in the cur alloc region, but not less than
  1940   // the min TLAB size.
  1941   // Also, no more than half the region size, since we can't allow tlabs to
  1942   // grow big enough to accomodate humongous objects.
  1944   // We need to story it locally, since it might change between when we
  1945   // test for NULL and when we use it later.
  1946   ContiguousSpace* cur_alloc_space = _cur_alloc_region;
  1947   if (cur_alloc_space == NULL) {
  1948     return HeapRegion::GrainBytes/2;
  1949   } else {
  1950     return MAX2(MIN2(cur_alloc_space->free(),
  1951                      (size_t)(HeapRegion::GrainBytes/2)),
  1952                 (size_t)MinTLABSize);
  1956 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t size) {
  1957   bool dummy;
  1958   return G1CollectedHeap::mem_allocate(size, false, true, &dummy);
  1961 bool G1CollectedHeap::allocs_are_zero_filled() {
  1962   return false;
  1965 size_t G1CollectedHeap::large_typearray_limit() {
  1966   // FIXME
  1967   return HeapRegion::GrainBytes/HeapWordSize;
  1970 size_t G1CollectedHeap::max_capacity() const {
  1971   return _g1_committed.byte_size();
  1974 jlong G1CollectedHeap::millis_since_last_gc() {
  1975   // assert(false, "NYI");
  1976   return 0;
  1980 void G1CollectedHeap::prepare_for_verify() {
  1981   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
  1982     ensure_parsability(false);
  1984   g1_rem_set()->prepare_for_verify();
  1987 class VerifyLivenessOopClosure: public OopClosure {
  1988   G1CollectedHeap* g1h;
  1989 public:
  1990   VerifyLivenessOopClosure(G1CollectedHeap* _g1h) {
  1991     g1h = _g1h;
  1993   void do_oop(narrowOop *p) {
  1994     guarantee(false, "NYI");
  1996   void do_oop(oop *p) {
  1997     oop obj = *p;
  1998     assert(obj == NULL || !g1h->is_obj_dead(obj),
  1999            "Dead object referenced by a not dead object");
  2001 };
  2003 class VerifyObjsInRegionClosure: public ObjectClosure {
  2004   G1CollectedHeap* _g1h;
  2005   size_t _live_bytes;
  2006   HeapRegion *_hr;
  2007 public:
  2008   VerifyObjsInRegionClosure(HeapRegion *hr) : _live_bytes(0), _hr(hr) {
  2009     _g1h = G1CollectedHeap::heap();
  2011   void do_object(oop o) {
  2012     VerifyLivenessOopClosure isLive(_g1h);
  2013     assert(o != NULL, "Huh?");
  2014     if (!_g1h->is_obj_dead(o)) {
  2015       o->oop_iterate(&isLive);
  2016       if (!_hr->obj_allocated_since_prev_marking(o))
  2017         _live_bytes += (o->size() * HeapWordSize);
  2020   size_t live_bytes() { return _live_bytes; }
  2021 };
  2023 class PrintObjsInRegionClosure : public ObjectClosure {
  2024   HeapRegion *_hr;
  2025   G1CollectedHeap *_g1;
  2026 public:
  2027   PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
  2028     _g1 = G1CollectedHeap::heap();
  2029   };
  2031   void do_object(oop o) {
  2032     if (o != NULL) {
  2033       HeapWord *start = (HeapWord *) o;
  2034       size_t word_sz = o->size();
  2035       gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
  2036                           " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
  2037                           (void*) o, word_sz,
  2038                           _g1->isMarkedPrev(o),
  2039                           _g1->isMarkedNext(o),
  2040                           _hr->obj_allocated_since_prev_marking(o));
  2041       HeapWord *end = start + word_sz;
  2042       HeapWord *cur;
  2043       int *val;
  2044       for (cur = start; cur < end; cur++) {
  2045         val = (int *) cur;
  2046         gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
  2050 };
  2052 class VerifyRegionClosure: public HeapRegionClosure {
  2053 public:
  2054   bool _allow_dirty;
  2055   bool _par;
  2056   VerifyRegionClosure(bool allow_dirty, bool par = false)
  2057     : _allow_dirty(allow_dirty), _par(par) {}
  2058   bool doHeapRegion(HeapRegion* r) {
  2059     guarantee(_par || r->claim_value() == HeapRegion::InitialClaimValue,
  2060               "Should be unclaimed at verify points.");
  2061     if (r->isHumongous()) {
  2062       if (r->startsHumongous()) {
  2063         // Verify the single H object.
  2064         oop(r->bottom())->verify();
  2065         size_t word_sz = oop(r->bottom())->size();
  2066         guarantee(r->top() == r->bottom() + word_sz,
  2067                   "Only one object in a humongous region");
  2069     } else {
  2070       VerifyObjsInRegionClosure not_dead_yet_cl(r);
  2071       r->verify(_allow_dirty);
  2072       r->object_iterate(&not_dead_yet_cl);
  2073       guarantee(r->max_live_bytes() >= not_dead_yet_cl.live_bytes(),
  2074                 "More live objects than counted in last complete marking.");
  2076     return false;
  2078 };
  2080 class VerifyRootsClosure: public OopsInGenClosure {
  2081 private:
  2082   G1CollectedHeap* _g1h;
  2083   bool             _failures;
  2085 public:
  2086   VerifyRootsClosure() :
  2087     _g1h(G1CollectedHeap::heap()), _failures(false) { }
  2089   bool failures() { return _failures; }
  2091   void do_oop(narrowOop* p) {
  2092     guarantee(false, "NYI");
  2095   void do_oop(oop* p) {
  2096     oop obj = *p;
  2097     if (obj != NULL) {
  2098       if (_g1h->is_obj_dead(obj)) {
  2099         gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
  2100                                "points to dead obj "PTR_FORMAT, p, (void*) obj);
  2101         obj->print_on(gclog_or_tty);
  2102         _failures = true;
  2106 };
  2108 // This is the task used for parallel heap verification.
  2110 class G1ParVerifyTask: public AbstractGangTask {
  2111 private:
  2112   G1CollectedHeap* _g1h;
  2113   bool _allow_dirty;
  2115 public:
  2116   G1ParVerifyTask(G1CollectedHeap* g1h, bool allow_dirty) :
  2117     AbstractGangTask("Parallel verify task"),
  2118     _g1h(g1h), _allow_dirty(allow_dirty) { }
  2120   void work(int worker_i) {
  2121     VerifyRegionClosure blk(_allow_dirty, true);
  2122     _g1h->heap_region_par_iterate_chunked(&blk, worker_i,
  2123                                           HeapRegion::ParVerifyClaimValue);
  2125 };
  2127 void G1CollectedHeap::verify(bool allow_dirty, bool silent) {
  2128   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
  2129     if (!silent) { gclog_or_tty->print("roots "); }
  2130     VerifyRootsClosure rootsCl;
  2131     process_strong_roots(false,
  2132                          SharedHeap::SO_AllClasses,
  2133                          &rootsCl,
  2134                          &rootsCl);
  2135     rem_set()->invalidate(perm_gen()->used_region(), false);
  2136     if (!silent) { gclog_or_tty->print("heapRegions "); }
  2137     if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
  2138       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  2139              "sanity check");
  2141       G1ParVerifyTask task(this, allow_dirty);
  2142       int n_workers = workers()->total_workers();
  2143       set_par_threads(n_workers);
  2144       workers()->run_task(&task);
  2145       set_par_threads(0);
  2147       assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
  2148              "sanity check");
  2150       reset_heap_region_claim_values();
  2152       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  2153              "sanity check");
  2154     } else {
  2155       VerifyRegionClosure blk(allow_dirty);
  2156       _hrs->iterate(&blk);
  2158     if (!silent) gclog_or_tty->print("remset ");
  2159     rem_set()->verify();
  2160     guarantee(!rootsCl.failures(), "should not have had failures");
  2161   } else {
  2162     if (!silent) gclog_or_tty->print("(SKIPPING roots, heapRegions, remset) ");
  2166 class PrintRegionClosure: public HeapRegionClosure {
  2167   outputStream* _st;
  2168 public:
  2169   PrintRegionClosure(outputStream* st) : _st(st) {}
  2170   bool doHeapRegion(HeapRegion* r) {
  2171     r->print_on(_st);
  2172     return false;
  2174 };
  2176 void G1CollectedHeap::print() const { print_on(gclog_or_tty); }
  2178 void G1CollectedHeap::print_on(outputStream* st) const {
  2179   PrintRegionClosure blk(st);
  2180   _hrs->iterate(&blk);
  2183 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
  2184   if (ParallelGCThreads > 0) {
  2185     workers()->print_worker_threads();
  2187   st->print("\"G1 concurrent mark GC Thread\" ");
  2188   _cmThread->print();
  2189   st->cr();
  2190   st->print("\"G1 concurrent refinement GC Thread\" ");
  2191   _cg1r->cg1rThread()->print_on(st);
  2192   st->cr();
  2193   st->print("\"G1 zero-fill GC Thread\" ");
  2194   _czft->print_on(st);
  2195   st->cr();
  2198 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
  2199   if (ParallelGCThreads > 0) {
  2200     workers()->threads_do(tc);
  2202   tc->do_thread(_cmThread);
  2203   tc->do_thread(_cg1r->cg1rThread());
  2204   tc->do_thread(_czft);
  2207 void G1CollectedHeap::print_tracing_info() const {
  2208   concurrent_g1_refine()->print_final_card_counts();
  2210   // We'll overload this to mean "trace GC pause statistics."
  2211   if (TraceGen0Time || TraceGen1Time) {
  2212     // The "G1CollectorPolicy" is keeping track of these stats, so delegate
  2213     // to that.
  2214     g1_policy()->print_tracing_info();
  2216   if (SummarizeG1RSStats) {
  2217     g1_rem_set()->print_summary_info();
  2219   if (SummarizeG1ConcMark) {
  2220     concurrent_mark()->print_summary_info();
  2222   if (SummarizeG1ZFStats) {
  2223     ConcurrentZFThread::print_summary_info();
  2225   if (G1SummarizePopularity) {
  2226     print_popularity_summary_info();
  2228   g1_policy()->print_yg_surv_rate_info();
  2230   GCOverheadReporter::printGCOverhead();
  2232   SpecializationStats::print();
  2236 int G1CollectedHeap::addr_to_arena_id(void* addr) const {
  2237   HeapRegion* hr = heap_region_containing(addr);
  2238   if (hr == NULL) {
  2239     return 0;
  2240   } else {
  2241     return 1;
  2245 G1CollectedHeap* G1CollectedHeap::heap() {
  2246   assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
  2247          "not a garbage-first heap");
  2248   return _g1h;
  2251 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
  2252   if (PrintHeapAtGC){
  2253     gclog_or_tty->print_cr(" {Heap before GC collections=%d:", total_collections());
  2254     Universe::print();
  2256   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
  2257   // Call allocation profiler
  2258   AllocationProfiler::iterate_since_last_gc();
  2259   // Fill TLAB's and such
  2260   ensure_parsability(true);
  2263 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
  2264   // FIXME: what is this about?
  2265   // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
  2266   // is set.
  2267   COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
  2268                         "derived pointer present"));
  2270   if (PrintHeapAtGC){
  2271     gclog_or_tty->print_cr(" Heap after GC collections=%d:", total_collections());
  2272     Universe::print();
  2273     gclog_or_tty->print("} ");
  2277 void G1CollectedHeap::do_collection_pause() {
  2278   // Read the GC count while holding the Heap_lock
  2279   // we need to do this _before_ wait_for_cleanup_complete(), to
  2280   // ensure that we do not give up the heap lock and potentially
  2281   // pick up the wrong count
  2282   int gc_count_before = SharedHeap::heap()->total_collections();
  2284   // Don't want to do a GC pause while cleanup is being completed!
  2285   wait_for_cleanup_complete();
  2287   g1_policy()->record_stop_world_start();
  2289     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
  2290     VM_G1IncCollectionPause op(gc_count_before);
  2291     VMThread::execute(&op);
  2295 void
  2296 G1CollectedHeap::doConcurrentMark() {
  2297   if (G1ConcMark) {
  2298     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2299     if (!_cmThread->in_progress()) {
  2300       _cmThread->set_started();
  2301       CGC_lock->notify();
  2306 class VerifyMarkedObjsClosure: public ObjectClosure {
  2307     G1CollectedHeap* _g1h;
  2308     public:
  2309     VerifyMarkedObjsClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
  2310     void do_object(oop obj) {
  2311       assert(obj->mark()->is_marked() ? !_g1h->is_obj_dead(obj) : true,
  2312              "markandsweep mark should agree with concurrent deadness");
  2314 };
  2316 void
  2317 G1CollectedHeap::checkConcurrentMark() {
  2318     VerifyMarkedObjsClosure verifycl(this);
  2319     doConcurrentMark();
  2320     //    MutexLockerEx x(getMarkBitMapLock(),
  2321     //              Mutex::_no_safepoint_check_flag);
  2322     object_iterate(&verifycl);
  2325 void G1CollectedHeap::do_sync_mark() {
  2326   _cm->checkpointRootsInitial();
  2327   _cm->markFromRoots();
  2328   _cm->checkpointRootsFinal(false);
  2331 // <NEW PREDICTION>
  2333 double G1CollectedHeap::predict_region_elapsed_time_ms(HeapRegion *hr,
  2334                                                        bool young) {
  2335   return _g1_policy->predict_region_elapsed_time_ms(hr, young);
  2338 void G1CollectedHeap::check_if_region_is_too_expensive(double
  2339                                                            predicted_time_ms) {
  2340   _g1_policy->check_if_region_is_too_expensive(predicted_time_ms);
  2343 size_t G1CollectedHeap::pending_card_num() {
  2344   size_t extra_cards = 0;
  2345   JavaThread *curr = Threads::first();
  2346   while (curr != NULL) {
  2347     DirtyCardQueue& dcq = curr->dirty_card_queue();
  2348     extra_cards += dcq.size();
  2349     curr = curr->next();
  2351   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
  2352   size_t buffer_size = dcqs.buffer_size();
  2353   size_t buffer_num = dcqs.completed_buffers_num();
  2354   return buffer_size * buffer_num + extra_cards;
  2357 size_t G1CollectedHeap::max_pending_card_num() {
  2358   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
  2359   size_t buffer_size = dcqs.buffer_size();
  2360   size_t buffer_num  = dcqs.completed_buffers_num();
  2361   int thread_num  = Threads::number_of_threads();
  2362   return (buffer_num + thread_num) * buffer_size;
  2365 size_t G1CollectedHeap::cards_scanned() {
  2366   HRInto_G1RemSet* g1_rset = (HRInto_G1RemSet*) g1_rem_set();
  2367   return g1_rset->cardsScanned();
  2370 void
  2371 G1CollectedHeap::setup_surviving_young_words() {
  2372   guarantee( _surviving_young_words == NULL, "pre-condition" );
  2373   size_t array_length = g1_policy()->young_cset_length();
  2374   _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, array_length);
  2375   if (_surviving_young_words == NULL) {
  2376     vm_exit_out_of_memory(sizeof(size_t) * array_length,
  2377                           "Not enough space for young surv words summary.");
  2379   memset(_surviving_young_words, 0, array_length * sizeof(size_t));
  2380   for (size_t i = 0;  i < array_length; ++i) {
  2381     guarantee( _surviving_young_words[i] == 0, "invariant" );
  2385 void
  2386 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
  2387   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  2388   size_t array_length = g1_policy()->young_cset_length();
  2389   for (size_t i = 0; i < array_length; ++i)
  2390     _surviving_young_words[i] += surv_young_words[i];
  2393 void
  2394 G1CollectedHeap::cleanup_surviving_young_words() {
  2395   guarantee( _surviving_young_words != NULL, "pre-condition" );
  2396   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words);
  2397   _surviving_young_words = NULL;
  2400 // </NEW PREDICTION>
  2402 void
  2403 G1CollectedHeap::do_collection_pause_at_safepoint(HeapRegion* popular_region) {
  2404   char verbose_str[128];
  2405   sprintf(verbose_str, "GC pause ");
  2406   if (popular_region != NULL)
  2407     strcat(verbose_str, "(popular)");
  2408   else if (g1_policy()->in_young_gc_mode()) {
  2409     if (g1_policy()->full_young_gcs())
  2410       strcat(verbose_str, "(young)");
  2411     else
  2412       strcat(verbose_str, "(partial)");
  2414   bool reset_should_initiate_conc_mark = false;
  2415   if (popular_region != NULL && g1_policy()->should_initiate_conc_mark()) {
  2416     // we currently do not allow an initial mark phase to be piggy-backed
  2417     // on a popular pause
  2418     reset_should_initiate_conc_mark = true;
  2419     g1_policy()->unset_should_initiate_conc_mark();
  2421   if (g1_policy()->should_initiate_conc_mark())
  2422     strcat(verbose_str, " (initial-mark)");
  2424   GCCauseSetter x(this, (popular_region == NULL ?
  2425                          GCCause::_g1_inc_collection_pause :
  2426                          GCCause::_g1_pop_region_collection_pause));
  2428   // if PrintGCDetails is on, we'll print long statistics information
  2429   // in the collector policy code, so let's not print this as the output
  2430   // is messy if we do.
  2431   gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
  2432   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  2433   TraceTime t(verbose_str, PrintGC && !PrintGCDetails, true, gclog_or_tty);
  2435   ResourceMark rm;
  2436   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
  2437   assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
  2438   guarantee(!is_gc_active(), "collection is not reentrant");
  2439   assert(regions_accounted_for(), "Region leakage!");
  2441   increment_gc_time_stamp();
  2443   if (g1_policy()->in_young_gc_mode()) {
  2444     assert(check_young_list_well_formed(),
  2445                 "young list should be well formed");
  2448   if (GC_locker::is_active()) {
  2449     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
  2452   bool abandoned = false;
  2453   { // Call to jvmpi::post_class_unload_events must occur outside of active GC
  2454     IsGCActiveMark x;
  2456     gc_prologue(false);
  2457     increment_total_collections();
  2459 #if G1_REM_SET_LOGGING
  2460     gclog_or_tty->print_cr("\nJust chose CS, heap:");
  2461     print();
  2462 #endif
  2464     if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
  2465       HandleMark hm;  // Discard invalid handles created during verification
  2466       prepare_for_verify();
  2467       gclog_or_tty->print(" VerifyBeforeGC:");
  2468       Universe::verify(false);
  2471     COMPILER2_PRESENT(DerivedPointerTable::clear());
  2473     // We want to turn off ref discovery, if necessary, and turn it back on
  2474     // on again later if we do.
  2475     bool was_enabled = ref_processor()->discovery_enabled();
  2476     if (was_enabled) ref_processor()->disable_discovery();
  2478     // Forget the current alloc region (we might even choose it to be part
  2479     // of the collection set!).
  2480     abandon_cur_alloc_region();
  2482     // The elapsed time induced by the start time below deliberately elides
  2483     // the possible verification above.
  2484     double start_time_sec = os::elapsedTime();
  2485     GCOverheadReporter::recordSTWStart(start_time_sec);
  2486     size_t start_used_bytes = used();
  2487     if (!G1ConcMark) {
  2488       do_sync_mark();
  2491     g1_policy()->record_collection_pause_start(start_time_sec,
  2492                                                start_used_bytes);
  2494     guarantee(_in_cset_fast_test == NULL, "invariant");
  2495     guarantee(_in_cset_fast_test_base == NULL, "invariant");
  2496     _in_cset_fast_test_length = n_regions();
  2497     _in_cset_fast_test_base =
  2498                              NEW_C_HEAP_ARRAY(bool, _in_cset_fast_test_length);
  2499     memset(_in_cset_fast_test_base, false,
  2500                                      _in_cset_fast_test_length * sizeof(bool));
  2501     // We're biasing _in_cset_fast_test to avoid subtracting the
  2502     // beginning of the heap every time we want to index; basically
  2503     // it's the same with what we do with the card table.
  2504     _in_cset_fast_test = _in_cset_fast_test_base -
  2505               ((size_t) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
  2507 #if SCAN_ONLY_VERBOSE
  2508     _young_list->print();
  2509 #endif // SCAN_ONLY_VERBOSE
  2511     if (g1_policy()->should_initiate_conc_mark()) {
  2512       concurrent_mark()->checkpointRootsInitialPre();
  2514     save_marks();
  2516     // We must do this before any possible evacuation that should propagate
  2517     // marks, including evacuation of popular objects in a popular pause.
  2518     if (mark_in_progress()) {
  2519       double start_time_sec = os::elapsedTime();
  2521       _cm->drainAllSATBBuffers();
  2522       double finish_mark_ms = (os::elapsedTime() - start_time_sec) * 1000.0;
  2523       g1_policy()->record_satb_drain_time(finish_mark_ms);
  2526     // Record the number of elements currently on the mark stack, so we
  2527     // only iterate over these.  (Since evacuation may add to the mark
  2528     // stack, doing more exposes race conditions.)  If no mark is in
  2529     // progress, this will be zero.
  2530     _cm->set_oops_do_bound();
  2532     assert(regions_accounted_for(), "Region leakage.");
  2534     bool abandoned = false;
  2536     if (mark_in_progress())
  2537       concurrent_mark()->newCSet();
  2539     // Now choose the CS.
  2540     if (popular_region == NULL) {
  2541       g1_policy()->choose_collection_set();
  2542     } else {
  2543       // We may be evacuating a single region (for popularity).
  2544       g1_policy()->record_popular_pause_preamble_start();
  2545       popularity_pause_preamble(popular_region);
  2546       g1_policy()->record_popular_pause_preamble_end();
  2547       abandoned = (g1_policy()->collection_set() == NULL);
  2548       // Now we allow more regions to be added (we have to collect
  2549       // all popular regions).
  2550       if (!abandoned) {
  2551         g1_policy()->choose_collection_set(popular_region);
  2554     // We may abandon a pause if we find no region that will fit in the MMU
  2555     // pause.
  2556     abandoned = (g1_policy()->collection_set() == NULL);
  2558     // Nothing to do if we were unable to choose a collection set.
  2559     if (!abandoned) {
  2560 #if G1_REM_SET_LOGGING
  2561       gclog_or_tty->print_cr("\nAfter pause, heap:");
  2562       print();
  2563 #endif
  2565       setup_surviving_young_words();
  2567       // Set up the gc allocation regions.
  2568       get_gc_alloc_regions();
  2570       // Actually do the work...
  2571       evacuate_collection_set();
  2572       free_collection_set(g1_policy()->collection_set());
  2573       g1_policy()->clear_collection_set();
  2575       FREE_C_HEAP_ARRAY(bool, _in_cset_fast_test_base);
  2576       // this is more for peace of mind; we're nulling them here and
  2577       // we're expecting them to be null at the beginning of the next GC
  2578       _in_cset_fast_test = NULL;
  2579       _in_cset_fast_test_base = NULL;
  2581       if (popular_region != NULL) {
  2582         // We have to wait until now, because we don't want the region to
  2583         // be rescheduled for pop-evac during RS update.
  2584         popular_region->set_popular_pending(false);
  2587       release_gc_alloc_regions();
  2589       cleanup_surviving_young_words();
  2591       if (g1_policy()->in_young_gc_mode()) {
  2592         _young_list->reset_sampled_info();
  2593         assert(check_young_list_empty(true),
  2594                "young list should be empty");
  2596 #if SCAN_ONLY_VERBOSE
  2597         _young_list->print();
  2598 #endif // SCAN_ONLY_VERBOSE
  2600         g1_policy()->record_survivor_regions(_young_list->survivor_length(),
  2601                                              _young_list->first_survivor_region(),
  2602                                              _young_list->last_survivor_region());
  2603         _young_list->reset_auxilary_lists();
  2605     } else {
  2606       COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
  2609     if (evacuation_failed()) {
  2610       _summary_bytes_used = recalculate_used();
  2611     } else {
  2612       // The "used" of the the collection set have already been subtracted
  2613       // when they were freed.  Add in the bytes evacuated.
  2614       _summary_bytes_used += g1_policy()->bytes_in_to_space();
  2617     if (g1_policy()->in_young_gc_mode() &&
  2618         g1_policy()->should_initiate_conc_mark()) {
  2619       concurrent_mark()->checkpointRootsInitialPost();
  2620       set_marking_started();
  2621       doConcurrentMark();
  2624 #if SCAN_ONLY_VERBOSE
  2625     _young_list->print();
  2626 #endif // SCAN_ONLY_VERBOSE
  2628     double end_time_sec = os::elapsedTime();
  2629     if (!evacuation_failed()) {
  2630       g1_policy()->record_pause_time((end_time_sec - start_time_sec)*1000.0);
  2632     GCOverheadReporter::recordSTWEnd(end_time_sec);
  2633     g1_policy()->record_collection_pause_end(popular_region != NULL,
  2634                                              abandoned);
  2636     assert(regions_accounted_for(), "Region leakage.");
  2638     if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
  2639       HandleMark hm;  // Discard invalid handles created during verification
  2640       gclog_or_tty->print(" VerifyAfterGC:");
  2641       Universe::verify(false);
  2644     if (was_enabled) ref_processor()->enable_discovery();
  2647       size_t expand_bytes = g1_policy()->expansion_amount();
  2648       if (expand_bytes > 0) {
  2649         size_t bytes_before = capacity();
  2650         expand(expand_bytes);
  2654     if (mark_in_progress()) {
  2655       concurrent_mark()->update_g1_committed();
  2658 #ifdef TRACESPINNING
  2659     ParallelTaskTerminator::print_termination_counts();
  2660 #endif
  2662     gc_epilogue(false);
  2665   assert(verify_region_lists(), "Bad region lists.");
  2667   if (reset_should_initiate_conc_mark)
  2668     g1_policy()->set_should_initiate_conc_mark();
  2670   if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) {
  2671     gclog_or_tty->print_cr("Stopping after GC #%d", ExitAfterGCNum);
  2672     print_tracing_info();
  2673     vm_exit(-1);
  2677 void G1CollectedHeap::set_gc_alloc_region(int purpose, HeapRegion* r) {
  2678   assert(purpose >= 0 && purpose < GCAllocPurposeCount, "invalid purpose");
  2679   HeapWord* original_top = NULL;
  2680   if (r != NULL)
  2681     original_top = r->top();
  2683   // We will want to record the used space in r as being there before gc.
  2684   // One we install it as a GC alloc region it's eligible for allocation.
  2685   // So record it now and use it later.
  2686   size_t r_used = 0;
  2687   if (r != NULL) {
  2688     r_used = r->used();
  2690     if (ParallelGCThreads > 0) {
  2691       // need to take the lock to guard against two threads calling
  2692       // get_gc_alloc_region concurrently (very unlikely but...)
  2693       MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  2694       r->save_marks();
  2697   HeapRegion* old_alloc_region = _gc_alloc_regions[purpose];
  2698   _gc_alloc_regions[purpose] = r;
  2699   if (old_alloc_region != NULL) {
  2700     // Replace aliases too.
  2701     for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
  2702       if (_gc_alloc_regions[ap] == old_alloc_region) {
  2703         _gc_alloc_regions[ap] = r;
  2707   if (r != NULL) {
  2708     push_gc_alloc_region(r);
  2709     if (mark_in_progress() && original_top != r->next_top_at_mark_start()) {
  2710       // We are using a region as a GC alloc region after it has been used
  2711       // as a mutator allocation region during the current marking cycle.
  2712       // The mutator-allocated objects are currently implicitly marked, but
  2713       // when we move hr->next_top_at_mark_start() forward at the the end
  2714       // of the GC pause, they won't be.  We therefore mark all objects in
  2715       // the "gap".  We do this object-by-object, since marking densely
  2716       // does not currently work right with marking bitmap iteration.  This
  2717       // means we rely on TLAB filling at the start of pauses, and no
  2718       // "resuscitation" of filled TLAB's.  If we want to do this, we need
  2719       // to fix the marking bitmap iteration.
  2720       HeapWord* curhw = r->next_top_at_mark_start();
  2721       HeapWord* t = original_top;
  2723       while (curhw < t) {
  2724         oop cur = (oop)curhw;
  2725         // We'll assume parallel for generality.  This is rare code.
  2726         concurrent_mark()->markAndGrayObjectIfNecessary(cur); // can't we just mark them?
  2727         curhw = curhw + cur->size();
  2729       assert(curhw == t, "Should have parsed correctly.");
  2731     if (G1PolicyVerbose > 1) {
  2732       gclog_or_tty->print("New alloc region ["PTR_FORMAT", "PTR_FORMAT", " PTR_FORMAT") "
  2733                           "for survivors:", r->bottom(), original_top, r->end());
  2734       r->print();
  2736     g1_policy()->record_before_bytes(r_used);
  2740 void G1CollectedHeap::push_gc_alloc_region(HeapRegion* hr) {
  2741   assert(Thread::current()->is_VM_thread() ||
  2742          par_alloc_during_gc_lock()->owned_by_self(), "Precondition");
  2743   assert(!hr->is_gc_alloc_region() && !hr->in_collection_set(),
  2744          "Precondition.");
  2745   hr->set_is_gc_alloc_region(true);
  2746   hr->set_next_gc_alloc_region(_gc_alloc_region_list);
  2747   _gc_alloc_region_list = hr;
  2750 #ifdef G1_DEBUG
  2751 class FindGCAllocRegion: public HeapRegionClosure {
  2752 public:
  2753   bool doHeapRegion(HeapRegion* r) {
  2754     if (r->is_gc_alloc_region()) {
  2755       gclog_or_tty->print_cr("Region %d ["PTR_FORMAT"...] is still a gc_alloc_region.",
  2756                              r->hrs_index(), r->bottom());
  2758     return false;
  2760 };
  2761 #endif // G1_DEBUG
  2763 void G1CollectedHeap::forget_alloc_region_list() {
  2764   assert(Thread::current()->is_VM_thread(), "Precondition");
  2765   while (_gc_alloc_region_list != NULL) {
  2766     HeapRegion* r = _gc_alloc_region_list;
  2767     assert(r->is_gc_alloc_region(), "Invariant.");
  2768     _gc_alloc_region_list = r->next_gc_alloc_region();
  2769     r->set_next_gc_alloc_region(NULL);
  2770     r->set_is_gc_alloc_region(false);
  2771     if (r->is_survivor()) {
  2772       if (r->is_empty()) {
  2773         r->set_not_young();
  2774       } else {
  2775         _young_list->add_survivor_region(r);
  2778     if (r->is_empty()) {
  2779       ++_free_regions;
  2782 #ifdef G1_DEBUG
  2783   FindGCAllocRegion fa;
  2784   heap_region_iterate(&fa);
  2785 #endif // G1_DEBUG
  2789 bool G1CollectedHeap::check_gc_alloc_regions() {
  2790   // TODO: allocation regions check
  2791   return true;
  2794 void G1CollectedHeap::get_gc_alloc_regions() {
  2795   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
  2796     // Create new GC alloc regions.
  2797     HeapRegion* alloc_region = _gc_alloc_regions[ap];
  2798     // Clear this alloc region, so that in case it turns out to be
  2799     // unacceptable, we end up with no allocation region, rather than a bad
  2800     // one.
  2801     _gc_alloc_regions[ap] = NULL;
  2802     if (alloc_region == NULL || alloc_region->in_collection_set()) {
  2803       // Can't re-use old one.  Allocate a new one.
  2804       alloc_region = newAllocRegionWithExpansion(ap, 0);
  2806     if (alloc_region != NULL) {
  2807       set_gc_alloc_region(ap, alloc_region);
  2810   // Set alternative regions for allocation purposes that have reached
  2811   // thier limit.
  2812   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
  2813     GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(ap);
  2814     if (_gc_alloc_regions[ap] == NULL && alt_purpose != ap) {
  2815       _gc_alloc_regions[ap] = _gc_alloc_regions[alt_purpose];
  2818   assert(check_gc_alloc_regions(), "alloc regions messed up");
  2821 void G1CollectedHeap::release_gc_alloc_regions() {
  2822   // We keep a separate list of all regions that have been alloc regions in
  2823   // the current collection pause.  Forget that now.
  2824   forget_alloc_region_list();
  2826   // The current alloc regions contain objs that have survived
  2827   // collection. Make them no longer GC alloc regions.
  2828   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
  2829     HeapRegion* r = _gc_alloc_regions[ap];
  2830     if (r != NULL && r->is_empty()) {
  2832         MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  2833         r->set_zero_fill_complete();
  2834         put_free_region_on_list_locked(r);
  2837     // set_gc_alloc_region will also NULLify all aliases to the region
  2838     set_gc_alloc_region(ap, NULL);
  2839     _gc_alloc_region_counts[ap] = 0;
  2843 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
  2844   _drain_in_progress = false;
  2845   set_evac_failure_closure(cl);
  2846   _evac_failure_scan_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
  2849 void G1CollectedHeap::finalize_for_evac_failure() {
  2850   assert(_evac_failure_scan_stack != NULL &&
  2851          _evac_failure_scan_stack->length() == 0,
  2852          "Postcondition");
  2853   assert(!_drain_in_progress, "Postcondition");
  2854   // Don't have to delete, since the scan stack is a resource object.
  2855   _evac_failure_scan_stack = NULL;
  2860 // *** Sequential G1 Evacuation
  2862 HeapWord* G1CollectedHeap::allocate_during_gc(GCAllocPurpose purpose, size_t word_size) {
  2863   HeapRegion* alloc_region = _gc_alloc_regions[purpose];
  2864   // let the caller handle alloc failure
  2865   if (alloc_region == NULL) return NULL;
  2866   assert(isHumongous(word_size) || !alloc_region->isHumongous(),
  2867          "Either the object is humongous or the region isn't");
  2868   HeapWord* block = alloc_region->allocate(word_size);
  2869   if (block == NULL) {
  2870     block = allocate_during_gc_slow(purpose, alloc_region, false, word_size);
  2872   return block;
  2875 class G1IsAliveClosure: public BoolObjectClosure {
  2876   G1CollectedHeap* _g1;
  2877 public:
  2878   G1IsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
  2879   void do_object(oop p) { assert(false, "Do not call."); }
  2880   bool do_object_b(oop p) {
  2881     // It is reachable if it is outside the collection set, or is inside
  2882     // and forwarded.
  2884 #ifdef G1_DEBUG
  2885     gclog_or_tty->print_cr("is alive "PTR_FORMAT" in CS %d forwarded %d overall %d",
  2886                            (void*) p, _g1->obj_in_cs(p), p->is_forwarded(),
  2887                            !_g1->obj_in_cs(p) || p->is_forwarded());
  2888 #endif // G1_DEBUG
  2890     return !_g1->obj_in_cs(p) || p->is_forwarded();
  2892 };
  2894 class G1KeepAliveClosure: public OopClosure {
  2895   G1CollectedHeap* _g1;
  2896 public:
  2897   G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
  2898   void do_oop(narrowOop* p) {
  2899     guarantee(false, "NYI");
  2901   void do_oop(oop* p) {
  2902     oop obj = *p;
  2903 #ifdef G1_DEBUG
  2904     if (PrintGC && Verbose) {
  2905       gclog_or_tty->print_cr("keep alive *"PTR_FORMAT" = "PTR_FORMAT" "PTR_FORMAT,
  2906                              p, (void*) obj, (void*) *p);
  2908 #endif // G1_DEBUG
  2910     if (_g1->obj_in_cs(obj)) {
  2911       assert( obj->is_forwarded(), "invariant" );
  2912       *p = obj->forwardee();
  2914 #ifdef G1_DEBUG
  2915       gclog_or_tty->print_cr("     in CSet: moved "PTR_FORMAT" -> "PTR_FORMAT,
  2916                              (void*) obj, (void*) *p);
  2917 #endif // G1_DEBUG
  2920 };
  2922 class RecreateRSetEntriesClosure: public OopClosure {
  2923 private:
  2924   G1CollectedHeap* _g1;
  2925   G1RemSet* _g1_rem_set;
  2926   HeapRegion* _from;
  2927 public:
  2928   RecreateRSetEntriesClosure(G1CollectedHeap* g1, HeapRegion* from) :
  2929     _g1(g1), _g1_rem_set(g1->g1_rem_set()), _from(from)
  2930   {}
  2932   void do_oop(narrowOop* p) {
  2933     guarantee(false, "NYI");
  2935   void do_oop(oop* p) {
  2936     assert(_from->is_in_reserved(p), "paranoia");
  2937     if (*p != NULL) {
  2938       _g1_rem_set->write_ref(_from, p);
  2941 };
  2943 class RemoveSelfPointerClosure: public ObjectClosure {
  2944 private:
  2945   G1CollectedHeap* _g1;
  2946   ConcurrentMark* _cm;
  2947   HeapRegion* _hr;
  2948   size_t _prev_marked_bytes;
  2949   size_t _next_marked_bytes;
  2950 public:
  2951   RemoveSelfPointerClosure(G1CollectedHeap* g1, HeapRegion* hr) :
  2952     _g1(g1), _cm(_g1->concurrent_mark()), _hr(hr),
  2953     _prev_marked_bytes(0), _next_marked_bytes(0)
  2954   {}
  2956   size_t prev_marked_bytes() { return _prev_marked_bytes; }
  2957   size_t next_marked_bytes() { return _next_marked_bytes; }
  2959   // The original idea here was to coalesce evacuated and dead objects.
  2960   // However that caused complications with the block offset table (BOT).
  2961   // In particular if there were two TLABs, one of them partially refined.
  2962   // |----- TLAB_1--------|----TLAB_2-~~~(partially refined part)~~~|
  2963   // The BOT entries of the unrefined part of TLAB_2 point to the start
  2964   // of TLAB_2. If the last object of the TLAB_1 and the first object
  2965   // of TLAB_2 are coalesced, then the cards of the unrefined part
  2966   // would point into middle of the filler object.
  2967   //
  2968   // The current approach is to not coalesce and leave the BOT contents intact.
  2969   void do_object(oop obj) {
  2970     if (obj->is_forwarded() && obj->forwardee() == obj) {
  2971       // The object failed to move.
  2972       assert(!_g1->is_obj_dead(obj), "We should not be preserving dead objs.");
  2973       _cm->markPrev(obj);
  2974       assert(_cm->isPrevMarked(obj), "Should be marked!");
  2975       _prev_marked_bytes += (obj->size() * HeapWordSize);
  2976       if (_g1->mark_in_progress() && !_g1->is_obj_ill(obj)) {
  2977         _cm->markAndGrayObjectIfNecessary(obj);
  2979       obj->set_mark(markOopDesc::prototype());
  2980       // While we were processing RSet buffers during the
  2981       // collection, we actually didn't scan any cards on the
  2982       // collection set, since we didn't want to update remebered
  2983       // sets with entries that point into the collection set, given
  2984       // that live objects fromthe collection set are about to move
  2985       // and such entries will be stale very soon. This change also
  2986       // dealt with a reliability issue which involved scanning a
  2987       // card in the collection set and coming across an array that
  2988       // was being chunked and looking malformed. The problem is
  2989       // that, if evacuation fails, we might have remembered set
  2990       // entries missing given that we skipped cards on the
  2991       // collection set. So, we'll recreate such entries now.
  2992       RecreateRSetEntriesClosure cl(_g1, _hr);
  2993       obj->oop_iterate(&cl);
  2994       assert(_cm->isPrevMarked(obj), "Should be marked!");
  2995     } else {
  2996       // The object has been either evacuated or is dead. Fill it with a
  2997       // dummy object.
  2998       MemRegion mr((HeapWord*)obj, obj->size());
  2999       CollectedHeap::fill_with_object(mr);
  3000       _cm->clearRangeBothMaps(mr);
  3003 };
  3005 void G1CollectedHeap::remove_self_forwarding_pointers() {
  3006   HeapRegion* cur = g1_policy()->collection_set();
  3008   while (cur != NULL) {
  3009     assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
  3011     if (cur->evacuation_failed()) {
  3012       RemoveSelfPointerClosure rspc(_g1h, cur);
  3013       assert(cur->in_collection_set(), "bad CS");
  3014       cur->object_iterate(&rspc);
  3016       // A number of manipulations to make the TAMS be the current top,
  3017       // and the marked bytes be the ones observed in the iteration.
  3018       if (_g1h->concurrent_mark()->at_least_one_mark_complete()) {
  3019         // The comments below are the postconditions achieved by the
  3020         // calls.  Note especially the last such condition, which says that
  3021         // the count of marked bytes has been properly restored.
  3022         cur->note_start_of_marking(false);
  3023         // _next_top_at_mark_start == top, _next_marked_bytes == 0
  3024         cur->add_to_marked_bytes(rspc.prev_marked_bytes());
  3025         // _next_marked_bytes == prev_marked_bytes.
  3026         cur->note_end_of_marking();
  3027         // _prev_top_at_mark_start == top(),
  3028         // _prev_marked_bytes == prev_marked_bytes
  3030       // If there is no mark in progress, we modified the _next variables
  3031       // above needlessly, but harmlessly.
  3032       if (_g1h->mark_in_progress()) {
  3033         cur->note_start_of_marking(false);
  3034         // _next_top_at_mark_start == top, _next_marked_bytes == 0
  3035         // _next_marked_bytes == next_marked_bytes.
  3038       // Now make sure the region has the right index in the sorted array.
  3039       g1_policy()->note_change_in_marked_bytes(cur);
  3041     cur = cur->next_in_collection_set();
  3043   assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
  3045   // Now restore saved marks, if any.
  3046   if (_objs_with_preserved_marks != NULL) {
  3047     assert(_preserved_marks_of_objs != NULL, "Both or none.");
  3048     assert(_objs_with_preserved_marks->length() ==
  3049            _preserved_marks_of_objs->length(), "Both or none.");
  3050     guarantee(_objs_with_preserved_marks->length() ==
  3051               _preserved_marks_of_objs->length(), "Both or none.");
  3052     for (int i = 0; i < _objs_with_preserved_marks->length(); i++) {
  3053       oop obj   = _objs_with_preserved_marks->at(i);
  3054       markOop m = _preserved_marks_of_objs->at(i);
  3055       obj->set_mark(m);
  3057     // Delete the preserved marks growable arrays (allocated on the C heap).
  3058     delete _objs_with_preserved_marks;
  3059     delete _preserved_marks_of_objs;
  3060     _objs_with_preserved_marks = NULL;
  3061     _preserved_marks_of_objs = NULL;
  3065 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
  3066   _evac_failure_scan_stack->push(obj);
  3069 void G1CollectedHeap::drain_evac_failure_scan_stack() {
  3070   assert(_evac_failure_scan_stack != NULL, "precondition");
  3072   while (_evac_failure_scan_stack->length() > 0) {
  3073      oop obj = _evac_failure_scan_stack->pop();
  3074      _evac_failure_closure->set_region(heap_region_containing(obj));
  3075      obj->oop_iterate_backwards(_evac_failure_closure);
  3079 void G1CollectedHeap::handle_evacuation_failure(oop old) {
  3080   markOop m = old->mark();
  3081   // forward to self
  3082   assert(!old->is_forwarded(), "precondition");
  3084   old->forward_to(old);
  3085   handle_evacuation_failure_common(old, m);
  3088 oop
  3089 G1CollectedHeap::handle_evacuation_failure_par(OopsInHeapRegionClosure* cl,
  3090                                                oop old) {
  3091   markOop m = old->mark();
  3092   oop forward_ptr = old->forward_to_atomic(old);
  3093   if (forward_ptr == NULL) {
  3094     // Forward-to-self succeeded.
  3095     if (_evac_failure_closure != cl) {
  3096       MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
  3097       assert(!_drain_in_progress,
  3098              "Should only be true while someone holds the lock.");
  3099       // Set the global evac-failure closure to the current thread's.
  3100       assert(_evac_failure_closure == NULL, "Or locking has failed.");
  3101       set_evac_failure_closure(cl);
  3102       // Now do the common part.
  3103       handle_evacuation_failure_common(old, m);
  3104       // Reset to NULL.
  3105       set_evac_failure_closure(NULL);
  3106     } else {
  3107       // The lock is already held, and this is recursive.
  3108       assert(_drain_in_progress, "This should only be the recursive case.");
  3109       handle_evacuation_failure_common(old, m);
  3111     return old;
  3112   } else {
  3113     // Someone else had a place to copy it.
  3114     return forward_ptr;
  3118 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
  3119   set_evacuation_failed(true);
  3121   preserve_mark_if_necessary(old, m);
  3123   HeapRegion* r = heap_region_containing(old);
  3124   if (!r->evacuation_failed()) {
  3125     r->set_evacuation_failed(true);
  3126     if (G1TraceRegions) {
  3127       gclog_or_tty->print("evacuation failed in heap region "PTR_FORMAT" "
  3128                           "["PTR_FORMAT","PTR_FORMAT")\n",
  3129                           r, r->bottom(), r->end());
  3133   push_on_evac_failure_scan_stack(old);
  3135   if (!_drain_in_progress) {
  3136     // prevent recursion in copy_to_survivor_space()
  3137     _drain_in_progress = true;
  3138     drain_evac_failure_scan_stack();
  3139     _drain_in_progress = false;
  3143 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
  3144   if (m != markOopDesc::prototype()) {
  3145     if (_objs_with_preserved_marks == NULL) {
  3146       assert(_preserved_marks_of_objs == NULL, "Both or none.");
  3147       _objs_with_preserved_marks =
  3148         new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
  3149       _preserved_marks_of_objs =
  3150         new (ResourceObj::C_HEAP) GrowableArray<markOop>(40, true);
  3152     _objs_with_preserved_marks->push(obj);
  3153     _preserved_marks_of_objs->push(m);
  3157 // *** Parallel G1 Evacuation
  3159 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
  3160                                                   size_t word_size) {
  3161   HeapRegion* alloc_region = _gc_alloc_regions[purpose];
  3162   // let the caller handle alloc failure
  3163   if (alloc_region == NULL) return NULL;
  3165   HeapWord* block = alloc_region->par_allocate(word_size);
  3166   if (block == NULL) {
  3167     MutexLockerEx x(par_alloc_during_gc_lock(),
  3168                     Mutex::_no_safepoint_check_flag);
  3169     block = allocate_during_gc_slow(purpose, alloc_region, true, word_size);
  3171   return block;
  3174 void G1CollectedHeap::retire_alloc_region(HeapRegion* alloc_region,
  3175                                             bool par) {
  3176   // Another thread might have obtained alloc_region for the given
  3177   // purpose, and might be attempting to allocate in it, and might
  3178   // succeed.  Therefore, we can't do the "finalization" stuff on the
  3179   // region below until we're sure the last allocation has happened.
  3180   // We ensure this by allocating the remaining space with a garbage
  3181   // object.
  3182   if (par) par_allocate_remaining_space(alloc_region);
  3183   // Now we can do the post-GC stuff on the region.
  3184   alloc_region->note_end_of_copying();
  3185   g1_policy()->record_after_bytes(alloc_region->used());
  3188 HeapWord*
  3189 G1CollectedHeap::allocate_during_gc_slow(GCAllocPurpose purpose,
  3190                                          HeapRegion*    alloc_region,
  3191                                          bool           par,
  3192                                          size_t         word_size) {
  3193   HeapWord* block = NULL;
  3194   // In the parallel case, a previous thread to obtain the lock may have
  3195   // already assigned a new gc_alloc_region.
  3196   if (alloc_region != _gc_alloc_regions[purpose]) {
  3197     assert(par, "But should only happen in parallel case.");
  3198     alloc_region = _gc_alloc_regions[purpose];
  3199     if (alloc_region == NULL) return NULL;
  3200     block = alloc_region->par_allocate(word_size);
  3201     if (block != NULL) return block;
  3202     // Otherwise, continue; this new region is empty, too.
  3204   assert(alloc_region != NULL, "We better have an allocation region");
  3205   retire_alloc_region(alloc_region, par);
  3207   if (_gc_alloc_region_counts[purpose] >= g1_policy()->max_regions(purpose)) {
  3208     // Cannot allocate more regions for the given purpose.
  3209     GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(purpose);
  3210     // Is there an alternative?
  3211     if (purpose != alt_purpose) {
  3212       HeapRegion* alt_region = _gc_alloc_regions[alt_purpose];
  3213       // Has not the alternative region been aliased?
  3214       if (alloc_region != alt_region && alt_region != NULL) {
  3215         // Try to allocate in the alternative region.
  3216         if (par) {
  3217           block = alt_region->par_allocate(word_size);
  3218         } else {
  3219           block = alt_region->allocate(word_size);
  3221         // Make an alias.
  3222         _gc_alloc_regions[purpose] = _gc_alloc_regions[alt_purpose];
  3223         if (block != NULL) {
  3224           return block;
  3226         retire_alloc_region(alt_region, par);
  3228       // Both the allocation region and the alternative one are full
  3229       // and aliased, replace them with a new allocation region.
  3230       purpose = alt_purpose;
  3231     } else {
  3232       set_gc_alloc_region(purpose, NULL);
  3233       return NULL;
  3237   // Now allocate a new region for allocation.
  3238   alloc_region = newAllocRegionWithExpansion(purpose, word_size, false /*zero_filled*/);
  3240   // let the caller handle alloc failure
  3241   if (alloc_region != NULL) {
  3243     assert(check_gc_alloc_regions(), "alloc regions messed up");
  3244     assert(alloc_region->saved_mark_at_top(),
  3245            "Mark should have been saved already.");
  3246     // We used to assert that the region was zero-filled here, but no
  3247     // longer.
  3249     // This must be done last: once it's installed, other regions may
  3250     // allocate in it (without holding the lock.)
  3251     set_gc_alloc_region(purpose, alloc_region);
  3253     if (par) {
  3254       block = alloc_region->par_allocate(word_size);
  3255     } else {
  3256       block = alloc_region->allocate(word_size);
  3258     // Caller handles alloc failure.
  3259   } else {
  3260     // This sets other apis using the same old alloc region to NULL, also.
  3261     set_gc_alloc_region(purpose, NULL);
  3263   return block;  // May be NULL.
  3266 void G1CollectedHeap::par_allocate_remaining_space(HeapRegion* r) {
  3267   HeapWord* block = NULL;
  3268   size_t free_words;
  3269   do {
  3270     free_words = r->free()/HeapWordSize;
  3271     // If there's too little space, no one can allocate, so we're done.
  3272     if (free_words < (size_t)oopDesc::header_size()) return;
  3273     // Otherwise, try to claim it.
  3274     block = r->par_allocate(free_words);
  3275   } while (block == NULL);
  3276   fill_with_object(block, free_words);
  3279 #define use_local_bitmaps         1
  3280 #define verify_local_bitmaps      0
  3282 #ifndef PRODUCT
  3284 class GCLabBitMap;
  3285 class GCLabBitMapClosure: public BitMapClosure {
  3286 private:
  3287   ConcurrentMark* _cm;
  3288   GCLabBitMap*    _bitmap;
  3290 public:
  3291   GCLabBitMapClosure(ConcurrentMark* cm,
  3292                      GCLabBitMap* bitmap) {
  3293     _cm     = cm;
  3294     _bitmap = bitmap;
  3297   virtual bool do_bit(size_t offset);
  3298 };
  3300 #endif // PRODUCT
  3302 #define oop_buffer_length 256
  3304 class GCLabBitMap: public BitMap {
  3305 private:
  3306   ConcurrentMark* _cm;
  3308   int       _shifter;
  3309   size_t    _bitmap_word_covers_words;
  3311   // beginning of the heap
  3312   HeapWord* _heap_start;
  3314   // this is the actual start of the GCLab
  3315   HeapWord* _real_start_word;
  3317   // this is the actual end of the GCLab
  3318   HeapWord* _real_end_word;
  3320   // this is the first word, possibly located before the actual start
  3321   // of the GCLab, that corresponds to the first bit of the bitmap
  3322   HeapWord* _start_word;
  3324   // size of a GCLab in words
  3325   size_t _gclab_word_size;
  3327   static int shifter() {
  3328     return MinObjAlignment - 1;
  3331   // how many heap words does a single bitmap word corresponds to?
  3332   static size_t bitmap_word_covers_words() {
  3333     return BitsPerWord << shifter();
  3336   static size_t gclab_word_size() {
  3337     return ParallelGCG1AllocBufferSize / HeapWordSize;
  3340   static size_t bitmap_size_in_bits() {
  3341     size_t bits_in_bitmap = gclab_word_size() >> shifter();
  3342     // We are going to ensure that the beginning of a word in this
  3343     // bitmap also corresponds to the beginning of a word in the
  3344     // global marking bitmap. To handle the case where a GCLab
  3345     // starts from the middle of the bitmap, we need to add enough
  3346     // space (i.e. up to a bitmap word) to ensure that we have
  3347     // enough bits in the bitmap.
  3348     return bits_in_bitmap + BitsPerWord - 1;
  3350 public:
  3351   GCLabBitMap(HeapWord* heap_start)
  3352     : BitMap(bitmap_size_in_bits()),
  3353       _cm(G1CollectedHeap::heap()->concurrent_mark()),
  3354       _shifter(shifter()),
  3355       _bitmap_word_covers_words(bitmap_word_covers_words()),
  3356       _heap_start(heap_start),
  3357       _gclab_word_size(gclab_word_size()),
  3358       _real_start_word(NULL),
  3359       _real_end_word(NULL),
  3360       _start_word(NULL)
  3362     guarantee( size_in_words() >= bitmap_size_in_words(),
  3363                "just making sure");
  3366   inline unsigned heapWordToOffset(HeapWord* addr) {
  3367     unsigned offset = (unsigned) pointer_delta(addr, _start_word) >> _shifter;
  3368     assert(offset < size(), "offset should be within bounds");
  3369     return offset;
  3372   inline HeapWord* offsetToHeapWord(size_t offset) {
  3373     HeapWord* addr =  _start_word + (offset << _shifter);
  3374     assert(_real_start_word <= addr && addr < _real_end_word, "invariant");
  3375     return addr;
  3378   bool fields_well_formed() {
  3379     bool ret1 = (_real_start_word == NULL) &&
  3380                 (_real_end_word == NULL) &&
  3381                 (_start_word == NULL);
  3382     if (ret1)
  3383       return true;
  3385     bool ret2 = _real_start_word >= _start_word &&
  3386       _start_word < _real_end_word &&
  3387       (_real_start_word + _gclab_word_size) == _real_end_word &&
  3388       (_start_word + _gclab_word_size + _bitmap_word_covers_words)
  3389                                                               > _real_end_word;
  3390     return ret2;
  3393   inline bool mark(HeapWord* addr) {
  3394     guarantee(use_local_bitmaps, "invariant");
  3395     assert(fields_well_formed(), "invariant");
  3397     if (addr >= _real_start_word && addr < _real_end_word) {
  3398       assert(!isMarked(addr), "should not have already been marked");
  3400       // first mark it on the bitmap
  3401       at_put(heapWordToOffset(addr), true);
  3403       return true;
  3404     } else {
  3405       return false;
  3409   inline bool isMarked(HeapWord* addr) {
  3410     guarantee(use_local_bitmaps, "invariant");
  3411     assert(fields_well_formed(), "invariant");
  3413     return at(heapWordToOffset(addr));
  3416   void set_buffer(HeapWord* start) {
  3417     guarantee(use_local_bitmaps, "invariant");
  3418     clear();
  3420     assert(start != NULL, "invariant");
  3421     _real_start_word = start;
  3422     _real_end_word   = start + _gclab_word_size;
  3424     size_t diff =
  3425       pointer_delta(start, _heap_start) % _bitmap_word_covers_words;
  3426     _start_word = start - diff;
  3428     assert(fields_well_formed(), "invariant");
  3431 #ifndef PRODUCT
  3432   void verify() {
  3433     // verify that the marks have been propagated
  3434     GCLabBitMapClosure cl(_cm, this);
  3435     iterate(&cl);
  3437 #endif // PRODUCT
  3439   void retire() {
  3440     guarantee(use_local_bitmaps, "invariant");
  3441     assert(fields_well_formed(), "invariant");
  3443     if (_start_word != NULL) {
  3444       CMBitMap*       mark_bitmap = _cm->nextMarkBitMap();
  3446       // this means that the bitmap was set up for the GCLab
  3447       assert(_real_start_word != NULL && _real_end_word != NULL, "invariant");
  3449       mark_bitmap->mostly_disjoint_range_union(this,
  3450                                 0, // always start from the start of the bitmap
  3451                                 _start_word,
  3452                                 size_in_words());
  3453       _cm->grayRegionIfNecessary(MemRegion(_real_start_word, _real_end_word));
  3455 #ifndef PRODUCT
  3456       if (use_local_bitmaps && verify_local_bitmaps)
  3457         verify();
  3458 #endif // PRODUCT
  3459     } else {
  3460       assert(_real_start_word == NULL && _real_end_word == NULL, "invariant");
  3464   static size_t bitmap_size_in_words() {
  3465     return (bitmap_size_in_bits() + BitsPerWord - 1) / BitsPerWord;
  3467 };
  3469 #ifndef PRODUCT
  3471 bool GCLabBitMapClosure::do_bit(size_t offset) {
  3472   HeapWord* addr = _bitmap->offsetToHeapWord(offset);
  3473   guarantee(_cm->isMarked(oop(addr)), "it should be!");
  3474   return true;
  3477 #endif // PRODUCT
  3479 class G1ParGCAllocBuffer: public ParGCAllocBuffer {
  3480 private:
  3481   bool        _retired;
  3482   bool        _during_marking;
  3483   GCLabBitMap _bitmap;
  3485 public:
  3486   G1ParGCAllocBuffer() :
  3487     ParGCAllocBuffer(ParallelGCG1AllocBufferSize / HeapWordSize),
  3488     _during_marking(G1CollectedHeap::heap()->mark_in_progress()),
  3489     _bitmap(G1CollectedHeap::heap()->reserved_region().start()),
  3490     _retired(false)
  3491   { }
  3493   inline bool mark(HeapWord* addr) {
  3494     guarantee(use_local_bitmaps, "invariant");
  3495     assert(_during_marking, "invariant");
  3496     return _bitmap.mark(addr);
  3499   inline void set_buf(HeapWord* buf) {
  3500     if (use_local_bitmaps && _during_marking)
  3501       _bitmap.set_buffer(buf);
  3502     ParGCAllocBuffer::set_buf(buf);
  3503     _retired = false;
  3506   inline void retire(bool end_of_gc, bool retain) {
  3507     if (_retired)
  3508       return;
  3509     if (use_local_bitmaps && _during_marking) {
  3510       _bitmap.retire();
  3512     ParGCAllocBuffer::retire(end_of_gc, retain);
  3513     _retired = true;
  3515 };
  3518 class G1ParScanThreadState : public StackObj {
  3519 protected:
  3520   G1CollectedHeap* _g1h;
  3521   RefToScanQueue*  _refs;
  3523   typedef GrowableArray<oop*> OverflowQueue;
  3524   OverflowQueue* _overflowed_refs;
  3526   G1ParGCAllocBuffer _alloc_buffers[GCAllocPurposeCount];
  3527   ageTable           _age_table;
  3529   size_t           _alloc_buffer_waste;
  3530   size_t           _undo_waste;
  3532   OopsInHeapRegionClosure*      _evac_failure_cl;
  3533   G1ParScanHeapEvacClosure*     _evac_cl;
  3534   G1ParScanPartialArrayClosure* _partial_scan_cl;
  3536   int _hash_seed;
  3537   int _queue_num;
  3539   int _term_attempts;
  3540 #if G1_DETAILED_STATS
  3541   int _pushes, _pops, _steals, _steal_attempts;
  3542   int _overflow_pushes;
  3543 #endif
  3545   double _start;
  3546   double _start_strong_roots;
  3547   double _strong_roots_time;
  3548   double _start_term;
  3549   double _term_time;
  3551   // Map from young-age-index (0 == not young, 1 is youngest) to
  3552   // surviving words. base is what we get back from the malloc call
  3553   size_t* _surviving_young_words_base;
  3554   // this points into the array, as we use the first few entries for padding
  3555   size_t* _surviving_young_words;
  3557 #define PADDING_ELEM_NUM (64 / sizeof(size_t))
  3559   void   add_to_alloc_buffer_waste(size_t waste) { _alloc_buffer_waste += waste; }
  3561   void   add_to_undo_waste(size_t waste)         { _undo_waste += waste; }
  3563 public:
  3564   G1ParScanThreadState(G1CollectedHeap* g1h, int queue_num)
  3565     : _g1h(g1h),
  3566       _refs(g1h->task_queue(queue_num)),
  3567       _hash_seed(17), _queue_num(queue_num),
  3568       _term_attempts(0),
  3569       _age_table(false),
  3570 #if G1_DETAILED_STATS
  3571       _pushes(0), _pops(0), _steals(0),
  3572       _steal_attempts(0),  _overflow_pushes(0),
  3573 #endif
  3574       _strong_roots_time(0), _term_time(0),
  3575       _alloc_buffer_waste(0), _undo_waste(0)
  3577     // we allocate G1YoungSurvRateNumRegions plus one entries, since
  3578     // we "sacrifice" entry 0 to keep track of surviving bytes for
  3579     // non-young regions (where the age is -1)
  3580     // We also add a few elements at the beginning and at the end in
  3581     // an attempt to eliminate cache contention
  3582     size_t real_length = 1 + _g1h->g1_policy()->young_cset_length();
  3583     size_t array_length = PADDING_ELEM_NUM +
  3584                           real_length +
  3585                           PADDING_ELEM_NUM;
  3586     _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length);
  3587     if (_surviving_young_words_base == NULL)
  3588       vm_exit_out_of_memory(array_length * sizeof(size_t),
  3589                             "Not enough space for young surv histo.");
  3590     _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
  3591     memset(_surviving_young_words, 0, real_length * sizeof(size_t));
  3593     _overflowed_refs = new OverflowQueue(10);
  3595     _start = os::elapsedTime();
  3598   ~G1ParScanThreadState() {
  3599     FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base);
  3602   RefToScanQueue*   refs()            { return _refs;             }
  3603   OverflowQueue*    overflowed_refs() { return _overflowed_refs;  }
  3604   ageTable*         age_table()       { return &_age_table;       }
  3606   G1ParGCAllocBuffer* alloc_buffer(GCAllocPurpose purpose) {
  3607     return &_alloc_buffers[purpose];
  3610   size_t alloc_buffer_waste()                    { return _alloc_buffer_waste; }
  3611   size_t undo_waste()                            { return _undo_waste; }
  3613   void push_on_queue(oop* ref) {
  3614     assert(ref != NULL, "invariant");
  3615     assert(has_partial_array_mask(ref) || _g1h->obj_in_cs(*ref), "invariant");
  3617     if (!refs()->push(ref)) {
  3618       overflowed_refs()->push(ref);
  3619       IF_G1_DETAILED_STATS(note_overflow_push());
  3620     } else {
  3621       IF_G1_DETAILED_STATS(note_push());
  3625   void pop_from_queue(oop*& ref) {
  3626     if (!refs()->pop_local(ref)) {
  3627       ref = NULL;
  3628     } else {
  3629       assert(ref != NULL, "invariant");
  3630       assert(has_partial_array_mask(ref) || _g1h->obj_in_cs(*ref),
  3631              "invariant");
  3633       IF_G1_DETAILED_STATS(note_pop());
  3637   void pop_from_overflow_queue(oop*& ref) {
  3638     ref = overflowed_refs()->pop();
  3641   int refs_to_scan()                             { return refs()->size();                 }
  3642   int overflowed_refs_to_scan()                  { return overflowed_refs()->length();    }
  3644   HeapWord* allocate_slow(GCAllocPurpose purpose, size_t word_sz) {
  3646     HeapWord* obj = NULL;
  3647     if (word_sz * 100 <
  3648         (size_t)(ParallelGCG1AllocBufferSize / HeapWordSize) *
  3649                                                   ParallelGCBufferWastePct) {
  3650       G1ParGCAllocBuffer* alloc_buf = alloc_buffer(purpose);
  3651       add_to_alloc_buffer_waste(alloc_buf->words_remaining());
  3652       alloc_buf->retire(false, false);
  3654       HeapWord* buf =
  3655         _g1h->par_allocate_during_gc(purpose, ParallelGCG1AllocBufferSize / HeapWordSize);
  3656       if (buf == NULL) return NULL; // Let caller handle allocation failure.
  3657       // Otherwise.
  3658       alloc_buf->set_buf(buf);
  3660       obj = alloc_buf->allocate(word_sz);
  3661       assert(obj != NULL, "buffer was definitely big enough...");
  3662     } else {
  3663       obj = _g1h->par_allocate_during_gc(purpose, word_sz);
  3665     return obj;
  3668   HeapWord* allocate(GCAllocPurpose purpose, size_t word_sz) {
  3669     HeapWord* obj = alloc_buffer(purpose)->allocate(word_sz);
  3670     if (obj != NULL) return obj;
  3671     return allocate_slow(purpose, word_sz);
  3674   void undo_allocation(GCAllocPurpose purpose, HeapWord* obj, size_t word_sz) {
  3675     if (alloc_buffer(purpose)->contains(obj)) {
  3676       guarantee(alloc_buffer(purpose)->contains(obj + word_sz - 1),
  3677                 "should contain whole object");
  3678       alloc_buffer(purpose)->undo_allocation(obj, word_sz);
  3679     } else {
  3680       CollectedHeap::fill_with_object(obj, word_sz);
  3681       add_to_undo_waste(word_sz);
  3685   void set_evac_failure_closure(OopsInHeapRegionClosure* evac_failure_cl) {
  3686     _evac_failure_cl = evac_failure_cl;
  3688   OopsInHeapRegionClosure* evac_failure_closure() {
  3689     return _evac_failure_cl;
  3692   void set_evac_closure(G1ParScanHeapEvacClosure* evac_cl) {
  3693     _evac_cl = evac_cl;
  3696   void set_partial_scan_closure(G1ParScanPartialArrayClosure* partial_scan_cl) {
  3697     _partial_scan_cl = partial_scan_cl;
  3700   int* hash_seed() { return &_hash_seed; }
  3701   int  queue_num() { return _queue_num; }
  3703   int term_attempts()   { return _term_attempts; }
  3704   void note_term_attempt()  { _term_attempts++; }
  3706 #if G1_DETAILED_STATS
  3707   int pushes()          { return _pushes; }
  3708   int pops()            { return _pops; }
  3709   int steals()          { return _steals; }
  3710   int steal_attempts()  { return _steal_attempts; }
  3711   int overflow_pushes() { return _overflow_pushes; }
  3713   void note_push()          { _pushes++; }
  3714   void note_pop()           { _pops++; }
  3715   void note_steal()         { _steals++; }
  3716   void note_steal_attempt() { _steal_attempts++; }
  3717   void note_overflow_push() { _overflow_pushes++; }
  3718 #endif
  3720   void start_strong_roots() {
  3721     _start_strong_roots = os::elapsedTime();
  3723   void end_strong_roots() {
  3724     _strong_roots_time += (os::elapsedTime() - _start_strong_roots);
  3726   double strong_roots_time() { return _strong_roots_time; }
  3728   void start_term_time() {
  3729     note_term_attempt();
  3730     _start_term = os::elapsedTime();
  3732   void end_term_time() {
  3733     _term_time += (os::elapsedTime() - _start_term);
  3735   double term_time() { return _term_time; }
  3737   double elapsed() {
  3738     return os::elapsedTime() - _start;
  3741   size_t* surviving_young_words() {
  3742     // We add on to hide entry 0 which accumulates surviving words for
  3743     // age -1 regions (i.e. non-young ones)
  3744     return _surviving_young_words;
  3747   void retire_alloc_buffers() {
  3748     for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
  3749       size_t waste = _alloc_buffers[ap].words_remaining();
  3750       add_to_alloc_buffer_waste(waste);
  3751       _alloc_buffers[ap].retire(true, false);
  3755 private:
  3756   void deal_with_reference(oop* ref_to_scan) {
  3757     if (has_partial_array_mask(ref_to_scan)) {
  3758       _partial_scan_cl->do_oop_nv(ref_to_scan);
  3759     } else {
  3760       // Note: we can use "raw" versions of "region_containing" because
  3761       // "obj_to_scan" is definitely in the heap, and is not in a
  3762       // humongous region.
  3763       HeapRegion* r = _g1h->heap_region_containing_raw(ref_to_scan);
  3764       _evac_cl->set_region(r);
  3765       _evac_cl->do_oop_nv(ref_to_scan);
  3769 public:
  3770   void trim_queue() {
  3771     // I've replicated the loop twice, first to drain the overflow
  3772     // queue, second to drain the task queue. This is better than
  3773     // having a single loop, which checks both conditions and, inside
  3774     // it, either pops the overflow queue or the task queue, as each
  3775     // loop is tighter. Also, the decision to drain the overflow queue
  3776     // first is not arbitrary, as the overflow queue is not visible
  3777     // to the other workers, whereas the task queue is. So, we want to
  3778     // drain the "invisible" entries first, while allowing the other
  3779     // workers to potentially steal the "visible" entries.
  3781     while (refs_to_scan() > 0 || overflowed_refs_to_scan() > 0) {
  3782       while (overflowed_refs_to_scan() > 0) {
  3783         oop *ref_to_scan = NULL;
  3784         pop_from_overflow_queue(ref_to_scan);
  3785         assert(ref_to_scan != NULL, "invariant");
  3786         // We shouldn't have pushed it on the queue if it was not
  3787         // pointing into the CSet.
  3788         assert(ref_to_scan != NULL, "sanity");
  3789         assert(has_partial_array_mask(ref_to_scan) ||
  3790                                       _g1h->obj_in_cs(*ref_to_scan), "sanity");
  3792         deal_with_reference(ref_to_scan);
  3795       while (refs_to_scan() > 0) {
  3796         oop *ref_to_scan = NULL;
  3797         pop_from_queue(ref_to_scan);
  3799         if (ref_to_scan != NULL) {
  3800           // We shouldn't have pushed it on the queue if it was not
  3801           // pointing into the CSet.
  3802           assert(has_partial_array_mask(ref_to_scan) ||
  3803                                       _g1h->obj_in_cs(*ref_to_scan), "sanity");
  3805           deal_with_reference(ref_to_scan);
  3810 };
  3813 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
  3814   _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()),
  3815   _par_scan_state(par_scan_state) { }
  3817 // This closure is applied to the fields of the objects that have just been copied.
  3818 // Should probably be made inline and moved in g1OopClosures.inline.hpp.
  3819 void G1ParScanClosure::do_oop_nv(oop* p) {
  3820   oop obj = *p;
  3822   if (obj != NULL) {
  3823     if (_g1->in_cset_fast_test(obj)) {
  3824       // We're not going to even bother checking whether the object is
  3825       // already forwarded or not, as this usually causes an immediate
  3826       // stall. We'll try to prefetch the object (for write, given that
  3827       // we might need to install the forwarding reference) and we'll
  3828       // get back to it when pop it from the queue
  3829       Prefetch::write(obj->mark_addr(), 0);
  3830       Prefetch::read(obj->mark_addr(), (HeapWordSize*2));
  3832       // slightly paranoid test; I'm trying to catch potential
  3833       // problems before we go into push_on_queue to know where the
  3834       // problem is coming from
  3835       assert(obj == *p, "the value of *p should not have changed");
  3836       _par_scan_state->push_on_queue(p);
  3837     } else {
  3838       _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
  3843 void G1ParCopyHelper::mark_forwardee(oop* p) {
  3844   // This is called _after_ do_oop_work has been called, hence after
  3845   // the object has been relocated to its new location and *p points
  3846   // to its new location.
  3848   oop thisOop = *p;
  3849   if (thisOop != NULL) {
  3850     assert((_g1->evacuation_failed()) || (!_g1->obj_in_cs(thisOop)),
  3851            "shouldn't still be in the CSet if evacuation didn't fail.");
  3852     HeapWord* addr = (HeapWord*)thisOop;
  3853     if (_g1->is_in_g1_reserved(addr))
  3854       _cm->grayRoot(oop(addr));
  3858 oop G1ParCopyHelper::copy_to_survivor_space(oop old) {
  3859   size_t    word_sz = old->size();
  3860   HeapRegion* from_region = _g1->heap_region_containing_raw(old);
  3861   // +1 to make the -1 indexes valid...
  3862   int       young_index = from_region->young_index_in_cset()+1;
  3863   assert( (from_region->is_young() && young_index > 0) ||
  3864           (!from_region->is_young() && young_index == 0), "invariant" );
  3865   G1CollectorPolicy* g1p = _g1->g1_policy();
  3866   markOop m = old->mark();
  3867   int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
  3868                                            : m->age();
  3869   GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
  3870                                                              word_sz);
  3871   HeapWord* obj_ptr = _par_scan_state->allocate(alloc_purpose, word_sz);
  3872   oop       obj     = oop(obj_ptr);
  3874   if (obj_ptr == NULL) {
  3875     // This will either forward-to-self, or detect that someone else has
  3876     // installed a forwarding pointer.
  3877     OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
  3878     return _g1->handle_evacuation_failure_par(cl, old);
  3881   // We're going to allocate linearly, so might as well prefetch ahead.
  3882   Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
  3884   oop forward_ptr = old->forward_to_atomic(obj);
  3885   if (forward_ptr == NULL) {
  3886     Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
  3887     if (g1p->track_object_age(alloc_purpose)) {
  3888       // We could simply do obj->incr_age(). However, this causes a
  3889       // performance issue. obj->incr_age() will first check whether
  3890       // the object has a displaced mark by checking its mark word;
  3891       // getting the mark word from the new location of the object
  3892       // stalls. So, given that we already have the mark word and we
  3893       // are about to install it anyway, it's better to increase the
  3894       // age on the mark word, when the object does not have a
  3895       // displaced mark word. We're not expecting many objects to have
  3896       // a displaced marked word, so that case is not optimized
  3897       // further (it could be...) and we simply call obj->incr_age().
  3899       if (m->has_displaced_mark_helper()) {
  3900         // in this case, we have to install the mark word first,
  3901         // otherwise obj looks to be forwarded (the old mark word,
  3902         // which contains the forward pointer, was copied)
  3903         obj->set_mark(m);
  3904         obj->incr_age();
  3905       } else {
  3906         m = m->incr_age();
  3907         obj->set_mark(m);
  3909       _par_scan_state->age_table()->add(obj, word_sz);
  3910     } else {
  3911       obj->set_mark(m);
  3914     // preserve "next" mark bit
  3915     if (_g1->mark_in_progress() && !_g1->is_obj_ill(old)) {
  3916       if (!use_local_bitmaps ||
  3917           !_par_scan_state->alloc_buffer(alloc_purpose)->mark(obj_ptr)) {
  3918         // if we couldn't mark it on the local bitmap (this happens when
  3919         // the object was not allocated in the GCLab), we have to bite
  3920         // the bullet and do the standard parallel mark
  3921         _cm->markAndGrayObjectIfNecessary(obj);
  3923 #if 1
  3924       if (_g1->isMarkedNext(old)) {
  3925         _cm->nextMarkBitMap()->parClear((HeapWord*)old);
  3927 #endif
  3930     size_t* surv_young_words = _par_scan_state->surviving_young_words();
  3931     surv_young_words[young_index] += word_sz;
  3933     if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
  3934       arrayOop(old)->set_length(0);
  3935       _par_scan_state->push_on_queue(set_partial_array_mask(old));
  3936     } else {
  3937       // No point in using the slower heap_region_containing() method,
  3938       // given that we know obj is in the heap.
  3939       _scanner->set_region(_g1->heap_region_containing_raw(obj));
  3940       obj->oop_iterate_backwards(_scanner);
  3942   } else {
  3943     _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz);
  3944     obj = forward_ptr;
  3946   return obj;
  3949 template<bool do_gen_barrier, G1Barrier barrier,
  3950          bool do_mark_forwardee, bool skip_cset_test>
  3951 void G1ParCopyClosure<do_gen_barrier, barrier,
  3952                       do_mark_forwardee, skip_cset_test>::do_oop_work(oop* p) {
  3953   oop obj = *p;
  3954   assert(barrier != G1BarrierRS || obj != NULL,
  3955          "Precondition: G1BarrierRS implies obj is nonNull");
  3957   // The only time we skip the cset test is when we're scanning
  3958   // references popped from the queue. And we only push on the queue
  3959   // references that we know point into the cset, so no point in
  3960   // checking again. But we'll leave an assert here for peace of mind.
  3961   assert(!skip_cset_test || _g1->obj_in_cs(obj), "invariant");
  3963   // here the null check is implicit in the cset_fast_test() test
  3964   if (skip_cset_test || _g1->in_cset_fast_test(obj)) {
  3965 #if G1_REM_SET_LOGGING
  3966     gclog_or_tty->print_cr("Loc "PTR_FORMAT" contains pointer "PTR_FORMAT" "
  3967                            "into CS.", p, (void*) obj);
  3968 #endif
  3969     if (obj->is_forwarded()) {
  3970       *p = obj->forwardee();
  3971     } else {
  3972       *p = copy_to_survivor_space(obj);
  3974     // When scanning the RS, we only care about objs in CS.
  3975     if (barrier == G1BarrierRS) {
  3976       _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
  3980   // When scanning moved objs, must look at all oops.
  3981   if (barrier == G1BarrierEvac && obj != NULL) {
  3982     _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
  3985   if (do_gen_barrier && obj != NULL) {
  3986     par_do_barrier(p);
  3990 template void G1ParCopyClosure<false, G1BarrierEvac, false, true>::do_oop_work(oop* p);
  3992 template<class T> void G1ParScanPartialArrayClosure::process_array_chunk(
  3993   oop obj, int start, int end) {
  3994   // process our set of indices (include header in first chunk)
  3995   assert(start < end, "invariant");
  3996   T* const base      = (T*)objArrayOop(obj)->base();
  3997   T* const start_addr = (start == 0) ? (T*) obj : base + start;
  3998   T* const end_addr   = base + end;
  3999   MemRegion mr((HeapWord*)start_addr, (HeapWord*)end_addr);
  4000   _scanner.set_region(_g1->heap_region_containing(obj));
  4001   obj->oop_iterate(&_scanner, mr);
  4004 void G1ParScanPartialArrayClosure::do_oop_nv(oop* p) {
  4005   assert(!UseCompressedOops, "Needs to be fixed to work with compressed oops");
  4006   assert(has_partial_array_mask(p), "invariant");
  4007   oop old = clear_partial_array_mask(p);
  4008   assert(old->is_objArray(), "must be obj array");
  4009   assert(old->is_forwarded(), "must be forwarded");
  4010   assert(Universe::heap()->is_in_reserved(old), "must be in heap.");
  4012   objArrayOop obj = objArrayOop(old->forwardee());
  4013   assert((void*)old != (void*)old->forwardee(), "self forwarding here?");
  4014   // Process ParGCArrayScanChunk elements now
  4015   // and push the remainder back onto queue
  4016   int start     = arrayOop(old)->length();
  4017   int end       = obj->length();
  4018   int remainder = end - start;
  4019   assert(start <= end, "just checking");
  4020   if (remainder > 2 * ParGCArrayScanChunk) {
  4021     // Test above combines last partial chunk with a full chunk
  4022     end = start + ParGCArrayScanChunk;
  4023     arrayOop(old)->set_length(end);
  4024     // Push remainder.
  4025     _par_scan_state->push_on_queue(set_partial_array_mask(old));
  4026   } else {
  4027     // Restore length so that the heap remains parsable in
  4028     // case of evacuation failure.
  4029     arrayOop(old)->set_length(end);
  4032   // process our set of indices (include header in first chunk)
  4033   process_array_chunk<oop>(obj, start, end);
  4036 int G1ScanAndBalanceClosure::_nq = 0;
  4038 class G1ParEvacuateFollowersClosure : public VoidClosure {
  4039 protected:
  4040   G1CollectedHeap*              _g1h;
  4041   G1ParScanThreadState*         _par_scan_state;
  4042   RefToScanQueueSet*            _queues;
  4043   ParallelTaskTerminator*       _terminator;
  4045   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
  4046   RefToScanQueueSet*      queues()         { return _queues; }
  4047   ParallelTaskTerminator* terminator()     { return _terminator; }
  4049 public:
  4050   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
  4051                                 G1ParScanThreadState* par_scan_state,
  4052                                 RefToScanQueueSet* queues,
  4053                                 ParallelTaskTerminator* terminator)
  4054     : _g1h(g1h), _par_scan_state(par_scan_state),
  4055       _queues(queues), _terminator(terminator) {}
  4057   void do_void() {
  4058     G1ParScanThreadState* pss = par_scan_state();
  4059     while (true) {
  4060       oop* ref_to_scan;
  4061       pss->trim_queue();
  4062       IF_G1_DETAILED_STATS(pss->note_steal_attempt());
  4063       if (queues()->steal(pss->queue_num(),
  4064                           pss->hash_seed(),
  4065                           ref_to_scan)) {
  4066         IF_G1_DETAILED_STATS(pss->note_steal());
  4068         // slightly paranoid tests; I'm trying to catch potential
  4069         // problems before we go into push_on_queue to know where the
  4070         // problem is coming from
  4071         assert(ref_to_scan != NULL, "invariant");
  4072         assert(has_partial_array_mask(ref_to_scan) ||
  4073                                    _g1h->obj_in_cs(*ref_to_scan), "invariant");
  4074         pss->push_on_queue(ref_to_scan);
  4075         continue;
  4077       pss->start_term_time();
  4078       if (terminator()->offer_termination()) break;
  4079       pss->end_term_time();
  4081     pss->end_term_time();
  4082     pss->retire_alloc_buffers();
  4084 };
  4086 class G1ParTask : public AbstractGangTask {
  4087 protected:
  4088   G1CollectedHeap*       _g1h;
  4089   RefToScanQueueSet      *_queues;
  4090   ParallelTaskTerminator _terminator;
  4092   Mutex _stats_lock;
  4093   Mutex* stats_lock() { return &_stats_lock; }
  4095   size_t getNCards() {
  4096     return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
  4097       / G1BlockOffsetSharedArray::N_bytes;
  4100 public:
  4101   G1ParTask(G1CollectedHeap* g1h, int workers, RefToScanQueueSet *task_queues)
  4102     : AbstractGangTask("G1 collection"),
  4103       _g1h(g1h),
  4104       _queues(task_queues),
  4105       _terminator(workers, _queues),
  4106       _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
  4107   {}
  4109   RefToScanQueueSet* queues() { return _queues; }
  4111   RefToScanQueue *work_queue(int i) {
  4112     return queues()->queue(i);
  4115   void work(int i) {
  4116     ResourceMark rm;
  4117     HandleMark   hm;
  4119     G1ParScanThreadState            pss(_g1h, i);
  4120     G1ParScanHeapEvacClosure        scan_evac_cl(_g1h, &pss);
  4121     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss);
  4122     G1ParScanPartialArrayClosure    partial_scan_cl(_g1h, &pss);
  4124     pss.set_evac_closure(&scan_evac_cl);
  4125     pss.set_evac_failure_closure(&evac_failure_cl);
  4126     pss.set_partial_scan_closure(&partial_scan_cl);
  4128     G1ParScanExtRootClosure         only_scan_root_cl(_g1h, &pss);
  4129     G1ParScanPermClosure            only_scan_perm_cl(_g1h, &pss);
  4130     G1ParScanHeapRSClosure          only_scan_heap_rs_cl(_g1h, &pss);
  4131     G1ParScanAndMarkExtRootClosure  scan_mark_root_cl(_g1h, &pss);
  4132     G1ParScanAndMarkPermClosure     scan_mark_perm_cl(_g1h, &pss);
  4133     G1ParScanAndMarkHeapRSClosure   scan_mark_heap_rs_cl(_g1h, &pss);
  4135     OopsInHeapRegionClosure        *scan_root_cl;
  4136     OopsInHeapRegionClosure        *scan_perm_cl;
  4137     OopsInHeapRegionClosure        *scan_so_cl;
  4139     if (_g1h->g1_policy()->should_initiate_conc_mark()) {
  4140       scan_root_cl = &scan_mark_root_cl;
  4141       scan_perm_cl = &scan_mark_perm_cl;
  4142       scan_so_cl   = &scan_mark_heap_rs_cl;
  4143     } else {
  4144       scan_root_cl = &only_scan_root_cl;
  4145       scan_perm_cl = &only_scan_perm_cl;
  4146       scan_so_cl   = &only_scan_heap_rs_cl;
  4149     pss.start_strong_roots();
  4150     _g1h->g1_process_strong_roots(/* not collecting perm */ false,
  4151                                   SharedHeap::SO_AllClasses,
  4152                                   scan_root_cl,
  4153                                   &only_scan_heap_rs_cl,
  4154                                   scan_so_cl,
  4155                                   scan_perm_cl,
  4156                                   i);
  4157     pss.end_strong_roots();
  4159       double start = os::elapsedTime();
  4160       G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
  4161       evac.do_void();
  4162       double elapsed_ms = (os::elapsedTime()-start)*1000.0;
  4163       double term_ms = pss.term_time()*1000.0;
  4164       _g1h->g1_policy()->record_obj_copy_time(i, elapsed_ms-term_ms);
  4165       _g1h->g1_policy()->record_termination_time(i, term_ms);
  4167     if (G1UseSurvivorSpace) {
  4168       _g1h->g1_policy()->record_thread_age_table(pss.age_table());
  4170     _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
  4172     // Clean up any par-expanded rem sets.
  4173     HeapRegionRemSet::par_cleanup();
  4175     MutexLocker x(stats_lock());
  4176     if (ParallelGCVerbose) {
  4177       gclog_or_tty->print("Thread %d complete:\n", i);
  4178 #if G1_DETAILED_STATS
  4179       gclog_or_tty->print("  Pushes: %7d    Pops: %7d   Overflows: %7d   Steals %7d (in %d attempts)\n",
  4180                           pss.pushes(),
  4181                           pss.pops(),
  4182                           pss.overflow_pushes(),
  4183                           pss.steals(),
  4184                           pss.steal_attempts());
  4185 #endif
  4186       double elapsed      = pss.elapsed();
  4187       double strong_roots = pss.strong_roots_time();
  4188       double term         = pss.term_time();
  4189       gclog_or_tty->print("  Elapsed: %7.2f ms.\n"
  4190                           "    Strong roots: %7.2f ms (%6.2f%%)\n"
  4191                           "    Termination:  %7.2f ms (%6.2f%%) (in %d entries)\n",
  4192                           elapsed * 1000.0,
  4193                           strong_roots * 1000.0, (strong_roots*100.0/elapsed),
  4194                           term * 1000.0, (term*100.0/elapsed),
  4195                           pss.term_attempts());
  4196       size_t total_waste = pss.alloc_buffer_waste() + pss.undo_waste();
  4197       gclog_or_tty->print("  Waste: %8dK\n"
  4198                  "    Alloc Buffer: %8dK\n"
  4199                  "    Undo: %8dK\n",
  4200                  (total_waste * HeapWordSize) / K,
  4201                  (pss.alloc_buffer_waste() * HeapWordSize) / K,
  4202                  (pss.undo_waste() * HeapWordSize) / K);
  4205     assert(pss.refs_to_scan() == 0, "Task queue should be empty");
  4206     assert(pss.overflowed_refs_to_scan() == 0, "Overflow queue should be empty");
  4208 };
  4210 // *** Common G1 Evacuation Stuff
  4212 class G1CountClosure: public OopsInHeapRegionClosure {
  4213 public:
  4214   int n;
  4215   G1CountClosure() : n(0) {}
  4216   void do_oop(narrowOop* p) {
  4217     guarantee(false, "NYI");
  4219   void do_oop(oop* p) {
  4220     oop obj = *p;
  4221     assert(obj != NULL && G1CollectedHeap::heap()->obj_in_cs(obj),
  4222            "Rem set closure called on non-rem-set pointer.");
  4223     n++;
  4225 };
  4227 static G1CountClosure count_closure;
  4229 void
  4230 G1CollectedHeap::
  4231 g1_process_strong_roots(bool collecting_perm_gen,
  4232                         SharedHeap::ScanningOption so,
  4233                         OopClosure* scan_non_heap_roots,
  4234                         OopsInHeapRegionClosure* scan_rs,
  4235                         OopsInHeapRegionClosure* scan_so,
  4236                         OopsInGenClosure* scan_perm,
  4237                         int worker_i) {
  4238   // First scan the strong roots, including the perm gen.
  4239   double ext_roots_start = os::elapsedTime();
  4240   double closure_app_time_sec = 0.0;
  4242   BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
  4243   BufferingOopsInGenClosure buf_scan_perm(scan_perm);
  4244   buf_scan_perm.set_generation(perm_gen());
  4246   process_strong_roots(collecting_perm_gen, so,
  4247                        &buf_scan_non_heap_roots,
  4248                        &buf_scan_perm);
  4249   // Finish up any enqueued closure apps.
  4250   buf_scan_non_heap_roots.done();
  4251   buf_scan_perm.done();
  4252   double ext_roots_end = os::elapsedTime();
  4253   g1_policy()->reset_obj_copy_time(worker_i);
  4254   double obj_copy_time_sec =
  4255     buf_scan_non_heap_roots.closure_app_seconds() +
  4256     buf_scan_perm.closure_app_seconds();
  4257   g1_policy()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
  4258   double ext_root_time_ms =
  4259     ((ext_roots_end - ext_roots_start) - obj_copy_time_sec) * 1000.0;
  4260   g1_policy()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
  4262   // Scan strong roots in mark stack.
  4263   if (!_process_strong_tasks->is_task_claimed(G1H_PS_mark_stack_oops_do)) {
  4264     concurrent_mark()->oops_do(scan_non_heap_roots);
  4266   double mark_stack_scan_ms = (os::elapsedTime() - ext_roots_end) * 1000.0;
  4267   g1_policy()->record_mark_stack_scan_time(worker_i, mark_stack_scan_ms);
  4269   // XXX What should this be doing in the parallel case?
  4270   g1_policy()->record_collection_pause_end_CH_strong_roots();
  4271   if (G1VerifyRemSet) {
  4272     // :::: FIXME ::::
  4273     // The stupid remembered set doesn't know how to filter out dead
  4274     // objects, which the smart one does, and so when it is created
  4275     // and then compared the number of entries in each differs and
  4276     // the verification code fails.
  4277     guarantee(false, "verification code is broken, see note");
  4279     // Let's make sure that the current rem set agrees with the stupidest
  4280     // one possible!
  4281     bool refs_enabled = ref_processor()->discovery_enabled();
  4282     if (refs_enabled) ref_processor()->disable_discovery();
  4283     StupidG1RemSet stupid(this);
  4284     count_closure.n = 0;
  4285     stupid.oops_into_collection_set_do(&count_closure, worker_i);
  4286     int stupid_n = count_closure.n;
  4287     count_closure.n = 0;
  4288     g1_rem_set()->oops_into_collection_set_do(&count_closure, worker_i);
  4289     guarantee(count_closure.n == stupid_n, "Old and new rem sets differ.");
  4290     gclog_or_tty->print_cr("\nFound %d pointers in heap RS.", count_closure.n);
  4291     if (refs_enabled) ref_processor()->enable_discovery();
  4293   if (scan_so != NULL) {
  4294     scan_scan_only_set(scan_so, worker_i);
  4296   // Now scan the complement of the collection set.
  4297   if (scan_rs != NULL) {
  4298     g1_rem_set()->oops_into_collection_set_do(scan_rs, worker_i);
  4300   // Finish with the ref_processor roots.
  4301   if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
  4302     ref_processor()->oops_do(scan_non_heap_roots);
  4304   g1_policy()->record_collection_pause_end_G1_strong_roots();
  4305   _process_strong_tasks->all_tasks_completed();
  4308 void
  4309 G1CollectedHeap::scan_scan_only_region(HeapRegion* r,
  4310                                        OopsInHeapRegionClosure* oc,
  4311                                        int worker_i) {
  4312   HeapWord* startAddr = r->bottom();
  4313   HeapWord* endAddr = r->used_region().end();
  4315   oc->set_region(r);
  4317   HeapWord* p = r->bottom();
  4318   HeapWord* t = r->top();
  4319   guarantee( p == r->next_top_at_mark_start(), "invariant" );
  4320   while (p < t) {
  4321     oop obj = oop(p);
  4322     p += obj->oop_iterate(oc);
  4326 void
  4327 G1CollectedHeap::scan_scan_only_set(OopsInHeapRegionClosure* oc,
  4328                                     int worker_i) {
  4329   double start = os::elapsedTime();
  4331   BufferingOopsInHeapRegionClosure boc(oc);
  4333   FilterInHeapRegionAndIntoCSClosure scan_only(this, &boc);
  4334   FilterAndMarkInHeapRegionAndIntoCSClosure scan_and_mark(this, &boc, concurrent_mark());
  4336   OopsInHeapRegionClosure *foc;
  4337   if (g1_policy()->should_initiate_conc_mark())
  4338     foc = &scan_and_mark;
  4339   else
  4340     foc = &scan_only;
  4342   HeapRegion* hr;
  4343   int n = 0;
  4344   while ((hr = _young_list->par_get_next_scan_only_region()) != NULL) {
  4345     scan_scan_only_region(hr, foc, worker_i);
  4346     ++n;
  4348   boc.done();
  4350   double closure_app_s = boc.closure_app_seconds();
  4351   g1_policy()->record_obj_copy_time(worker_i, closure_app_s * 1000.0);
  4352   double ms = (os::elapsedTime() - start - closure_app_s)*1000.0;
  4353   g1_policy()->record_scan_only_time(worker_i, ms, n);
  4356 void
  4357 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure,
  4358                                        OopClosure* non_root_closure) {
  4359   SharedHeap::process_weak_roots(root_closure, non_root_closure);
  4363 class SaveMarksClosure: public HeapRegionClosure {
  4364 public:
  4365   bool doHeapRegion(HeapRegion* r) {
  4366     r->save_marks();
  4367     return false;
  4369 };
  4371 void G1CollectedHeap::save_marks() {
  4372   if (ParallelGCThreads == 0) {
  4373     SaveMarksClosure sm;
  4374     heap_region_iterate(&sm);
  4376   // We do this even in the parallel case
  4377   perm_gen()->save_marks();
  4380 void G1CollectedHeap::evacuate_collection_set() {
  4381   set_evacuation_failed(false);
  4383   g1_rem_set()->prepare_for_oops_into_collection_set_do();
  4384   concurrent_g1_refine()->set_use_cache(false);
  4385   int n_workers = (ParallelGCThreads > 0 ? workers()->total_workers() : 1);
  4387   set_par_threads(n_workers);
  4388   G1ParTask g1_par_task(this, n_workers, _task_queues);
  4390   init_for_evac_failure(NULL);
  4392   change_strong_roots_parity();  // In preparation for parallel strong roots.
  4393   rem_set()->prepare_for_younger_refs_iterate(true);
  4394   double start_par = os::elapsedTime();
  4396   if (ParallelGCThreads > 0) {
  4397     // The individual threads will set their evac-failure closures.
  4398     workers()->run_task(&g1_par_task);
  4399   } else {
  4400     g1_par_task.work(0);
  4403   double par_time = (os::elapsedTime() - start_par) * 1000.0;
  4404   g1_policy()->record_par_time(par_time);
  4405   set_par_threads(0);
  4406   // Is this the right thing to do here?  We don't save marks
  4407   // on individual heap regions when we allocate from
  4408   // them in parallel, so this seems like the correct place for this.
  4409   retire_all_alloc_regions();
  4411     G1IsAliveClosure is_alive(this);
  4412     G1KeepAliveClosure keep_alive(this);
  4413     JNIHandles::weak_oops_do(&is_alive, &keep_alive);
  4416   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
  4417   concurrent_g1_refine()->set_use_cache(true);
  4419   finalize_for_evac_failure();
  4421   // Must do this before removing self-forwarding pointers, which clears
  4422   // the per-region evac-failure flags.
  4423   concurrent_mark()->complete_marking_in_collection_set();
  4425   if (evacuation_failed()) {
  4426     remove_self_forwarding_pointers();
  4428     if (PrintGCDetails) {
  4429       gclog_or_tty->print(" (evacuation failed)");
  4430     } else if (PrintGC) {
  4431       gclog_or_tty->print("--");
  4435   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
  4438 void G1CollectedHeap::free_region(HeapRegion* hr) {
  4439   size_t pre_used = 0;
  4440   size_t cleared_h_regions = 0;
  4441   size_t freed_regions = 0;
  4442   UncleanRegionList local_list;
  4444   HeapWord* start = hr->bottom();
  4445   HeapWord* end   = hr->prev_top_at_mark_start();
  4446   size_t used_bytes = hr->used();
  4447   size_t live_bytes = hr->max_live_bytes();
  4448   if (used_bytes > 0) {
  4449     guarantee( live_bytes <= used_bytes, "invariant" );
  4450   } else {
  4451     guarantee( live_bytes == 0, "invariant" );
  4454   size_t garbage_bytes = used_bytes - live_bytes;
  4455   if (garbage_bytes > 0)
  4456     g1_policy()->decrease_known_garbage_bytes(garbage_bytes);
  4458   free_region_work(hr, pre_used, cleared_h_regions, freed_regions,
  4459                    &local_list);
  4460   finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
  4461                           &local_list);
  4464 void
  4465 G1CollectedHeap::free_region_work(HeapRegion* hr,
  4466                                   size_t& pre_used,
  4467                                   size_t& cleared_h_regions,
  4468                                   size_t& freed_regions,
  4469                                   UncleanRegionList* list,
  4470                                   bool par) {
  4471   assert(!hr->popular(), "should not free popular regions");
  4472   pre_used += hr->used();
  4473   if (hr->isHumongous()) {
  4474     assert(hr->startsHumongous(),
  4475            "Only the start of a humongous region should be freed.");
  4476     int ind = _hrs->find(hr);
  4477     assert(ind != -1, "Should have an index.");
  4478     // Clear the start region.
  4479     hr->hr_clear(par, true /*clear_space*/);
  4480     list->insert_before_head(hr);
  4481     cleared_h_regions++;
  4482     freed_regions++;
  4483     // Clear any continued regions.
  4484     ind++;
  4485     while ((size_t)ind < n_regions()) {
  4486       HeapRegion* hrc = _hrs->at(ind);
  4487       if (!hrc->continuesHumongous()) break;
  4488       // Otherwise, does continue the H region.
  4489       assert(hrc->humongous_start_region() == hr, "Huh?");
  4490       hrc->hr_clear(par, true /*clear_space*/);
  4491       cleared_h_regions++;
  4492       freed_regions++;
  4493       list->insert_before_head(hrc);
  4494       ind++;
  4496   } else {
  4497     hr->hr_clear(par, true /*clear_space*/);
  4498     list->insert_before_head(hr);
  4499     freed_regions++;
  4500     // If we're using clear2, this should not be enabled.
  4501     // assert(!hr->in_cohort(), "Can't be both free and in a cohort.");
  4505 void G1CollectedHeap::finish_free_region_work(size_t pre_used,
  4506                                               size_t cleared_h_regions,
  4507                                               size_t freed_regions,
  4508                                               UncleanRegionList* list) {
  4509   if (list != NULL && list->sz() > 0) {
  4510     prepend_region_list_on_unclean_list(list);
  4512   // Acquire a lock, if we're parallel, to update possibly-shared
  4513   // variables.
  4514   Mutex* lock = (n_par_threads() > 0) ? ParGCRareEvent_lock : NULL;
  4516     MutexLockerEx x(lock, Mutex::_no_safepoint_check_flag);
  4517     _summary_bytes_used -= pre_used;
  4518     _num_humongous_regions -= (int) cleared_h_regions;
  4519     _free_regions += freed_regions;
  4524 void G1CollectedHeap::dirtyCardsForYoungRegions(CardTableModRefBS* ct_bs, HeapRegion* list) {
  4525   while (list != NULL) {
  4526     guarantee( list->is_young(), "invariant" );
  4528     HeapWord* bottom = list->bottom();
  4529     HeapWord* end = list->end();
  4530     MemRegion mr(bottom, end);
  4531     ct_bs->dirty(mr);
  4533     list = list->get_next_young_region();
  4537 void G1CollectedHeap::cleanUpCardTable() {
  4538   CardTableModRefBS* ct_bs = (CardTableModRefBS*) (barrier_set());
  4539   double start = os::elapsedTime();
  4541   ct_bs->clear(_g1_committed);
  4543   // now, redirty the cards of the scan-only and survivor regions
  4544   // (it seemed faster to do it this way, instead of iterating over
  4545   // all regions and then clearing / dirtying as approprite)
  4546   dirtyCardsForYoungRegions(ct_bs, _young_list->first_scan_only_region());
  4547   dirtyCardsForYoungRegions(ct_bs, _young_list->first_survivor_region());
  4549   double elapsed = os::elapsedTime() - start;
  4550   g1_policy()->record_clear_ct_time( elapsed * 1000.0);
  4554 void G1CollectedHeap::do_collection_pause_if_appropriate(size_t word_size) {
  4555   // First do any popular regions.
  4556   HeapRegion* hr;
  4557   while ((hr = popular_region_to_evac()) != NULL) {
  4558     evac_popular_region(hr);
  4560   // Now do heuristic pauses.
  4561   if (g1_policy()->should_do_collection_pause(word_size)) {
  4562     do_collection_pause();
  4566 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head) {
  4567   double young_time_ms     = 0.0;
  4568   double non_young_time_ms = 0.0;
  4570   G1CollectorPolicy* policy = g1_policy();
  4572   double start_sec = os::elapsedTime();
  4573   bool non_young = true;
  4575   HeapRegion* cur = cs_head;
  4576   int age_bound = -1;
  4577   size_t rs_lengths = 0;
  4579   while (cur != NULL) {
  4580     if (non_young) {
  4581       if (cur->is_young()) {
  4582         double end_sec = os::elapsedTime();
  4583         double elapsed_ms = (end_sec - start_sec) * 1000.0;
  4584         non_young_time_ms += elapsed_ms;
  4586         start_sec = os::elapsedTime();
  4587         non_young = false;
  4589     } else {
  4590       if (!cur->is_on_free_list()) {
  4591         double end_sec = os::elapsedTime();
  4592         double elapsed_ms = (end_sec - start_sec) * 1000.0;
  4593         young_time_ms += elapsed_ms;
  4595         start_sec = os::elapsedTime();
  4596         non_young = true;
  4600     rs_lengths += cur->rem_set()->occupied();
  4602     HeapRegion* next = cur->next_in_collection_set();
  4603     assert(cur->in_collection_set(), "bad CS");
  4604     cur->set_next_in_collection_set(NULL);
  4605     cur->set_in_collection_set(false);
  4607     if (cur->is_young()) {
  4608       int index = cur->young_index_in_cset();
  4609       guarantee( index != -1, "invariant" );
  4610       guarantee( (size_t)index < policy->young_cset_length(), "invariant" );
  4611       size_t words_survived = _surviving_young_words[index];
  4612       cur->record_surv_words_in_group(words_survived);
  4613     } else {
  4614       int index = cur->young_index_in_cset();
  4615       guarantee( index == -1, "invariant" );
  4618     assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
  4619             (!cur->is_young() && cur->young_index_in_cset() == -1),
  4620             "invariant" );
  4622     if (!cur->evacuation_failed()) {
  4623       // And the region is empty.
  4624       assert(!cur->is_empty(),
  4625              "Should not have empty regions in a CS.");
  4626       free_region(cur);
  4627     } else {
  4628       guarantee( !cur->is_scan_only(), "should not be scan only" );
  4629       cur->uninstall_surv_rate_group();
  4630       if (cur->is_young())
  4631         cur->set_young_index_in_cset(-1);
  4632       cur->set_not_young();
  4633       cur->set_evacuation_failed(false);
  4635     cur = next;
  4638   policy->record_max_rs_lengths(rs_lengths);
  4639   policy->cset_regions_freed();
  4641   double end_sec = os::elapsedTime();
  4642   double elapsed_ms = (end_sec - start_sec) * 1000.0;
  4643   if (non_young)
  4644     non_young_time_ms += elapsed_ms;
  4645   else
  4646     young_time_ms += elapsed_ms;
  4648   policy->record_young_free_cset_time_ms(young_time_ms);
  4649   policy->record_non_young_free_cset_time_ms(non_young_time_ms);
  4652 HeapRegion*
  4653 G1CollectedHeap::alloc_region_from_unclean_list_locked(bool zero_filled) {
  4654   assert(ZF_mon->owned_by_self(), "Precondition");
  4655   HeapRegion* res = pop_unclean_region_list_locked();
  4656   if (res != NULL) {
  4657     assert(!res->continuesHumongous() &&
  4658            res->zero_fill_state() != HeapRegion::Allocated,
  4659            "Only free regions on unclean list.");
  4660     if (zero_filled) {
  4661       res->ensure_zero_filled_locked();
  4662       res->set_zero_fill_allocated();
  4665   return res;
  4668 HeapRegion* G1CollectedHeap::alloc_region_from_unclean_list(bool zero_filled) {
  4669   MutexLockerEx zx(ZF_mon, Mutex::_no_safepoint_check_flag);
  4670   return alloc_region_from_unclean_list_locked(zero_filled);
  4673 void G1CollectedHeap::put_region_on_unclean_list(HeapRegion* r) {
  4674   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  4675   put_region_on_unclean_list_locked(r);
  4676   if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
  4679 void G1CollectedHeap::set_unclean_regions_coming(bool b) {
  4680   MutexLockerEx x(Cleanup_mon);
  4681   set_unclean_regions_coming_locked(b);
  4684 void G1CollectedHeap::set_unclean_regions_coming_locked(bool b) {
  4685   assert(Cleanup_mon->owned_by_self(), "Precondition");
  4686   _unclean_regions_coming = b;
  4687   // Wake up mutator threads that might be waiting for completeCleanup to
  4688   // finish.
  4689   if (!b) Cleanup_mon->notify_all();
  4692 void G1CollectedHeap::wait_for_cleanup_complete() {
  4693   MutexLockerEx x(Cleanup_mon);
  4694   wait_for_cleanup_complete_locked();
  4697 void G1CollectedHeap::wait_for_cleanup_complete_locked() {
  4698   assert(Cleanup_mon->owned_by_self(), "precondition");
  4699   while (_unclean_regions_coming) {
  4700     Cleanup_mon->wait();
  4704 void
  4705 G1CollectedHeap::put_region_on_unclean_list_locked(HeapRegion* r) {
  4706   assert(ZF_mon->owned_by_self(), "precondition.");
  4707   _unclean_region_list.insert_before_head(r);
  4710 void
  4711 G1CollectedHeap::prepend_region_list_on_unclean_list(UncleanRegionList* list) {
  4712   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  4713   prepend_region_list_on_unclean_list_locked(list);
  4714   if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
  4717 void
  4718 G1CollectedHeap::
  4719 prepend_region_list_on_unclean_list_locked(UncleanRegionList* list) {
  4720   assert(ZF_mon->owned_by_self(), "precondition.");
  4721   _unclean_region_list.prepend_list(list);
  4724 HeapRegion* G1CollectedHeap::pop_unclean_region_list_locked() {
  4725   assert(ZF_mon->owned_by_self(), "precondition.");
  4726   HeapRegion* res = _unclean_region_list.pop();
  4727   if (res != NULL) {
  4728     // Inform ZF thread that there's a new unclean head.
  4729     if (_unclean_region_list.hd() != NULL && should_zf())
  4730       ZF_mon->notify_all();
  4732   return res;
  4735 HeapRegion* G1CollectedHeap::peek_unclean_region_list_locked() {
  4736   assert(ZF_mon->owned_by_self(), "precondition.");
  4737   return _unclean_region_list.hd();
  4741 bool G1CollectedHeap::move_cleaned_region_to_free_list_locked() {
  4742   assert(ZF_mon->owned_by_self(), "Precondition");
  4743   HeapRegion* r = peek_unclean_region_list_locked();
  4744   if (r != NULL && r->zero_fill_state() == HeapRegion::ZeroFilled) {
  4745     // Result of below must be equal to "r", since we hold the lock.
  4746     (void)pop_unclean_region_list_locked();
  4747     put_free_region_on_list_locked(r);
  4748     return true;
  4749   } else {
  4750     return false;
  4754 bool G1CollectedHeap::move_cleaned_region_to_free_list() {
  4755   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  4756   return move_cleaned_region_to_free_list_locked();
  4760 void G1CollectedHeap::put_free_region_on_list_locked(HeapRegion* r) {
  4761   assert(ZF_mon->owned_by_self(), "precondition.");
  4762   assert(_free_region_list_size == free_region_list_length(), "Inv");
  4763   assert(r->zero_fill_state() == HeapRegion::ZeroFilled,
  4764         "Regions on free list must be zero filled");
  4765   assert(!r->isHumongous(), "Must not be humongous.");
  4766   assert(r->is_empty(), "Better be empty");
  4767   assert(!r->is_on_free_list(),
  4768          "Better not already be on free list");
  4769   assert(!r->is_on_unclean_list(),
  4770          "Better not already be on unclean list");
  4771   r->set_on_free_list(true);
  4772   r->set_next_on_free_list(_free_region_list);
  4773   _free_region_list = r;
  4774   _free_region_list_size++;
  4775   assert(_free_region_list_size == free_region_list_length(), "Inv");
  4778 void G1CollectedHeap::put_free_region_on_list(HeapRegion* r) {
  4779   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  4780   put_free_region_on_list_locked(r);
  4783 HeapRegion* G1CollectedHeap::pop_free_region_list_locked() {
  4784   assert(ZF_mon->owned_by_self(), "precondition.");
  4785   assert(_free_region_list_size == free_region_list_length(), "Inv");
  4786   HeapRegion* res = _free_region_list;
  4787   if (res != NULL) {
  4788     _free_region_list = res->next_from_free_list();
  4789     _free_region_list_size--;
  4790     res->set_on_free_list(false);
  4791     res->set_next_on_free_list(NULL);
  4792     assert(_free_region_list_size == free_region_list_length(), "Inv");
  4794   return res;
  4798 HeapRegion* G1CollectedHeap::alloc_free_region_from_lists(bool zero_filled) {
  4799   // By self, or on behalf of self.
  4800   assert(Heap_lock->is_locked(), "Precondition");
  4801   HeapRegion* res = NULL;
  4802   bool first = true;
  4803   while (res == NULL) {
  4804     if (zero_filled || !first) {
  4805       MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  4806       res = pop_free_region_list_locked();
  4807       if (res != NULL) {
  4808         assert(!res->zero_fill_is_allocated(),
  4809                "No allocated regions on free list.");
  4810         res->set_zero_fill_allocated();
  4811       } else if (!first) {
  4812         break;  // We tried both, time to return NULL.
  4816     if (res == NULL) {
  4817       res = alloc_region_from_unclean_list(zero_filled);
  4819     assert(res == NULL ||
  4820            !zero_filled ||
  4821            res->zero_fill_is_allocated(),
  4822            "We must have allocated the region we're returning");
  4823     first = false;
  4825   return res;
  4828 void G1CollectedHeap::remove_allocated_regions_from_lists() {
  4829   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  4831     HeapRegion* prev = NULL;
  4832     HeapRegion* cur = _unclean_region_list.hd();
  4833     while (cur != NULL) {
  4834       HeapRegion* next = cur->next_from_unclean_list();
  4835       if (cur->zero_fill_is_allocated()) {
  4836         // Remove from the list.
  4837         if (prev == NULL) {
  4838           (void)_unclean_region_list.pop();
  4839         } else {
  4840           _unclean_region_list.delete_after(prev);
  4842         cur->set_on_unclean_list(false);
  4843         cur->set_next_on_unclean_list(NULL);
  4844       } else {
  4845         prev = cur;
  4847       cur = next;
  4849     assert(_unclean_region_list.sz() == unclean_region_list_length(),
  4850            "Inv");
  4854     HeapRegion* prev = NULL;
  4855     HeapRegion* cur = _free_region_list;
  4856     while (cur != NULL) {
  4857       HeapRegion* next = cur->next_from_free_list();
  4858       if (cur->zero_fill_is_allocated()) {
  4859         // Remove from the list.
  4860         if (prev == NULL) {
  4861           _free_region_list = cur->next_from_free_list();
  4862         } else {
  4863           prev->set_next_on_free_list(cur->next_from_free_list());
  4865         cur->set_on_free_list(false);
  4866         cur->set_next_on_free_list(NULL);
  4867         _free_region_list_size--;
  4868       } else {
  4869         prev = cur;
  4871       cur = next;
  4873     assert(_free_region_list_size == free_region_list_length(), "Inv");
  4877 bool G1CollectedHeap::verify_region_lists() {
  4878   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  4879   return verify_region_lists_locked();
  4882 bool G1CollectedHeap::verify_region_lists_locked() {
  4883   HeapRegion* unclean = _unclean_region_list.hd();
  4884   while (unclean != NULL) {
  4885     guarantee(unclean->is_on_unclean_list(), "Well, it is!");
  4886     guarantee(!unclean->is_on_free_list(), "Well, it shouldn't be!");
  4887     guarantee(unclean->zero_fill_state() != HeapRegion::Allocated,
  4888               "Everything else is possible.");
  4889     unclean = unclean->next_from_unclean_list();
  4891   guarantee(_unclean_region_list.sz() == unclean_region_list_length(), "Inv");
  4893   HeapRegion* free_r = _free_region_list;
  4894   while (free_r != NULL) {
  4895     assert(free_r->is_on_free_list(), "Well, it is!");
  4896     assert(!free_r->is_on_unclean_list(), "Well, it shouldn't be!");
  4897     switch (free_r->zero_fill_state()) {
  4898     case HeapRegion::NotZeroFilled:
  4899     case HeapRegion::ZeroFilling:
  4900       guarantee(false, "Should not be on free list.");
  4901       break;
  4902     default:
  4903       // Everything else is possible.
  4904       break;
  4906     free_r = free_r->next_from_free_list();
  4908   guarantee(_free_region_list_size == free_region_list_length(), "Inv");
  4909   // If we didn't do an assertion...
  4910   return true;
  4913 size_t G1CollectedHeap::free_region_list_length() {
  4914   assert(ZF_mon->owned_by_self(), "precondition.");
  4915   size_t len = 0;
  4916   HeapRegion* cur = _free_region_list;
  4917   while (cur != NULL) {
  4918     len++;
  4919     cur = cur->next_from_free_list();
  4921   return len;
  4924 size_t G1CollectedHeap::unclean_region_list_length() {
  4925   assert(ZF_mon->owned_by_self(), "precondition.");
  4926   return _unclean_region_list.length();
  4929 size_t G1CollectedHeap::n_regions() {
  4930   return _hrs->length();
  4933 size_t G1CollectedHeap::max_regions() {
  4934   return
  4935     (size_t)align_size_up(g1_reserved_obj_bytes(), HeapRegion::GrainBytes) /
  4936     HeapRegion::GrainBytes;
  4939 size_t G1CollectedHeap::free_regions() {
  4940   /* Possibly-expensive assert.
  4941   assert(_free_regions == count_free_regions(),
  4942          "_free_regions is off.");
  4943   */
  4944   return _free_regions;
  4947 bool G1CollectedHeap::should_zf() {
  4948   return _free_region_list_size < (size_t) G1ConcZFMaxRegions;
  4951 class RegionCounter: public HeapRegionClosure {
  4952   size_t _n;
  4953 public:
  4954   RegionCounter() : _n(0) {}
  4955   bool doHeapRegion(HeapRegion* r) {
  4956     if (r->is_empty() && !r->popular()) {
  4957       assert(!r->isHumongous(), "H regions should not be empty.");
  4958       _n++;
  4960     return false;
  4962   int res() { return (int) _n; }
  4963 };
  4965 size_t G1CollectedHeap::count_free_regions() {
  4966   RegionCounter rc;
  4967   heap_region_iterate(&rc);
  4968   size_t n = rc.res();
  4969   if (_cur_alloc_region != NULL && _cur_alloc_region->is_empty())
  4970     n--;
  4971   return n;
  4974 size_t G1CollectedHeap::count_free_regions_list() {
  4975   size_t n = 0;
  4976   size_t o = 0;
  4977   ZF_mon->lock_without_safepoint_check();
  4978   HeapRegion* cur = _free_region_list;
  4979   while (cur != NULL) {
  4980     cur = cur->next_from_free_list();
  4981     n++;
  4983   size_t m = unclean_region_list_length();
  4984   ZF_mon->unlock();
  4985   return n + m;
  4988 bool G1CollectedHeap::should_set_young_locked() {
  4989   assert(heap_lock_held_for_gc(),
  4990               "the heap lock should already be held by or for this thread");
  4991   return  (g1_policy()->in_young_gc_mode() &&
  4992            g1_policy()->should_add_next_region_to_young_list());
  4995 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
  4996   assert(heap_lock_held_for_gc(),
  4997               "the heap lock should already be held by or for this thread");
  4998   _young_list->push_region(hr);
  4999   g1_policy()->set_region_short_lived(hr);
  5002 class NoYoungRegionsClosure: public HeapRegionClosure {
  5003 private:
  5004   bool _success;
  5005 public:
  5006   NoYoungRegionsClosure() : _success(true) { }
  5007   bool doHeapRegion(HeapRegion* r) {
  5008     if (r->is_young()) {
  5009       gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
  5010                              r->bottom(), r->end());
  5011       _success = false;
  5013     return false;
  5015   bool success() { return _success; }
  5016 };
  5018 bool G1CollectedHeap::check_young_list_empty(bool ignore_scan_only_list,
  5019                                              bool check_sample) {
  5020   bool ret = true;
  5022   ret = _young_list->check_list_empty(ignore_scan_only_list, check_sample);
  5023   if (!ignore_scan_only_list) {
  5024     NoYoungRegionsClosure closure;
  5025     heap_region_iterate(&closure);
  5026     ret = ret && closure.success();
  5029   return ret;
  5032 void G1CollectedHeap::empty_young_list() {
  5033   assert(heap_lock_held_for_gc(),
  5034               "the heap lock should already be held by or for this thread");
  5035   assert(g1_policy()->in_young_gc_mode(), "should be in young GC mode");
  5037   _young_list->empty_list();
  5040 bool G1CollectedHeap::all_alloc_regions_no_allocs_since_save_marks() {
  5041   bool no_allocs = true;
  5042   for (int ap = 0; ap < GCAllocPurposeCount && no_allocs; ++ap) {
  5043     HeapRegion* r = _gc_alloc_regions[ap];
  5044     no_allocs = r == NULL || r->saved_mark_at_top();
  5046   return no_allocs;
  5049 void G1CollectedHeap::retire_all_alloc_regions() {
  5050   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
  5051     HeapRegion* r = _gc_alloc_regions[ap];
  5052     if (r != NULL) {
  5053       // Check for aliases.
  5054       bool has_processed_alias = false;
  5055       for (int i = 0; i < ap; ++i) {
  5056         if (_gc_alloc_regions[i] == r) {
  5057           has_processed_alias = true;
  5058           break;
  5061       if (!has_processed_alias) {
  5062         retire_alloc_region(r, false /* par */);
  5069 // Done at the start of full GC.
  5070 void G1CollectedHeap::tear_down_region_lists() {
  5071   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  5072   while (pop_unclean_region_list_locked() != NULL) ;
  5073   assert(_unclean_region_list.hd() == NULL && _unclean_region_list.sz() == 0,
  5074          "Postconditions of loop.")
  5075   while (pop_free_region_list_locked() != NULL) ;
  5076   assert(_free_region_list == NULL, "Postcondition of loop.");
  5077   if (_free_region_list_size != 0) {
  5078     gclog_or_tty->print_cr("Size is %d.", _free_region_list_size);
  5079     print();
  5081   assert(_free_region_list_size == 0, "Postconditions of loop.");
  5085 class RegionResetter: public HeapRegionClosure {
  5086   G1CollectedHeap* _g1;
  5087   int _n;
  5088 public:
  5089   RegionResetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
  5090   bool doHeapRegion(HeapRegion* r) {
  5091     if (r->continuesHumongous()) return false;
  5092     if (r->top() > r->bottom()) {
  5093       if (r->top() < r->end()) {
  5094         Copy::fill_to_words(r->top(),
  5095                           pointer_delta(r->end(), r->top()));
  5097       r->set_zero_fill_allocated();
  5098     } else {
  5099       assert(r->is_empty(), "tautology");
  5100       if (r->popular()) {
  5101         if (r->zero_fill_state() != HeapRegion::Allocated) {
  5102           r->ensure_zero_filled_locked();
  5103           r->set_zero_fill_allocated();
  5105       } else {
  5106         _n++;
  5107         switch (r->zero_fill_state()) {
  5108         case HeapRegion::NotZeroFilled:
  5109         case HeapRegion::ZeroFilling:
  5110           _g1->put_region_on_unclean_list_locked(r);
  5111           break;
  5112         case HeapRegion::Allocated:
  5113           r->set_zero_fill_complete();
  5114           // no break; go on to put on free list.
  5115         case HeapRegion::ZeroFilled:
  5116           _g1->put_free_region_on_list_locked(r);
  5117           break;
  5121     return false;
  5124   int getFreeRegionCount() {return _n;}
  5125 };
  5127 // Done at the end of full GC.
  5128 void G1CollectedHeap::rebuild_region_lists() {
  5129   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  5130   // This needs to go at the end of the full GC.
  5131   RegionResetter rs;
  5132   heap_region_iterate(&rs);
  5133   _free_regions = rs.getFreeRegionCount();
  5134   // Tell the ZF thread it may have work to do.
  5135   if (should_zf()) ZF_mon->notify_all();
  5138 class UsedRegionsNeedZeroFillSetter: public HeapRegionClosure {
  5139   G1CollectedHeap* _g1;
  5140   int _n;
  5141 public:
  5142   UsedRegionsNeedZeroFillSetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
  5143   bool doHeapRegion(HeapRegion* r) {
  5144     if (r->continuesHumongous()) return false;
  5145     if (r->top() > r->bottom()) {
  5146       // There are assertions in "set_zero_fill_needed()" below that
  5147       // require top() == bottom(), so this is technically illegal.
  5148       // We'll skirt the law here, by making that true temporarily.
  5149       DEBUG_ONLY(HeapWord* save_top = r->top();
  5150                  r->set_top(r->bottom()));
  5151       r->set_zero_fill_needed();
  5152       DEBUG_ONLY(r->set_top(save_top));
  5154     return false;
  5156 };
  5158 // Done at the start of full GC.
  5159 void G1CollectedHeap::set_used_regions_to_need_zero_fill() {
  5160   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
  5161   // This needs to go at the end of the full GC.
  5162   UsedRegionsNeedZeroFillSetter rs;
  5163   heap_region_iterate(&rs);
  5166 class CountObjClosure: public ObjectClosure {
  5167   size_t _n;
  5168 public:
  5169   CountObjClosure() : _n(0) {}
  5170   void do_object(oop obj) { _n++; }
  5171   size_t n() { return _n; }
  5172 };
  5174 size_t G1CollectedHeap::pop_object_used_objs() {
  5175   size_t sum_objs = 0;
  5176   for (int i = 0; i < G1NumPopularRegions; i++) {
  5177     CountObjClosure cl;
  5178     _hrs->at(i)->object_iterate(&cl);
  5179     sum_objs += cl.n();
  5181   return sum_objs;
  5184 size_t G1CollectedHeap::pop_object_used_bytes() {
  5185   size_t sum_bytes = 0;
  5186   for (int i = 0; i < G1NumPopularRegions; i++) {
  5187     sum_bytes += _hrs->at(i)->used();
  5189   return sum_bytes;
  5193 static int nq = 0;
  5195 HeapWord* G1CollectedHeap::allocate_popular_object(size_t word_size) {
  5196   while (_cur_pop_hr_index < G1NumPopularRegions) {
  5197     HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
  5198     HeapWord* res = cur_pop_region->allocate(word_size);
  5199     if (res != NULL) {
  5200       // We account for popular objs directly in the used summary:
  5201       _summary_bytes_used += (word_size * HeapWordSize);
  5202       return res;
  5204     // Otherwise, try the next region (first making sure that we remember
  5205     // the last "top" value as the "next_top_at_mark_start", so that
  5206     // objects made popular during markings aren't automatically considered
  5207     // live).
  5208     cur_pop_region->note_end_of_copying();
  5209     // Otherwise, try the next region.
  5210     _cur_pop_hr_index++;
  5212   // XXX: For now !!!
  5213   vm_exit_out_of_memory(word_size,
  5214                         "Not enough pop obj space (To Be Fixed)");
  5215   return NULL;
  5218 class HeapRegionList: public CHeapObj {
  5219   public:
  5220   HeapRegion* hr;
  5221   HeapRegionList* next;
  5222 };
  5224 void G1CollectedHeap::schedule_popular_region_evac(HeapRegion* r) {
  5225   // This might happen during parallel GC, so protect by this lock.
  5226   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  5227   // We don't schedule regions whose evacuations are already pending, or
  5228   // are already being evacuated.
  5229   if (!r->popular_pending() && !r->in_collection_set()) {
  5230     r->set_popular_pending(true);
  5231     if (G1TracePopularity) {
  5232       gclog_or_tty->print_cr("Scheduling region "PTR_FORMAT" "
  5233                              "["PTR_FORMAT", "PTR_FORMAT") for pop-object evacuation.",
  5234                              r, r->bottom(), r->end());
  5236     HeapRegionList* hrl = new HeapRegionList;
  5237     hrl->hr = r;
  5238     hrl->next = _popular_regions_to_be_evacuated;
  5239     _popular_regions_to_be_evacuated = hrl;
  5243 HeapRegion* G1CollectedHeap::popular_region_to_evac() {
  5244   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  5245   HeapRegion* res = NULL;
  5246   while (_popular_regions_to_be_evacuated != NULL && res == NULL) {
  5247     HeapRegionList* hrl = _popular_regions_to_be_evacuated;
  5248     _popular_regions_to_be_evacuated = hrl->next;
  5249     res = hrl->hr;
  5250     // The G1RSPopLimit may have increased, so recheck here...
  5251     if (res->rem_set()->occupied() < (size_t) G1RSPopLimit) {
  5252       // Hah: don't need to schedule.
  5253       if (G1TracePopularity) {
  5254         gclog_or_tty->print_cr("Unscheduling region "PTR_FORMAT" "
  5255                                "["PTR_FORMAT", "PTR_FORMAT") "
  5256                                "for pop-object evacuation (size %d < limit %d)",
  5257                                res, res->bottom(), res->end(),
  5258                                res->rem_set()->occupied(), G1RSPopLimit);
  5260       res->set_popular_pending(false);
  5261       res = NULL;
  5263     // We do not reset res->popular() here; if we did so, it would allow
  5264     // the region to be "rescheduled" for popularity evacuation.  Instead,
  5265     // this is done in the collection pause, with the world stopped.
  5266     // So the invariant is that the regions in the list have the popularity
  5267     // boolean set, but having the boolean set does not imply membership
  5268     // on the list (though there can at most one such pop-pending region
  5269     // not on the list at any time).
  5270     delete hrl;
  5272   return res;
  5275 void G1CollectedHeap::evac_popular_region(HeapRegion* hr) {
  5276   while (true) {
  5277     // Don't want to do a GC pause while cleanup is being completed!
  5278     wait_for_cleanup_complete();
  5280     // Read the GC count while holding the Heap_lock
  5281     int gc_count_before = SharedHeap::heap()->total_collections();
  5282     g1_policy()->record_stop_world_start();
  5285       MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
  5286       VM_G1PopRegionCollectionPause op(gc_count_before, hr);
  5287       VMThread::execute(&op);
  5289       // If the prolog succeeded, we didn't do a GC for this.
  5290       if (op.prologue_succeeded()) break;
  5292     // Otherwise we didn't.  We should recheck the size, though, since
  5293     // the limit may have increased...
  5294     if (hr->rem_set()->occupied() < (size_t) G1RSPopLimit) {
  5295       hr->set_popular_pending(false);
  5296       break;
  5301 void G1CollectedHeap::atomic_inc_obj_rc(oop obj) {
  5302   Atomic::inc(obj_rc_addr(obj));
  5305 class CountRCClosure: public OopsInHeapRegionClosure {
  5306   G1CollectedHeap* _g1h;
  5307   bool _parallel;
  5308 public:
  5309   CountRCClosure(G1CollectedHeap* g1h) :
  5310     _g1h(g1h), _parallel(ParallelGCThreads > 0)
  5311   {}
  5312   void do_oop(narrowOop* p) {
  5313     guarantee(false, "NYI");
  5315   void do_oop(oop* p) {
  5316     oop obj = *p;
  5317     assert(obj != NULL, "Precondition.");
  5318     if (_parallel) {
  5319       // We go sticky at the limit to avoid excess contention.
  5320       // If we want to track the actual RC's further, we'll need to keep a
  5321       // per-thread hash table or something for the popular objects.
  5322       if (_g1h->obj_rc(obj) < G1ObjPopLimit) {
  5323         _g1h->atomic_inc_obj_rc(obj);
  5325     } else {
  5326       _g1h->inc_obj_rc(obj);
  5329 };
  5331 class EvacPopObjClosure: public ObjectClosure {
  5332   G1CollectedHeap* _g1h;
  5333   size_t _pop_objs;
  5334   size_t _max_rc;
  5335 public:
  5336   EvacPopObjClosure(G1CollectedHeap* g1h) :
  5337     _g1h(g1h), _pop_objs(0), _max_rc(0) {}
  5339   void do_object(oop obj) {
  5340     size_t rc = _g1h->obj_rc(obj);
  5341     _max_rc = MAX2(rc, _max_rc);
  5342     if (rc >= (size_t) G1ObjPopLimit) {
  5343       _g1h->_pop_obj_rc_at_copy.add((double)rc);
  5344       size_t word_sz = obj->size();
  5345       HeapWord* new_pop_loc = _g1h->allocate_popular_object(word_sz);
  5346       oop new_pop_obj = (oop)new_pop_loc;
  5347       Copy::aligned_disjoint_words((HeapWord*)obj, new_pop_loc, word_sz);
  5348       obj->forward_to(new_pop_obj);
  5349       G1ScanAndBalanceClosure scan_and_balance(_g1h);
  5350       new_pop_obj->oop_iterate_backwards(&scan_and_balance);
  5351       // preserve "next" mark bit if marking is in progress.
  5352       if (_g1h->mark_in_progress() && !_g1h->is_obj_ill(obj)) {
  5353         _g1h->concurrent_mark()->markAndGrayObjectIfNecessary(new_pop_obj);
  5356       if (G1TracePopularity) {
  5357         gclog_or_tty->print_cr("Found obj " PTR_FORMAT " of word size " SIZE_FORMAT
  5358                                " pop (%d), move to " PTR_FORMAT,
  5359                                (void*) obj, word_sz,
  5360                                _g1h->obj_rc(obj), (void*) new_pop_obj);
  5362       _pop_objs++;
  5365   size_t pop_objs() { return _pop_objs; }
  5366   size_t max_rc() { return _max_rc; }
  5367 };
  5369 class G1ParCountRCTask : public AbstractGangTask {
  5370   G1CollectedHeap* _g1h;
  5371   BitMap _bm;
  5373   size_t getNCards() {
  5374     return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
  5375       / G1BlockOffsetSharedArray::N_bytes;
  5377   CountRCClosure _count_rc_closure;
  5378 public:
  5379   G1ParCountRCTask(G1CollectedHeap* g1h) :
  5380     AbstractGangTask("G1 Par RC Count task"),
  5381     _g1h(g1h), _bm(getNCards()), _count_rc_closure(g1h)
  5382   {}
  5384   void work(int i) {
  5385     ResourceMark rm;
  5386     HandleMark   hm;
  5387     _g1h->g1_rem_set()->oops_into_collection_set_do(&_count_rc_closure, i);
  5389 };
  5391 void G1CollectedHeap::popularity_pause_preamble(HeapRegion* popular_region) {
  5392   // We're evacuating a single region (for popularity).
  5393   if (G1TracePopularity) {
  5394     gclog_or_tty->print_cr("Doing pop region pause for ["PTR_FORMAT", "PTR_FORMAT")",
  5395                            popular_region->bottom(), popular_region->end());
  5397   g1_policy()->set_single_region_collection_set(popular_region);
  5398   size_t max_rc;
  5399   if (!compute_reference_counts_and_evac_popular(popular_region,
  5400                                                  &max_rc)) {
  5401     // We didn't evacuate any popular objects.
  5402     // We increase the RS popularity limit, to prevent this from
  5403     // happening in the future.
  5404     if (G1RSPopLimit < (1 << 30)) {
  5405       G1RSPopLimit *= 2;
  5407     // For now, interesting enough for a message:
  5408 #if 1
  5409     gclog_or_tty->print_cr("In pop region pause for ["PTR_FORMAT", "PTR_FORMAT"), "
  5410                            "failed to find a pop object (max = %d).",
  5411                            popular_region->bottom(), popular_region->end(),
  5412                            max_rc);
  5413     gclog_or_tty->print_cr("Increased G1RSPopLimit to %d.", G1RSPopLimit);
  5414 #endif // 0
  5415     // Also, we reset the collection set to NULL, to make the rest of
  5416     // the collection do nothing.
  5417     assert(popular_region->next_in_collection_set() == NULL,
  5418            "should be single-region.");
  5419     popular_region->set_in_collection_set(false);
  5420     popular_region->set_popular_pending(false);
  5421     g1_policy()->clear_collection_set();
  5425 bool G1CollectedHeap::
  5426 compute_reference_counts_and_evac_popular(HeapRegion* popular_region,
  5427                                           size_t* max_rc) {
  5428   HeapWord* rc_region_bot;
  5429   HeapWord* rc_region_end;
  5431   // Set up the reference count region.
  5432   HeapRegion* rc_region = newAllocRegion(HeapRegion::GrainWords);
  5433   if (rc_region != NULL) {
  5434     rc_region_bot = rc_region->bottom();
  5435     rc_region_end = rc_region->end();
  5436   } else {
  5437     rc_region_bot = NEW_C_HEAP_ARRAY(HeapWord, HeapRegion::GrainWords);
  5438     if (rc_region_bot == NULL) {
  5439       vm_exit_out_of_memory(HeapRegion::GrainWords,
  5440                             "No space for RC region.");
  5442     rc_region_end = rc_region_bot + HeapRegion::GrainWords;
  5445   if (G1TracePopularity)
  5446     gclog_or_tty->print_cr("RC region is ["PTR_FORMAT", "PTR_FORMAT")",
  5447                            rc_region_bot, rc_region_end);
  5448   if (rc_region_bot > popular_region->bottom()) {
  5449     _rc_region_above = true;
  5450     _rc_region_diff =
  5451       pointer_delta(rc_region_bot, popular_region->bottom(), 1);
  5452   } else {
  5453     assert(rc_region_bot < popular_region->bottom(), "Can't be equal.");
  5454     _rc_region_above = false;
  5455     _rc_region_diff =
  5456       pointer_delta(popular_region->bottom(), rc_region_bot, 1);
  5458   g1_policy()->record_pop_compute_rc_start();
  5459   // Count external references.
  5460   g1_rem_set()->prepare_for_oops_into_collection_set_do();
  5461   if (ParallelGCThreads > 0) {
  5463     set_par_threads(workers()->total_workers());
  5464     G1ParCountRCTask par_count_rc_task(this);
  5465     workers()->run_task(&par_count_rc_task);
  5466     set_par_threads(0);
  5468   } else {
  5469     CountRCClosure count_rc_closure(this);
  5470     g1_rem_set()->oops_into_collection_set_do(&count_rc_closure, 0);
  5472   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
  5473   g1_policy()->record_pop_compute_rc_end();
  5475   // Now evacuate popular objects.
  5476   g1_policy()->record_pop_evac_start();
  5477   EvacPopObjClosure evac_pop_obj_cl(this);
  5478   popular_region->object_iterate(&evac_pop_obj_cl);
  5479   *max_rc = evac_pop_obj_cl.max_rc();
  5481   // Make sure the last "top" value of the current popular region is copied
  5482   // as the "next_top_at_mark_start", so that objects made popular during
  5483   // markings aren't automatically considered live.
  5484   HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
  5485   cur_pop_region->note_end_of_copying();
  5487   if (rc_region != NULL) {
  5488     free_region(rc_region);
  5489   } else {
  5490     FREE_C_HEAP_ARRAY(HeapWord, rc_region_bot);
  5492   g1_policy()->record_pop_evac_end();
  5494   return evac_pop_obj_cl.pop_objs() > 0;
  5497 class CountPopObjInfoClosure: public HeapRegionClosure {
  5498   size_t _objs;
  5499   size_t _bytes;
  5501   class CountObjClosure: public ObjectClosure {
  5502     int _n;
  5503   public:
  5504     CountObjClosure() : _n(0) {}
  5505     void do_object(oop obj) { _n++; }
  5506     size_t n() { return _n; }
  5507   };
  5509 public:
  5510   CountPopObjInfoClosure() : _objs(0), _bytes(0) {}
  5511   bool doHeapRegion(HeapRegion* r) {
  5512     _bytes += r->used();
  5513     CountObjClosure blk;
  5514     r->object_iterate(&blk);
  5515     _objs += blk.n();
  5516     return false;
  5518   size_t objs() { return _objs; }
  5519   size_t bytes() { return _bytes; }
  5520 };
  5523 void G1CollectedHeap::print_popularity_summary_info() const {
  5524   CountPopObjInfoClosure blk;
  5525   for (int i = 0; i <= _cur_pop_hr_index; i++) {
  5526     blk.doHeapRegion(_hrs->at(i));
  5528   gclog_or_tty->print_cr("\nPopular objects: %d objs, %d bytes.",
  5529                          blk.objs(), blk.bytes());
  5530   gclog_or_tty->print_cr("   RC at copy = [avg = %5.2f, max = %5.2f, sd = %5.2f].",
  5531                 _pop_obj_rc_at_copy.avg(),
  5532                 _pop_obj_rc_at_copy.maximum(),
  5533                 _pop_obj_rc_at_copy.sd());
  5536 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
  5537   _refine_cte_cl->set_concurrent(concurrent);
  5540 #ifndef PRODUCT
  5542 class PrintHeapRegionClosure: public HeapRegionClosure {
  5543 public:
  5544   bool doHeapRegion(HeapRegion *r) {
  5545     gclog_or_tty->print("Region: "PTR_FORMAT":", r);
  5546     if (r != NULL) {
  5547       if (r->is_on_free_list())
  5548         gclog_or_tty->print("Free ");
  5549       if (r->is_young())
  5550         gclog_or_tty->print("Young ");
  5551       if (r->isHumongous())
  5552         gclog_or_tty->print("Is Humongous ");
  5553       r->print();
  5555     return false;
  5557 };
  5559 class SortHeapRegionClosure : public HeapRegionClosure {
  5560   size_t young_regions,free_regions, unclean_regions;
  5561   size_t hum_regions, count;
  5562   size_t unaccounted, cur_unclean, cur_alloc;
  5563   size_t total_free;
  5564   HeapRegion* cur;
  5565 public:
  5566   SortHeapRegionClosure(HeapRegion *_cur) : cur(_cur), young_regions(0),
  5567     free_regions(0), unclean_regions(0),
  5568     hum_regions(0),
  5569     count(0), unaccounted(0),
  5570     cur_alloc(0), total_free(0)
  5571   {}
  5572   bool doHeapRegion(HeapRegion *r) {
  5573     count++;
  5574     if (r->is_on_free_list()) free_regions++;
  5575     else if (r->is_on_unclean_list()) unclean_regions++;
  5576     else if (r->isHumongous())  hum_regions++;
  5577     else if (r->is_young()) young_regions++;
  5578     else if (r == cur) cur_alloc++;
  5579     else unaccounted++;
  5580     return false;
  5582   void print() {
  5583     total_free = free_regions + unclean_regions;
  5584     gclog_or_tty->print("%d regions\n", count);
  5585     gclog_or_tty->print("%d free: free_list = %d unclean = %d\n",
  5586                         total_free, free_regions, unclean_regions);
  5587     gclog_or_tty->print("%d humongous %d young\n",
  5588                         hum_regions, young_regions);
  5589     gclog_or_tty->print("%d cur_alloc\n", cur_alloc);
  5590     gclog_or_tty->print("UHOH unaccounted = %d\n", unaccounted);
  5592 };
  5594 void G1CollectedHeap::print_region_counts() {
  5595   SortHeapRegionClosure sc(_cur_alloc_region);
  5596   PrintHeapRegionClosure cl;
  5597   heap_region_iterate(&cl);
  5598   heap_region_iterate(&sc);
  5599   sc.print();
  5600   print_region_accounting_info();
  5601 };
  5603 bool G1CollectedHeap::regions_accounted_for() {
  5604   // TODO: regions accounting for young/survivor/tenured
  5605   return true;
  5608 bool G1CollectedHeap::print_region_accounting_info() {
  5609   gclog_or_tty->print_cr("P regions: %d.", G1NumPopularRegions);
  5610   gclog_or_tty->print_cr("Free regions: %d (count: %d count list %d) (clean: %d unclean: %d).",
  5611                          free_regions(),
  5612                          count_free_regions(), count_free_regions_list(),
  5613                          _free_region_list_size, _unclean_region_list.sz());
  5614   gclog_or_tty->print_cr("cur_alloc: %d.",
  5615                          (_cur_alloc_region == NULL ? 0 : 1));
  5616   gclog_or_tty->print_cr("H regions: %d.", _num_humongous_regions);
  5618   // TODO: check regions accounting for young/survivor/tenured
  5619   return true;
  5622 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
  5623   HeapRegion* hr = heap_region_containing(p);
  5624   if (hr == NULL) {
  5625     return is_in_permanent(p);
  5626   } else {
  5627     return hr->is_in(p);
  5630 #endif // PRODUCT
  5632 void G1CollectedHeap::g1_unimplemented() {
  5633   // Unimplemented();
  5637 // Local Variables: ***
  5638 // c-indentation-style: gnu ***
  5639 // End: ***

mercurial