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

Fri, 12 Jun 2009 16:20:16 -0400

author
tonyp
date
Fri, 12 Jun 2009 16:20:16 -0400
changeset 1246
830ca2573896
parent 1229
315a5d70b295
child 1280
df6caf649ff7
permissions
-rw-r--r--

6850846: G1: extend G1 marking verification
Summary: extend G1 marking verification to use either the "prev" or "next" marking information, as appropriate.
Reviewed-by: johnc, ysr

     1 /*
     2  * Copyright 2001-2009 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/_g1CollectorPolicy.cpp.incl"
    28 #define PREDICTIONS_VERBOSE 0
    30 // <NEW PREDICTION>
    32 // Different defaults for different number of GC threads
    33 // They were chosen by running GCOld and SPECjbb on debris with different
    34 //   numbers of GC threads and choosing them based on the results
    36 // all the same
    37 static double rs_length_diff_defaults[] = {
    38   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
    39 };
    41 static double cost_per_card_ms_defaults[] = {
    42   0.01, 0.005, 0.005, 0.003, 0.003, 0.002, 0.002, 0.0015
    43 };
    45 static double cost_per_scan_only_region_ms_defaults[] = {
    46   1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
    47 };
    49 // all the same
    50 static double fully_young_cards_per_entry_ratio_defaults[] = {
    51   1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
    52 };
    54 static double cost_per_entry_ms_defaults[] = {
    55   0.015, 0.01, 0.01, 0.008, 0.008, 0.0055, 0.0055, 0.005
    56 };
    58 static double cost_per_byte_ms_defaults[] = {
    59   0.00006, 0.00003, 0.00003, 0.000015, 0.000015, 0.00001, 0.00001, 0.000009
    60 };
    62 // these should be pretty consistent
    63 static double constant_other_time_ms_defaults[] = {
    64   5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0
    65 };
    68 static double young_other_cost_per_region_ms_defaults[] = {
    69   0.3, 0.2, 0.2, 0.15, 0.15, 0.12, 0.12, 0.1
    70 };
    72 static double non_young_other_cost_per_region_ms_defaults[] = {
    73   1.0, 0.7, 0.7, 0.5, 0.5, 0.42, 0.42, 0.30
    74 };
    76 // </NEW PREDICTION>
    78 G1CollectorPolicy::G1CollectorPolicy() :
    79   _parallel_gc_threads((ParallelGCThreads > 0) ? ParallelGCThreads : 1),
    80   _n_pauses(0),
    81   _recent_CH_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    82   _recent_G1_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    83   _recent_evac_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    84   _recent_pause_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    85   _recent_rs_sizes(new TruncatedSeq(NumPrevPausesForHeuristics)),
    86   _recent_gc_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    87   _all_pause_times_ms(new NumberSeq()),
    88   _stop_world_start(0.0),
    89   _all_stop_world_times_ms(new NumberSeq()),
    90   _all_yield_times_ms(new NumberSeq()),
    92   _all_mod_union_times_ms(new NumberSeq()),
    94   _summary(new Summary()),
    95   _abandoned_summary(new AbandonedSummary()),
    97   _cur_clear_ct_time_ms(0.0),
    99   _region_num_young(0),
   100   _region_num_tenured(0),
   101   _prev_region_num_young(0),
   102   _prev_region_num_tenured(0),
   104   _aux_num(10),
   105   _all_aux_times_ms(new NumberSeq[_aux_num]),
   106   _cur_aux_start_times_ms(new double[_aux_num]),
   107   _cur_aux_times_ms(new double[_aux_num]),
   108   _cur_aux_times_set(new bool[_aux_num]),
   110   _concurrent_mark_init_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   111   _concurrent_mark_remark_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   112   _concurrent_mark_cleanup_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   114   // <NEW PREDICTION>
   116   _alloc_rate_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   117   _prev_collection_pause_end_ms(0.0),
   118   _pending_card_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
   119   _rs_length_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
   120   _cost_per_card_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   121   _cost_per_scan_only_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   122   _fully_young_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),
   123   _partially_young_cards_per_entry_ratio_seq(
   124                                          new TruncatedSeq(TruncatedSeqLength)),
   125   _cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   126   _partially_young_cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   127   _cost_per_byte_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   128   _cost_per_byte_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
   129   _cost_per_scan_only_region_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
   130   _constant_other_time_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   131   _young_other_cost_per_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   132   _non_young_other_cost_per_region_ms_seq(
   133                                          new TruncatedSeq(TruncatedSeqLength)),
   135   _pending_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
   136   _scanned_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
   137   _rs_lengths_seq(new TruncatedSeq(TruncatedSeqLength)),
   139   _pause_time_target_ms((double) MaxGCPauseMillis),
   141   // </NEW PREDICTION>
   143   _in_young_gc_mode(false),
   144   _full_young_gcs(true),
   145   _full_young_pause_num(0),
   146   _partial_young_pause_num(0),
   148   _during_marking(false),
   149   _in_marking_window(false),
   150   _in_marking_window_im(false),
   152   _known_garbage_ratio(0.0),
   153   _known_garbage_bytes(0),
   155   _young_gc_eff_seq(new TruncatedSeq(TruncatedSeqLength)),
   156   _target_pause_time_ms(-1.0),
   158    _recent_prev_end_times_for_all_gcs_sec(new TruncatedSeq(NumPrevPausesForHeuristics)),
   160   _recent_CS_bytes_used_before(new TruncatedSeq(NumPrevPausesForHeuristics)),
   161   _recent_CS_bytes_surviving(new TruncatedSeq(NumPrevPausesForHeuristics)),
   163   _recent_avg_pause_time_ratio(0.0),
   164   _num_markings(0),
   165   _n_marks(0),
   166   _n_pauses_at_mark_end(0),
   168   _all_full_gc_times_ms(new NumberSeq()),
   170   // G1PausesBtwnConcMark defaults to -1
   171   // so the hack is to do the cast  QQQ FIXME
   172   _pauses_btwn_concurrent_mark((size_t)G1PausesBtwnConcMark),
   173   _n_marks_since_last_pause(0),
   174   _conc_mark_initiated(false),
   175   _should_initiate_conc_mark(false),
   176   _should_revert_to_full_young_gcs(false),
   177   _last_full_young_gc(false),
   179   _prev_collection_pause_used_at_end_bytes(0),
   181   _collection_set(NULL),
   182 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
   183 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
   184 #endif // _MSC_VER
   186   _short_lived_surv_rate_group(new SurvRateGroup(this, "Short Lived",
   187                                                  G1YoungSurvRateNumRegionsSummary)),
   188   _survivor_surv_rate_group(new SurvRateGroup(this, "Survivor",
   189                                               G1YoungSurvRateNumRegionsSummary)),
   190   // add here any more surv rate groups
   191   _recorded_survivor_regions(0),
   192   _recorded_survivor_head(NULL),
   193   _recorded_survivor_tail(NULL),
   194   _survivors_age_table(true)
   196 {
   197   _recent_prev_end_times_for_all_gcs_sec->add(os::elapsedTime());
   198   _prev_collection_pause_end_ms = os::elapsedTime() * 1000.0;
   200   _par_last_ext_root_scan_times_ms = new double[_parallel_gc_threads];
   201   _par_last_mark_stack_scan_times_ms = new double[_parallel_gc_threads];
   202   _par_last_scan_only_times_ms = new double[_parallel_gc_threads];
   203   _par_last_scan_only_regions_scanned = new double[_parallel_gc_threads];
   205   _par_last_update_rs_start_times_ms = new double[_parallel_gc_threads];
   206   _par_last_update_rs_times_ms = new double[_parallel_gc_threads];
   207   _par_last_update_rs_processed_buffers = new double[_parallel_gc_threads];
   209   _par_last_scan_rs_start_times_ms = new double[_parallel_gc_threads];
   210   _par_last_scan_rs_times_ms = new double[_parallel_gc_threads];
   211   _par_last_scan_new_refs_times_ms = new double[_parallel_gc_threads];
   213   _par_last_obj_copy_times_ms = new double[_parallel_gc_threads];
   215   _par_last_termination_times_ms = new double[_parallel_gc_threads];
   217   // start conservatively
   218   _expensive_region_limit_ms = 0.5 * (double) MaxGCPauseMillis;
   220   // <NEW PREDICTION>
   222   int index;
   223   if (ParallelGCThreads == 0)
   224     index = 0;
   225   else if (ParallelGCThreads > 8)
   226     index = 7;
   227   else
   228     index = ParallelGCThreads - 1;
   230   _pending_card_diff_seq->add(0.0);
   231   _rs_length_diff_seq->add(rs_length_diff_defaults[index]);
   232   _cost_per_card_ms_seq->add(cost_per_card_ms_defaults[index]);
   233   _cost_per_scan_only_region_ms_seq->add(
   234                                  cost_per_scan_only_region_ms_defaults[index]);
   235   _fully_young_cards_per_entry_ratio_seq->add(
   236                             fully_young_cards_per_entry_ratio_defaults[index]);
   237   _cost_per_entry_ms_seq->add(cost_per_entry_ms_defaults[index]);
   238   _cost_per_byte_ms_seq->add(cost_per_byte_ms_defaults[index]);
   239   _constant_other_time_ms_seq->add(constant_other_time_ms_defaults[index]);
   240   _young_other_cost_per_region_ms_seq->add(
   241                                young_other_cost_per_region_ms_defaults[index]);
   242   _non_young_other_cost_per_region_ms_seq->add(
   243                            non_young_other_cost_per_region_ms_defaults[index]);
   245   // </NEW PREDICTION>
   247   double time_slice  = (double) GCPauseIntervalMillis / 1000.0;
   248   double max_gc_time = (double) MaxGCPauseMillis / 1000.0;
   249   guarantee(max_gc_time < time_slice,
   250             "Max GC time should not be greater than the time slice");
   251   _mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);
   252   _sigma = (double) G1ConfidencePercent / 100.0;
   254   // start conservatively (around 50ms is about right)
   255   _concurrent_mark_init_times_ms->add(0.05);
   256   _concurrent_mark_remark_times_ms->add(0.05);
   257   _concurrent_mark_cleanup_times_ms->add(0.20);
   258   _tenuring_threshold = MaxTenuringThreshold;
   260   if (G1UseSurvivorSpaces) {
   261     // if G1FixedSurvivorSpaceSize is 0 which means the size is not
   262     // fixed, then _max_survivor_regions will be calculated at
   263     // calculate_young_list_target_config during initialization
   264     _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
   265   } else {
   266     _max_survivor_regions = 0;
   267   }
   269   initialize_all();
   270 }
   272 // Increment "i", mod "len"
   273 static void inc_mod(int& i, int len) {
   274   i++; if (i == len) i = 0;
   275 }
   277 void G1CollectorPolicy::initialize_flags() {
   278   set_min_alignment(HeapRegion::GrainBytes);
   279   set_max_alignment(GenRemSet::max_alignment_constraint(rem_set_name()));
   280   if (SurvivorRatio < 1) {
   281     vm_exit_during_initialization("Invalid survivor ratio specified");
   282   }
   283   CollectorPolicy::initialize_flags();
   284 }
   286 void G1CollectorPolicy::init() {
   287   // Set aside an initial future to_space.
   288   _g1 = G1CollectedHeap::heap();
   289   size_t regions = Universe::heap()->capacity() / HeapRegion::GrainBytes;
   291   assert(Heap_lock->owned_by_self(), "Locking discipline.");
   293   if (G1SteadyStateUsed < 50) {
   294     vm_exit_during_initialization("G1SteadyStateUsed must be at least 50%.");
   295   }
   296   if (UseConcMarkSweepGC) {
   297     vm_exit_during_initialization("-XX:+UseG1GC is incompatible with "
   298                                   "-XX:+UseConcMarkSweepGC.");
   299   }
   301   initialize_gc_policy_counters();
   303   if (G1Gen) {
   304     _in_young_gc_mode = true;
   306     if (G1YoungGenSize == 0) {
   307       set_adaptive_young_list_length(true);
   308       _young_list_fixed_length = 0;
   309     } else {
   310       set_adaptive_young_list_length(false);
   311       _young_list_fixed_length = (G1YoungGenSize / HeapRegion::GrainBytes);
   312     }
   313      _free_regions_at_end_of_collection = _g1->free_regions();
   314      _scan_only_regions_at_end_of_collection = 0;
   315      calculate_young_list_min_length();
   316      guarantee( _young_list_min_length == 0, "invariant, not enough info" );
   317      calculate_young_list_target_config();
   318    } else {
   319      _young_list_fixed_length = 0;
   320     _in_young_gc_mode = false;
   321   }
   322 }
   324 // Create the jstat counters for the policy.
   325 void G1CollectorPolicy::initialize_gc_policy_counters()
   326 {
   327   _gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 2 + G1Gen);
   328 }
   330 void G1CollectorPolicy::calculate_young_list_min_length() {
   331   _young_list_min_length = 0;
   333   if (!adaptive_young_list_length())
   334     return;
   336   if (_alloc_rate_ms_seq->num() > 3) {
   337     double now_sec = os::elapsedTime();
   338     double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;
   339     double alloc_rate_ms = predict_alloc_rate_ms();
   340     int min_regions = (int) ceil(alloc_rate_ms * when_ms);
   341     int current_region_num = (int) _g1->young_list_length();
   342     _young_list_min_length = min_regions + current_region_num;
   343   }
   344 }
   346 void G1CollectorPolicy::calculate_young_list_target_config() {
   347   if (adaptive_young_list_length()) {
   348     size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
   349     calculate_young_list_target_config(rs_lengths);
   350   } else {
   351     if (full_young_gcs())
   352       _young_list_target_length = _young_list_fixed_length;
   353     else
   354       _young_list_target_length = _young_list_fixed_length / 2;
   355     _young_list_target_length = MAX2(_young_list_target_length, (size_t)1);
   356     size_t so_length = calculate_optimal_so_length(_young_list_target_length);
   357     guarantee( so_length < _young_list_target_length, "invariant" );
   358     _young_list_so_prefix_length = so_length;
   359   }
   360   calculate_survivors_policy();
   361 }
   363 // This method calculate the optimal scan-only set for a fixed young
   364 // gen size. I couldn't work out how to reuse the more elaborate one,
   365 // i.e. calculate_young_list_target_config(rs_length), as the loops are
   366 // fundamentally different (the other one finds a config for different
   367 // S-O lengths, whereas here we need to do the opposite).
   368 size_t G1CollectorPolicy::calculate_optimal_so_length(
   369                                                     size_t young_list_length) {
   370   if (!G1UseScanOnlyPrefix)
   371     return 0;
   373   if (_all_pause_times_ms->num() < 3) {
   374     // we won't use a scan-only set at the beginning to allow the rest
   375     // of the predictors to warm up
   376     return 0;
   377   }
   379   if (_cost_per_scan_only_region_ms_seq->num() < 3) {
   380     // then, we'll only set the S-O set to 1 for a little bit of time,
   381     // to get enough information on the scanning cost
   382     return 1;
   383   }
   385   size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
   386   size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
   387   size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
   388   size_t scanned_cards;
   389   if (full_young_gcs())
   390     scanned_cards = predict_young_card_num(adj_rs_lengths);
   391   else
   392     scanned_cards = predict_non_young_card_num(adj_rs_lengths);
   393   double base_time_ms = predict_base_elapsed_time_ms(pending_cards,
   394                                                      scanned_cards);
   396   size_t so_length = 0;
   397   double max_gc_eff = 0.0;
   398   for (size_t i = 0; i < young_list_length; ++i) {
   399     double gc_eff = 0.0;
   400     double pause_time_ms = 0.0;
   401     predict_gc_eff(young_list_length, i, base_time_ms,
   402                    &gc_eff, &pause_time_ms);
   403     if (gc_eff > max_gc_eff) {
   404       max_gc_eff = gc_eff;
   405       so_length = i;
   406     }
   407   }
   409   // set it to 95% of the optimal to make sure we sample the "area"
   410   // around the optimal length to get up-to-date survival rate data
   411   return so_length * 950 / 1000;
   412 }
   414 // This is a really cool piece of code! It finds the best
   415 // target configuration (young length / scan-only prefix length) so
   416 // that GC efficiency is maximized and that we also meet a pause
   417 // time. It's a triple nested loop. These loops are explained below
   418 // from the inside-out :-)
   419 //
   420 // (a) The innermost loop will try to find the optimal young length
   421 // for a fixed S-O length. It uses a binary search to speed up the
   422 // process. We assume that, for a fixed S-O length, as we add more
   423 // young regions to the CSet, the GC efficiency will only go up (I'll
   424 // skip the proof). So, using a binary search to optimize this process
   425 // makes perfect sense.
   426 //
   427 // (b) The middle loop will fix the S-O length before calling the
   428 // innermost one. It will vary it between two parameters, increasing
   429 // it by a given increment.
   430 //
   431 // (c) The outermost loop will call the middle loop three times.
   432 //   (1) The first time it will explore all possible S-O length values
   433 //   from 0 to as large as it can get, using a coarse increment (to
   434 //   quickly "home in" to where the optimal seems to be).
   435 //   (2) The second time it will explore the values around the optimal
   436 //   that was found by the first iteration using a fine increment.
   437 //   (3) Once the optimal config has been determined by the second
   438 //   iteration, we'll redo the calculation, but setting the S-O length
   439 //   to 95% of the optimal to make sure we sample the "area"
   440 //   around the optimal length to get up-to-date survival rate data
   441 //
   442 // Termination conditions for the iterations are several: the pause
   443 // time is over the limit, we do not have enough to-space, etc.
   445 void G1CollectorPolicy::calculate_young_list_target_config(size_t rs_lengths) {
   446   guarantee( adaptive_young_list_length(), "pre-condition" );
   448   double start_time_sec = os::elapsedTime();
   449   size_t min_reserve_perc = MAX2((size_t)2, (size_t)G1MinReservePercent);
   450   min_reserve_perc = MIN2((size_t) 50, min_reserve_perc);
   451   size_t reserve_regions =
   452     (size_t) ((double) min_reserve_perc * (double) _g1->n_regions() / 100.0);
   454   if (full_young_gcs() && _free_regions_at_end_of_collection > 0) {
   455     // we are in fully-young mode and there are free regions in the heap
   457     double survivor_regions_evac_time =
   458         predict_survivor_regions_evac_time();
   460     size_t min_so_length = 0;
   461     size_t max_so_length = 0;
   463     if (G1UseScanOnlyPrefix) {
   464       if (_all_pause_times_ms->num() < 3) {
   465         // we won't use a scan-only set at the beginning to allow the rest
   466         // of the predictors to warm up
   467         min_so_length = 0;
   468         max_so_length = 0;
   469       } else if (_cost_per_scan_only_region_ms_seq->num() < 3) {
   470         // then, we'll only set the S-O set to 1 for a little bit of time,
   471         // to get enough information on the scanning cost
   472         min_so_length = 1;
   473         max_so_length = 1;
   474       } else if (_in_marking_window || _last_full_young_gc) {
   475         // no S-O prefix during a marking phase either, as at the end
   476         // of the marking phase we'll have to use a very small young
   477         // length target to fill up the rest of the CSet with
   478         // non-young regions and, if we have lots of scan-only regions
   479         // left-over, we will not be able to add any more non-young
   480         // regions.
   481         min_so_length = 0;
   482         max_so_length = 0;
   483       } else {
   484         // this is the common case; we'll never reach the maximum, we
   485         // one of the end conditions will fire well before that
   486         // (hopefully!)
   487         min_so_length = 0;
   488         max_so_length = _free_regions_at_end_of_collection - 1;
   489       }
   490     } else {
   491       // no S-O prefix, as the switch is not set, but we still need to
   492       // do one iteration to calculate the best young target that
   493       // meets the pause time; this way we reuse the same code instead
   494       // of replicating it
   495       min_so_length = 0;
   496       max_so_length = 0;
   497     }
   499     double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
   500     size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
   501     size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
   502     size_t scanned_cards;
   503     if (full_young_gcs())
   504       scanned_cards = predict_young_card_num(adj_rs_lengths);
   505     else
   506       scanned_cards = predict_non_young_card_num(adj_rs_lengths);
   507     // calculate this once, so that we don't have to recalculate it in
   508     // the innermost loop
   509     double base_time_ms = predict_base_elapsed_time_ms(pending_cards, scanned_cards)
   510                           + survivor_regions_evac_time;
   511     // the result
   512     size_t final_young_length = 0;
   513     size_t final_so_length = 0;
   514     double final_gc_eff = 0.0;
   515     // we'll also keep track of how many times we go into the inner loop
   516     // this is for profiling reasons
   517     size_t calculations = 0;
   519     // this determines which of the three iterations the outer loop is in
   520     typedef enum {
   521       pass_type_coarse,
   522       pass_type_fine,
   523       pass_type_final
   524     } pass_type_t;
   526     // range of the outer loop's iteration
   527     size_t from_so_length   = min_so_length;
   528     size_t to_so_length     = max_so_length;
   529     guarantee( from_so_length <= to_so_length, "invariant" );
   531     // this will keep the S-O length that's found by the second
   532     // iteration of the outer loop; we'll keep it just in case the third
   533     // iteration fails to find something
   534     size_t fine_so_length   = 0;
   536     // the increment step for the coarse (first) iteration
   537     size_t so_coarse_increments = 5;
   539     // the common case, we'll start with the coarse iteration
   540     pass_type_t pass = pass_type_coarse;
   541     size_t so_length_incr = so_coarse_increments;
   543     if (from_so_length == to_so_length) {
   544       // not point in doing the coarse iteration, we'll go directly into
   545       // the fine one (we essentially trying to find the optimal young
   546       // length for a fixed S-O length).
   547       so_length_incr = 1;
   548       pass = pass_type_final;
   549     } else if (to_so_length - from_so_length < 3 * so_coarse_increments) {
   550       // again, the range is too short so no point in foind the coarse
   551       // iteration either
   552       so_length_incr = 1;
   553       pass = pass_type_fine;
   554     }
   556     bool done = false;
   557     // this is the outermost loop
   558     while (!done) {
   559 #ifdef TRACE_CALC_YOUNG_CONFIG
   560       // leave this in for debugging, just in case
   561       gclog_or_tty->print_cr("searching between " SIZE_FORMAT " and " SIZE_FORMAT
   562                              ", incr " SIZE_FORMAT ", pass %s",
   563                              from_so_length, to_so_length, so_length_incr,
   564                              (pass == pass_type_coarse) ? "coarse" :
   565                              (pass == pass_type_fine) ? "fine" : "final");
   566 #endif // TRACE_CALC_YOUNG_CONFIG
   568       size_t so_length = from_so_length;
   569       size_t init_free_regions =
   570         MAX2((size_t)0,
   571              _free_regions_at_end_of_collection +
   572              _scan_only_regions_at_end_of_collection - reserve_regions);
   574       // this determines whether a configuration was found
   575       bool gc_eff_set = false;
   576       // this is the middle loop
   577       while (so_length <= to_so_length) {
   578         // base time, which excludes region-related time; again we
   579         // calculate it once to avoid recalculating it in the
   580         // innermost loop
   581         double base_time_with_so_ms =
   582                            base_time_ms + predict_scan_only_time_ms(so_length);
   583         // it's already over the pause target, go around
   584         if (base_time_with_so_ms > target_pause_time_ms)
   585           break;
   587         size_t starting_young_length = so_length+1;
   589         // we make sure that the short young length that makes sense
   590         // (one more than the S-O length) is feasible
   591         size_t min_young_length = starting_young_length;
   592         double min_gc_eff;
   593         bool min_ok;
   594         ++calculations;
   595         min_ok = predict_gc_eff(min_young_length, so_length,
   596                                 base_time_with_so_ms,
   597                                 init_free_regions, target_pause_time_ms,
   598                                 &min_gc_eff);
   600         if (min_ok) {
   601           // the shortest young length is indeed feasible; we'll know
   602           // set up the max young length and we'll do a binary search
   603           // between min_young_length and max_young_length
   604           size_t max_young_length = _free_regions_at_end_of_collection - 1;
   605           double max_gc_eff = 0.0;
   606           bool max_ok = false;
   608           // the innermost loop! (finally!)
   609           while (max_young_length > min_young_length) {
   610             // we'll make sure that min_young_length is always at a
   611             // feasible config
   612             guarantee( min_ok, "invariant" );
   614             ++calculations;
   615             max_ok = predict_gc_eff(max_young_length, so_length,
   616                                     base_time_with_so_ms,
   617                                     init_free_regions, target_pause_time_ms,
   618                                     &max_gc_eff);
   620             size_t diff = (max_young_length - min_young_length) / 2;
   621             if (max_ok) {
   622               min_young_length = max_young_length;
   623               min_gc_eff = max_gc_eff;
   624               min_ok = true;
   625             }
   626             max_young_length = min_young_length + diff;
   627           }
   629           // the innermost loop found a config
   630           guarantee( min_ok, "invariant" );
   631           if (min_gc_eff > final_gc_eff) {
   632             // it's the best config so far, so we'll keep it
   633             final_gc_eff = min_gc_eff;
   634             final_young_length = min_young_length;
   635             final_so_length = so_length;
   636             gc_eff_set = true;
   637           }
   638         }
   640         // incremental the fixed S-O length and go around
   641         so_length += so_length_incr;
   642       }
   644       // this is the end of the outermost loop and we need to decide
   645       // what to do during the next iteration
   646       if (pass == pass_type_coarse) {
   647         // we just did the coarse pass (first iteration)
   649         if (!gc_eff_set)
   650           // we didn't find a feasible config so we'll just bail out; of
   651           // course, it might be the case that we missed it; but I'd say
   652           // it's a bit unlikely
   653           done = true;
   654         else {
   655           // We did find a feasible config with optimal GC eff during
   656           // the first pass. So the second pass we'll only consider the
   657           // S-O lengths around that config with a fine increment.
   659           guarantee( so_length_incr == so_coarse_increments, "invariant" );
   660           guarantee( final_so_length >= min_so_length, "invariant" );
   662 #ifdef TRACE_CALC_YOUNG_CONFIG
   663           // leave this in for debugging, just in case
   664           gclog_or_tty->print_cr("  coarse pass: SO length " SIZE_FORMAT,
   665                                  final_so_length);
   666 #endif // TRACE_CALC_YOUNG_CONFIG
   668           from_so_length =
   669             (final_so_length - min_so_length > so_coarse_increments) ?
   670             final_so_length - so_coarse_increments + 1 : min_so_length;
   671           to_so_length =
   672             (max_so_length - final_so_length > so_coarse_increments) ?
   673             final_so_length + so_coarse_increments - 1 : max_so_length;
   675           pass = pass_type_fine;
   676           so_length_incr = 1;
   677         }
   678       } else if (pass == pass_type_fine) {
   679         // we just finished the second pass
   681         if (!gc_eff_set) {
   682           // we didn't find a feasible config (yes, it's possible;
   683           // notice that, sometimes, we go directly into the fine
   684           // iteration and skip the coarse one) so we bail out
   685           done = true;
   686         } else {
   687           // We did find a feasible config with optimal GC eff
   688           guarantee( so_length_incr == 1, "invariant" );
   690           if (final_so_length == 0) {
   691             // The config is of an empty S-O set, so we'll just bail out
   692             done = true;
   693           } else {
   694             // we'll go around once more, setting the S-O length to 95%
   695             // of the optimal
   696             size_t new_so_length = 950 * final_so_length / 1000;
   698 #ifdef TRACE_CALC_YOUNG_CONFIG
   699             // leave this in for debugging, just in case
   700             gclog_or_tty->print_cr("  fine pass: SO length " SIZE_FORMAT
   701                                    ", setting it to " SIZE_FORMAT,
   702                                     final_so_length, new_so_length);
   703 #endif // TRACE_CALC_YOUNG_CONFIG
   705             from_so_length = new_so_length;
   706             to_so_length = new_so_length;
   707             fine_so_length = final_so_length;
   709             pass = pass_type_final;
   710           }
   711         }
   712       } else if (pass == pass_type_final) {
   713         // we just finished the final (third) pass
   715         if (!gc_eff_set)
   716           // we didn't find a feasible config, so we'll just use the one
   717           // we found during the second pass, which we saved
   718           final_so_length = fine_so_length;
   720         // and we're done!
   721         done = true;
   722       } else {
   723         guarantee( false, "should never reach here" );
   724       }
   726       // we now go around the outermost loop
   727     }
   729     // we should have at least one region in the target young length
   730     _young_list_target_length =
   731         MAX2((size_t) 1, final_young_length + _recorded_survivor_regions);
   732     if (final_so_length >= final_young_length)
   733       // and we need to ensure that the S-O length is not greater than
   734       // the target young length (this is being a bit careful)
   735       final_so_length = 0;
   736     _young_list_so_prefix_length = final_so_length;
   737     guarantee( !_in_marking_window || !_last_full_young_gc ||
   738                _young_list_so_prefix_length == 0, "invariant" );
   740     // let's keep an eye of how long we spend on this calculation
   741     // right now, I assume that we'll print it when we need it; we
   742     // should really adde it to the breakdown of a pause
   743     double end_time_sec = os::elapsedTime();
   744     double elapsed_time_ms = (end_time_sec - start_time_sec) * 1000.0;
   746 #ifdef TRACE_CALC_YOUNG_CONFIG
   747     // leave this in for debugging, just in case
   748     gclog_or_tty->print_cr("target = %1.1lf ms, young = " SIZE_FORMAT
   749                            ", SO = " SIZE_FORMAT ", "
   750                            "elapsed %1.2lf ms, calcs: " SIZE_FORMAT " (%s%s) "
   751                            SIZE_FORMAT SIZE_FORMAT,
   752                            target_pause_time_ms,
   753                            _young_list_target_length - _young_list_so_prefix_length,
   754                            _young_list_so_prefix_length,
   755                            elapsed_time_ms,
   756                            calculations,
   757                            full_young_gcs() ? "full" : "partial",
   758                            should_initiate_conc_mark() ? " i-m" : "",
   759                            _in_marking_window,
   760                            _in_marking_window_im);
   761 #endif // TRACE_CALC_YOUNG_CONFIG
   763     if (_young_list_target_length < _young_list_min_length) {
   764       // bummer; this means that, if we do a pause when the optimal
   765       // config dictates, we'll violate the pause spacing target (the
   766       // min length was calculate based on the application's current
   767       // alloc rate);
   769       // so, we have to bite the bullet, and allocate the minimum
   770       // number. We'll violate our target, but we just can't meet it.
   772       size_t so_length = 0;
   773       // a note further up explains why we do not want an S-O length
   774       // during marking
   775       if (!_in_marking_window && !_last_full_young_gc)
   776         // but we can still try to see whether we can find an optimal
   777         // S-O length
   778         so_length = calculate_optimal_so_length(_young_list_min_length);
   780 #ifdef TRACE_CALC_YOUNG_CONFIG
   781       // leave this in for debugging, just in case
   782       gclog_or_tty->print_cr("adjusted target length from "
   783                              SIZE_FORMAT " to " SIZE_FORMAT
   784                              ", SO " SIZE_FORMAT,
   785                              _young_list_target_length, _young_list_min_length,
   786                              so_length);
   787 #endif // TRACE_CALC_YOUNG_CONFIG
   789       _young_list_target_length =
   790         MAX2(_young_list_min_length, (size_t)1);
   791       _young_list_so_prefix_length = so_length;
   792     }
   793   } else {
   794     // we are in a partially-young mode or we've run out of regions (due
   795     // to evacuation failure)
   797 #ifdef TRACE_CALC_YOUNG_CONFIG
   798     // leave this in for debugging, just in case
   799     gclog_or_tty->print_cr("(partial) setting target to " SIZE_FORMAT
   800                            ", SO " SIZE_FORMAT,
   801                            _young_list_min_length, 0);
   802 #endif // TRACE_CALC_YOUNG_CONFIG
   804     // we'll do the pause as soon as possible and with no S-O prefix
   805     // (see above for the reasons behind the latter)
   806     _young_list_target_length =
   807       MAX2(_young_list_min_length, (size_t) 1);
   808     _young_list_so_prefix_length = 0;
   809   }
   811   _rs_lengths_prediction = rs_lengths;
   812 }
   814 // This is used by: calculate_optimal_so_length(length). It returns
   815 // the GC eff and predicted pause time for a particular config
   816 void
   817 G1CollectorPolicy::predict_gc_eff(size_t young_length,
   818                                   size_t so_length,
   819                                   double base_time_ms,
   820                                   double* ret_gc_eff,
   821                                   double* ret_pause_time_ms) {
   822   double so_time_ms = predict_scan_only_time_ms(so_length);
   823   double accum_surv_rate_adj = 0.0;
   824   if (so_length > 0)
   825     accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
   826   double accum_surv_rate =
   827     accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
   828   size_t bytes_to_copy =
   829     (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
   830   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
   831   double young_other_time_ms =
   832                        predict_young_other_time_ms(young_length - so_length);
   833   double pause_time_ms =
   834                 base_time_ms + so_time_ms + copy_time_ms + young_other_time_ms;
   835   size_t reclaimed_bytes =
   836     (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
   837   double gc_eff = (double) reclaimed_bytes / pause_time_ms;
   839   *ret_gc_eff = gc_eff;
   840   *ret_pause_time_ms = pause_time_ms;
   841 }
   843 // This is used by: calculate_young_list_target_config(rs_length). It
   844 // returns the GC eff of a particular config. It returns false if that
   845 // config violates any of the end conditions of the search in the
   846 // calling method, or true upon success. The end conditions were put
   847 // here since it's called twice and it was best not to replicate them
   848 // in the caller. Also, passing the parameteres avoids having to
   849 // recalculate them in the innermost loop.
   850 bool
   851 G1CollectorPolicy::predict_gc_eff(size_t young_length,
   852                                   size_t so_length,
   853                                   double base_time_with_so_ms,
   854                                   size_t init_free_regions,
   855                                   double target_pause_time_ms,
   856                                   double* ret_gc_eff) {
   857   *ret_gc_eff = 0.0;
   859   if (young_length >= init_free_regions)
   860     // end condition 1: not enough space for the young regions
   861     return false;
   863   double accum_surv_rate_adj = 0.0;
   864   if (so_length > 0)
   865     accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
   866   double accum_surv_rate =
   867     accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
   868   size_t bytes_to_copy =
   869     (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
   870   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
   871   double young_other_time_ms =
   872                        predict_young_other_time_ms(young_length - so_length);
   873   double pause_time_ms =
   874                    base_time_with_so_ms + copy_time_ms + young_other_time_ms;
   876   if (pause_time_ms > target_pause_time_ms)
   877     // end condition 2: over the target pause time
   878     return false;
   880   size_t reclaimed_bytes =
   881     (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
   882   size_t free_bytes =
   883                  (init_free_regions - young_length) * HeapRegion::GrainBytes;
   885   if ((2.0 + sigma()) * (double) bytes_to_copy > (double) free_bytes)
   886     // end condition 3: out of to-space (conservatively)
   887     return false;
   889   // success!
   890   double gc_eff = (double) reclaimed_bytes / pause_time_ms;
   891   *ret_gc_eff = gc_eff;
   893   return true;
   894 }
   896 double G1CollectorPolicy::predict_survivor_regions_evac_time() {
   897   double survivor_regions_evac_time = 0.0;
   898   for (HeapRegion * r = _recorded_survivor_head;
   899        r != NULL && r != _recorded_survivor_tail->get_next_young_region();
   900        r = r->get_next_young_region()) {
   901     survivor_regions_evac_time += predict_region_elapsed_time_ms(r, true);
   902   }
   903   return survivor_regions_evac_time;
   904 }
   906 void G1CollectorPolicy::check_prediction_validity() {
   907   guarantee( adaptive_young_list_length(), "should not call this otherwise" );
   909   size_t rs_lengths = _g1->young_list_sampled_rs_lengths();
   910   if (rs_lengths > _rs_lengths_prediction) {
   911     // add 10% to avoid having to recalculate often
   912     size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;
   913     calculate_young_list_target_config(rs_lengths_prediction);
   914   }
   915 }
   917 HeapWord* G1CollectorPolicy::mem_allocate_work(size_t size,
   918                                                bool is_tlab,
   919                                                bool* gc_overhead_limit_was_exceeded) {
   920   guarantee(false, "Not using this policy feature yet.");
   921   return NULL;
   922 }
   924 // This method controls how a collector handles one or more
   925 // of its generations being fully allocated.
   926 HeapWord* G1CollectorPolicy::satisfy_failed_allocation(size_t size,
   927                                                        bool is_tlab) {
   928   guarantee(false, "Not using this policy feature yet.");
   929   return NULL;
   930 }
   933 #ifndef PRODUCT
   934 bool G1CollectorPolicy::verify_young_ages() {
   935   HeapRegion* head = _g1->young_list_first_region();
   936   return
   937     verify_young_ages(head, _short_lived_surv_rate_group);
   938   // also call verify_young_ages on any additional surv rate groups
   939 }
   941 bool
   942 G1CollectorPolicy::verify_young_ages(HeapRegion* head,
   943                                      SurvRateGroup *surv_rate_group) {
   944   guarantee( surv_rate_group != NULL, "pre-condition" );
   946   const char* name = surv_rate_group->name();
   947   bool ret = true;
   948   int prev_age = -1;
   950   for (HeapRegion* curr = head;
   951        curr != NULL;
   952        curr = curr->get_next_young_region()) {
   953     SurvRateGroup* group = curr->surv_rate_group();
   954     if (group == NULL && !curr->is_survivor()) {
   955       gclog_or_tty->print_cr("## %s: encountered NULL surv_rate_group", name);
   956       ret = false;
   957     }
   959     if (surv_rate_group == group) {
   960       int age = curr->age_in_surv_rate_group();
   962       if (age < 0) {
   963         gclog_or_tty->print_cr("## %s: encountered negative age", name);
   964         ret = false;
   965       }
   967       if (age <= prev_age) {
   968         gclog_or_tty->print_cr("## %s: region ages are not strictly increasing "
   969                                "(%d, %d)", name, age, prev_age);
   970         ret = false;
   971       }
   972       prev_age = age;
   973     }
   974   }
   976   return ret;
   977 }
   978 #endif // PRODUCT
   980 void G1CollectorPolicy::record_full_collection_start() {
   981   _cur_collection_start_sec = os::elapsedTime();
   982   // Release the future to-space so that it is available for compaction into.
   983   _g1->set_full_collection();
   984 }
   986 void G1CollectorPolicy::record_full_collection_end() {
   987   // Consider this like a collection pause for the purposes of allocation
   988   // since last pause.
   989   double end_sec = os::elapsedTime();
   990   double full_gc_time_sec = end_sec - _cur_collection_start_sec;
   991   double full_gc_time_ms = full_gc_time_sec * 1000.0;
   993   checkpoint_conc_overhead();
   995   _all_full_gc_times_ms->add(full_gc_time_ms);
   997   update_recent_gc_times(end_sec, full_gc_time_ms);
   999   _g1->clear_full_collection();
  1001   // "Nuke" the heuristics that control the fully/partially young GC
  1002   // transitions and make sure we start with fully young GCs after the
  1003   // Full GC.
  1004   set_full_young_gcs(true);
  1005   _last_full_young_gc = false;
  1006   _should_revert_to_full_young_gcs = false;
  1007   _should_initiate_conc_mark = false;
  1008   _known_garbage_bytes = 0;
  1009   _known_garbage_ratio = 0.0;
  1010   _in_marking_window = false;
  1011   _in_marking_window_im = false;
  1013   _short_lived_surv_rate_group->record_scan_only_prefix(0);
  1014   _short_lived_surv_rate_group->start_adding_regions();
  1015   // also call this on any additional surv rate groups
  1017   record_survivor_regions(0, NULL, NULL);
  1019   _prev_region_num_young   = _region_num_young;
  1020   _prev_region_num_tenured = _region_num_tenured;
  1022   _free_regions_at_end_of_collection = _g1->free_regions();
  1023   _scan_only_regions_at_end_of_collection = 0;
  1024   // Reset survivors SurvRateGroup.
  1025   _survivor_surv_rate_group->reset();
  1026   calculate_young_list_min_length();
  1027   calculate_young_list_target_config();
  1030 void G1CollectorPolicy::record_before_bytes(size_t bytes) {
  1031   _bytes_in_to_space_before_gc += bytes;
  1034 void G1CollectorPolicy::record_after_bytes(size_t bytes) {
  1035   _bytes_in_to_space_after_gc += bytes;
  1038 void G1CollectorPolicy::record_stop_world_start() {
  1039   _stop_world_start = os::elapsedTime();
  1042 void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
  1043                                                       size_t start_used) {
  1044   if (PrintGCDetails) {
  1045     gclog_or_tty->stamp(PrintGCTimeStamps);
  1046     gclog_or_tty->print("[GC pause");
  1047     if (in_young_gc_mode())
  1048       gclog_or_tty->print(" (%s)", full_young_gcs() ? "young" : "partial");
  1051   assert(_g1->used_regions() == _g1->recalculate_used_regions(),
  1052          "sanity");
  1053   assert(_g1->used() == _g1->recalculate_used(), "sanity");
  1055   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
  1056   _all_stop_world_times_ms->add(s_w_t_ms);
  1057   _stop_world_start = 0.0;
  1059   _cur_collection_start_sec = start_time_sec;
  1060   _cur_collection_pause_used_at_start_bytes = start_used;
  1061   _cur_collection_pause_used_regions_at_start = _g1->used_regions();
  1062   _pending_cards = _g1->pending_card_num();
  1063   _max_pending_cards = _g1->max_pending_card_num();
  1065   _bytes_in_to_space_before_gc = 0;
  1066   _bytes_in_to_space_after_gc = 0;
  1067   _bytes_in_collection_set_before_gc = 0;
  1069 #ifdef DEBUG
  1070   // initialise these to something well known so that we can spot
  1071   // if they are not set properly
  1073   for (int i = 0; i < _parallel_gc_threads; ++i) {
  1074     _par_last_ext_root_scan_times_ms[i] = -666.0;
  1075     _par_last_mark_stack_scan_times_ms[i] = -666.0;
  1076     _par_last_scan_only_times_ms[i] = -666.0;
  1077     _par_last_scan_only_regions_scanned[i] = -666.0;
  1078     _par_last_update_rs_start_times_ms[i] = -666.0;
  1079     _par_last_update_rs_times_ms[i] = -666.0;
  1080     _par_last_update_rs_processed_buffers[i] = -666.0;
  1081     _par_last_scan_rs_start_times_ms[i] = -666.0;
  1082     _par_last_scan_rs_times_ms[i] = -666.0;
  1083     _par_last_scan_new_refs_times_ms[i] = -666.0;
  1084     _par_last_obj_copy_times_ms[i] = -666.0;
  1085     _par_last_termination_times_ms[i] = -666.0;
  1087 #endif
  1089   for (int i = 0; i < _aux_num; ++i) {
  1090     _cur_aux_times_ms[i] = 0.0;
  1091     _cur_aux_times_set[i] = false;
  1094   _satb_drain_time_set = false;
  1095   _last_satb_drain_processed_buffers = -1;
  1097   if (in_young_gc_mode())
  1098     _last_young_gc_full = false;
  1101   // do that for any other surv rate groups
  1102   _short_lived_surv_rate_group->stop_adding_regions();
  1103   size_t short_lived_so_length = _young_list_so_prefix_length;
  1104   _short_lived_surv_rate_group->record_scan_only_prefix(short_lived_so_length);
  1105   tag_scan_only(short_lived_so_length);
  1107   if (G1UseSurvivorSpaces) {
  1108     _survivors_age_table.clear();
  1111   assert( verify_young_ages(), "region age verification" );
  1114 void G1CollectorPolicy::tag_scan_only(size_t short_lived_scan_only_length) {
  1115   // done in a way that it can be extended for other surv rate groups too...
  1117   HeapRegion* head = _g1->young_list_first_region();
  1118   bool finished_short_lived = (short_lived_scan_only_length == 0);
  1120   if (finished_short_lived)
  1121     return;
  1123   for (HeapRegion* curr = head;
  1124        curr != NULL;
  1125        curr = curr->get_next_young_region()) {
  1126     SurvRateGroup* surv_rate_group = curr->surv_rate_group();
  1127     int age = curr->age_in_surv_rate_group();
  1129     if (surv_rate_group == _short_lived_surv_rate_group) {
  1130       if ((size_t)age < short_lived_scan_only_length)
  1131         curr->set_scan_only();
  1132       else
  1133         finished_short_lived = true;
  1137     if (finished_short_lived)
  1138       return;
  1141   guarantee( false, "we should never reach here" );
  1144 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
  1145   _mark_closure_time_ms = mark_closure_time_ms;
  1148 void G1CollectorPolicy::record_concurrent_mark_init_start() {
  1149   _mark_init_start_sec = os::elapsedTime();
  1150   guarantee(!in_young_gc_mode(), "should not do be here in young GC mode");
  1153 void G1CollectorPolicy::record_concurrent_mark_init_end_pre(double
  1154                                                    mark_init_elapsed_time_ms) {
  1155   _during_marking = true;
  1156   _should_initiate_conc_mark = false;
  1157   _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
  1160 void G1CollectorPolicy::record_concurrent_mark_init_end() {
  1161   double end_time_sec = os::elapsedTime();
  1162   double elapsed_time_ms = (end_time_sec - _mark_init_start_sec) * 1000.0;
  1163   _concurrent_mark_init_times_ms->add(elapsed_time_ms);
  1164   checkpoint_conc_overhead();
  1165   record_concurrent_mark_init_end_pre(elapsed_time_ms);
  1167   _mmu_tracker->add_pause(_mark_init_start_sec, end_time_sec, true);
  1170 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
  1171   _mark_remark_start_sec = os::elapsedTime();
  1172   _during_marking = false;
  1175 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
  1176   double end_time_sec = os::elapsedTime();
  1177   double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
  1178   checkpoint_conc_overhead();
  1179   _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
  1180   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1181   _prev_collection_pause_end_ms += elapsed_time_ms;
  1183   _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
  1186 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
  1187   _mark_cleanup_start_sec = os::elapsedTime();
  1190 void
  1191 G1CollectorPolicy::record_concurrent_mark_cleanup_end(size_t freed_bytes,
  1192                                                       size_t max_live_bytes) {
  1193   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  1194   record_concurrent_mark_cleanup_end_work2();
  1197 void
  1198 G1CollectorPolicy::
  1199 record_concurrent_mark_cleanup_end_work1(size_t freed_bytes,
  1200                                          size_t max_live_bytes) {
  1201   if (_n_marks < 2) _n_marks++;
  1202   if (G1PolicyVerbose > 0)
  1203     gclog_or_tty->print_cr("At end of marking, max_live is " SIZE_FORMAT " MB "
  1204                            " (of " SIZE_FORMAT " MB heap).",
  1205                            max_live_bytes/M, _g1->capacity()/M);
  1208 // The important thing about this is that it includes "os::elapsedTime".
  1209 void G1CollectorPolicy::record_concurrent_mark_cleanup_end_work2() {
  1210   checkpoint_conc_overhead();
  1211   double end_time_sec = os::elapsedTime();
  1212   double elapsed_time_ms = (end_time_sec - _mark_cleanup_start_sec)*1000.0;
  1213   _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
  1214   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1215   _prev_collection_pause_end_ms += elapsed_time_ms;
  1217   _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_time_sec, true);
  1219   _num_markings++;
  1221   // We did a marking, so reset the "since_last_mark" variables.
  1222   double considerConcMarkCost = 1.0;
  1223   // If there are available processors, concurrent activity is free...
  1224   if (Threads::number_of_non_daemon_threads() * 2 <
  1225       os::active_processor_count()) {
  1226     considerConcMarkCost = 0.0;
  1228   _n_pauses_at_mark_end = _n_pauses;
  1229   _n_marks_since_last_pause++;
  1230   _conc_mark_initiated = false;
  1233 void
  1234 G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
  1235   if (in_young_gc_mode()) {
  1236     _should_revert_to_full_young_gcs = false;
  1237     _last_full_young_gc = true;
  1238     _in_marking_window = false;
  1239     if (adaptive_young_list_length())
  1240       calculate_young_list_target_config();
  1244 void G1CollectorPolicy::record_concurrent_pause() {
  1245   if (_stop_world_start > 0.0) {
  1246     double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
  1247     _all_yield_times_ms->add(yield_ms);
  1251 void G1CollectorPolicy::record_concurrent_pause_end() {
  1254 void G1CollectorPolicy::record_collection_pause_end_CH_strong_roots() {
  1255   _cur_CH_strong_roots_end_sec = os::elapsedTime();
  1256   _cur_CH_strong_roots_dur_ms =
  1257     (_cur_CH_strong_roots_end_sec - _cur_collection_start_sec) * 1000.0;
  1260 void G1CollectorPolicy::record_collection_pause_end_G1_strong_roots() {
  1261   _cur_G1_strong_roots_end_sec = os::elapsedTime();
  1262   _cur_G1_strong_roots_dur_ms =
  1263     (_cur_G1_strong_roots_end_sec - _cur_CH_strong_roots_end_sec) * 1000.0;
  1266 template<class T>
  1267 T sum_of(T* sum_arr, int start, int n, int N) {
  1268   T sum = (T)0;
  1269   for (int i = 0; i < n; i++) {
  1270     int j = (start + i) % N;
  1271     sum += sum_arr[j];
  1273   return sum;
  1276 void G1CollectorPolicy::print_par_stats (int level,
  1277                                          const char* str,
  1278                                          double* data,
  1279                                          bool summary) {
  1280   double min = data[0], max = data[0];
  1281   double total = 0.0;
  1282   int j;
  1283   for (j = 0; j < level; ++j)
  1284     gclog_or_tty->print("   ");
  1285   gclog_or_tty->print("[%s (ms):", str);
  1286   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1287     double val = data[i];
  1288     if (val < min)
  1289       min = val;
  1290     if (val > max)
  1291       max = val;
  1292     total += val;
  1293     gclog_or_tty->print("  %3.1lf", val);
  1295   if (summary) {
  1296     gclog_or_tty->print_cr("");
  1297     double avg = total / (double) ParallelGCThreads;
  1298     gclog_or_tty->print(" ");
  1299     for (j = 0; j < level; ++j)
  1300       gclog_or_tty->print("   ");
  1301     gclog_or_tty->print("Avg: %5.1lf, Min: %5.1lf, Max: %5.1lf",
  1302                         avg, min, max);
  1304   gclog_or_tty->print_cr("]");
  1307 void G1CollectorPolicy::print_par_buffers (int level,
  1308                                          const char* str,
  1309                                          double* data,
  1310                                          bool summary) {
  1311   double min = data[0], max = data[0];
  1312   double total = 0.0;
  1313   int j;
  1314   for (j = 0; j < level; ++j)
  1315     gclog_or_tty->print("   ");
  1316   gclog_or_tty->print("[%s :", str);
  1317   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1318     double val = data[i];
  1319     if (val < min)
  1320       min = val;
  1321     if (val > max)
  1322       max = val;
  1323     total += val;
  1324     gclog_or_tty->print(" %d", (int) val);
  1326   if (summary) {
  1327     gclog_or_tty->print_cr("");
  1328     double avg = total / (double) ParallelGCThreads;
  1329     gclog_or_tty->print(" ");
  1330     for (j = 0; j < level; ++j)
  1331       gclog_or_tty->print("   ");
  1332     gclog_or_tty->print("Sum: %d, Avg: %d, Min: %d, Max: %d",
  1333                (int)total, (int)avg, (int)min, (int)max);
  1335   gclog_or_tty->print_cr("]");
  1338 void G1CollectorPolicy::print_stats (int level,
  1339                                      const char* str,
  1340                                      double value) {
  1341   for (int j = 0; j < level; ++j)
  1342     gclog_or_tty->print("   ");
  1343   gclog_or_tty->print_cr("[%s: %5.1lf ms]", str, value);
  1346 void G1CollectorPolicy::print_stats (int level,
  1347                                      const char* str,
  1348                                      int value) {
  1349   for (int j = 0; j < level; ++j)
  1350     gclog_or_tty->print("   ");
  1351   gclog_or_tty->print_cr("[%s: %d]", str, value);
  1354 double G1CollectorPolicy::avg_value (double* data) {
  1355   if (ParallelGCThreads > 0) {
  1356     double ret = 0.0;
  1357     for (uint i = 0; i < ParallelGCThreads; ++i)
  1358       ret += data[i];
  1359     return ret / (double) ParallelGCThreads;
  1360   } else {
  1361     return data[0];
  1365 double G1CollectorPolicy::max_value (double* data) {
  1366   if (ParallelGCThreads > 0) {
  1367     double ret = data[0];
  1368     for (uint i = 1; i < ParallelGCThreads; ++i)
  1369       if (data[i] > ret)
  1370         ret = data[i];
  1371     return ret;
  1372   } else {
  1373     return data[0];
  1377 double G1CollectorPolicy::sum_of_values (double* data) {
  1378   if (ParallelGCThreads > 0) {
  1379     double sum = 0.0;
  1380     for (uint i = 0; i < ParallelGCThreads; i++)
  1381       sum += data[i];
  1382     return sum;
  1383   } else {
  1384     return data[0];
  1388 double G1CollectorPolicy::max_sum (double* data1,
  1389                                    double* data2) {
  1390   double ret = data1[0] + data2[0];
  1392   if (ParallelGCThreads > 0) {
  1393     for (uint i = 1; i < ParallelGCThreads; ++i) {
  1394       double data = data1[i] + data2[i];
  1395       if (data > ret)
  1396         ret = data;
  1399   return ret;
  1402 // Anything below that is considered to be zero
  1403 #define MIN_TIMER_GRANULARITY 0.0000001
  1405 void G1CollectorPolicy::record_collection_pause_end(bool abandoned) {
  1406   double end_time_sec = os::elapsedTime();
  1407   double elapsed_ms = _last_pause_time_ms;
  1408   bool parallel = ParallelGCThreads > 0;
  1409   double evac_ms = (end_time_sec - _cur_G1_strong_roots_end_sec) * 1000.0;
  1410   size_t rs_size =
  1411     _cur_collection_pause_used_regions_at_start - collection_set_size();
  1412   size_t cur_used_bytes = _g1->used();
  1413   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
  1414   bool last_pause_included_initial_mark = false;
  1415   bool update_stats = !abandoned && !_g1->evacuation_failed();
  1417 #ifndef PRODUCT
  1418   if (G1YoungSurvRateVerbose) {
  1419     gclog_or_tty->print_cr("");
  1420     _short_lived_surv_rate_group->print();
  1421     // do that for any other surv rate groups too
  1423 #endif // PRODUCT
  1425   checkpoint_conc_overhead();
  1427   if (in_young_gc_mode()) {
  1428     last_pause_included_initial_mark = _should_initiate_conc_mark;
  1429     if (last_pause_included_initial_mark)
  1430       record_concurrent_mark_init_end_pre(0.0);
  1432     size_t min_used_targ =
  1433       (_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta);
  1435     if (cur_used_bytes > min_used_targ) {
  1436       if (cur_used_bytes <= _prev_collection_pause_used_at_end_bytes) {
  1437       } else if (!_g1->mark_in_progress() && !_last_full_young_gc) {
  1438         _should_initiate_conc_mark = true;
  1442     _prev_collection_pause_used_at_end_bytes = cur_used_bytes;
  1445   _mmu_tracker->add_pause(end_time_sec - elapsed_ms/1000.0,
  1446                           end_time_sec, false);
  1448   guarantee(_cur_collection_pause_used_regions_at_start >=
  1449             collection_set_size(),
  1450             "Negative RS size?");
  1452   // This assert is exempted when we're doing parallel collection pauses,
  1453   // because the fragmentation caused by the parallel GC allocation buffers
  1454   // can lead to more memory being used during collection than was used
  1455   // before. Best leave this out until the fragmentation problem is fixed.
  1456   // Pauses in which evacuation failed can also lead to negative
  1457   // collections, since no space is reclaimed from a region containing an
  1458   // object whose evacuation failed.
  1459   // Further, we're now always doing parallel collection.  But I'm still
  1460   // leaving this here as a placeholder for a more precise assertion later.
  1461   // (DLD, 10/05.)
  1462   assert((true || parallel) // Always using GC LABs now.
  1463          || _g1->evacuation_failed()
  1464          || _cur_collection_pause_used_at_start_bytes >= cur_used_bytes,
  1465          "Negative collection");
  1467   size_t freed_bytes =
  1468     _cur_collection_pause_used_at_start_bytes - cur_used_bytes;
  1469   size_t surviving_bytes = _collection_set_bytes_used_before - freed_bytes;
  1470   double survival_fraction =
  1471     (double)surviving_bytes/
  1472     (double)_collection_set_bytes_used_before;
  1474   _n_pauses++;
  1476   if (update_stats) {
  1477     _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
  1478     _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
  1479     _recent_evac_times_ms->add(evac_ms);
  1480     _recent_pause_times_ms->add(elapsed_ms);
  1482     _recent_rs_sizes->add(rs_size);
  1484     // We exempt parallel collection from this check because Alloc Buffer
  1485     // fragmentation can produce negative collections.  Same with evac
  1486     // failure.
  1487     // Further, we're now always doing parallel collection.  But I'm still
  1488     // leaving this here as a placeholder for a more precise assertion later.
  1489     // (DLD, 10/05.
  1490     assert((true || parallel)
  1491            || _g1->evacuation_failed()
  1492            || surviving_bytes <= _collection_set_bytes_used_before,
  1493            "Or else negative collection!");
  1494     _recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
  1495     _recent_CS_bytes_surviving->add(surviving_bytes);
  1497     // this is where we update the allocation rate of the application
  1498     double app_time_ms =
  1499       (_cur_collection_start_sec * 1000.0 - _prev_collection_pause_end_ms);
  1500     if (app_time_ms < MIN_TIMER_GRANULARITY) {
  1501       // This usually happens due to the timer not having the required
  1502       // granularity. Some Linuxes are the usual culprits.
  1503       // We'll just set it to something (arbitrarily) small.
  1504       app_time_ms = 1.0;
  1506     size_t regions_allocated =
  1507       (_region_num_young - _prev_region_num_young) +
  1508       (_region_num_tenured - _prev_region_num_tenured);
  1509     double alloc_rate_ms = (double) regions_allocated / app_time_ms;
  1510     _alloc_rate_ms_seq->add(alloc_rate_ms);
  1511     _prev_region_num_young   = _region_num_young;
  1512     _prev_region_num_tenured = _region_num_tenured;
  1514     double interval_ms =
  1515       (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
  1516     update_recent_gc_times(end_time_sec, elapsed_ms);
  1517     _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
  1518     assert(recent_avg_pause_time_ratio() < 1.00, "All GC?");
  1521   if (G1PolicyVerbose > 1) {
  1522     gclog_or_tty->print_cr("   Recording collection pause(%d)", _n_pauses);
  1525   PauseSummary* summary;
  1526   if (abandoned) {
  1527     summary = _abandoned_summary;
  1528   } else {
  1529     summary = _summary;
  1532   double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
  1533   double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
  1534   double scan_only_time = avg_value(_par_last_scan_only_times_ms);
  1535   double scan_only_regions_scanned =
  1536     sum_of_values(_par_last_scan_only_regions_scanned);
  1537   double update_rs_time = avg_value(_par_last_update_rs_times_ms);
  1538   double update_rs_processed_buffers =
  1539     sum_of_values(_par_last_update_rs_processed_buffers);
  1540   double scan_rs_time = avg_value(_par_last_scan_rs_times_ms);
  1541   double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
  1542   double termination_time = avg_value(_par_last_termination_times_ms);
  1544   double parallel_other_time = _cur_collection_par_time_ms -
  1545     (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
  1546      scan_only_time + scan_rs_time + obj_copy_time + termination_time);
  1547   if (update_stats) {
  1548     MainBodySummary* body_summary = summary->main_body_summary();
  1549     guarantee(body_summary != NULL, "should not be null!");
  1551     if (_satb_drain_time_set)
  1552       body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
  1553     else
  1554       body_summary->record_satb_drain_time_ms(0.0);
  1555     body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
  1556     body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
  1557     body_summary->record_scan_only_time_ms(scan_only_time);
  1558     body_summary->record_update_rs_time_ms(update_rs_time);
  1559     body_summary->record_scan_rs_time_ms(scan_rs_time);
  1560     body_summary->record_obj_copy_time_ms(obj_copy_time);
  1561     if (parallel) {
  1562       body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
  1563       body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
  1564       body_summary->record_termination_time_ms(termination_time);
  1565       body_summary->record_parallel_other_time_ms(parallel_other_time);
  1567     body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
  1570   if (G1PolicyVerbose > 1) {
  1571     gclog_or_tty->print_cr("      ET: %10.6f ms           (avg: %10.6f ms)\n"
  1572                            "        CH Strong: %10.6f ms    (avg: %10.6f ms)\n"
  1573                            "        G1 Strong: %10.6f ms    (avg: %10.6f ms)\n"
  1574                            "        Evac:      %10.6f ms    (avg: %10.6f ms)\n"
  1575                            "       ET-RS:  %10.6f ms      (avg: %10.6f ms)\n"
  1576                            "      |RS|: " SIZE_FORMAT,
  1577                            elapsed_ms, recent_avg_time_for_pauses_ms(),
  1578                            _cur_CH_strong_roots_dur_ms, recent_avg_time_for_CH_strong_ms(),
  1579                            _cur_G1_strong_roots_dur_ms, recent_avg_time_for_G1_strong_ms(),
  1580                            evac_ms, recent_avg_time_for_evac_ms(),
  1581                            scan_rs_time,
  1582                            recent_avg_time_for_pauses_ms() -
  1583                            recent_avg_time_for_G1_strong_ms(),
  1584                            rs_size);
  1586     gclog_or_tty->print_cr("       Used at start: " SIZE_FORMAT"K"
  1587                            "       At end " SIZE_FORMAT "K\n"
  1588                            "       garbage      : " SIZE_FORMAT "K"
  1589                            "       of     " SIZE_FORMAT "K\n"
  1590                            "       survival     : %6.2f%%  (%6.2f%% avg)",
  1591                            _cur_collection_pause_used_at_start_bytes/K,
  1592                            _g1->used()/K, freed_bytes/K,
  1593                            _collection_set_bytes_used_before/K,
  1594                            survival_fraction*100.0,
  1595                            recent_avg_survival_fraction()*100.0);
  1596     gclog_or_tty->print_cr("       Recent %% gc pause time: %6.2f",
  1597                            recent_avg_pause_time_ratio() * 100.0);
  1600   double other_time_ms = elapsed_ms;
  1602   if (!abandoned) {
  1603     if (_satb_drain_time_set)
  1604       other_time_ms -= _cur_satb_drain_time_ms;
  1606     if (parallel)
  1607       other_time_ms -= _cur_collection_par_time_ms + _cur_clear_ct_time_ms;
  1608     else
  1609       other_time_ms -=
  1610         update_rs_time +
  1611         ext_root_scan_time + mark_stack_scan_time + scan_only_time +
  1612         scan_rs_time + obj_copy_time;
  1615   if (PrintGCDetails) {
  1616     gclog_or_tty->print_cr("%s%s, %1.8lf secs]",
  1617                            abandoned ? " (abandoned)" : "",
  1618                            (last_pause_included_initial_mark) ? " (initial-mark)" : "",
  1619                            elapsed_ms / 1000.0);
  1621     if (!abandoned) {
  1622       if (_satb_drain_time_set) {
  1623         print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
  1625       if (_last_satb_drain_processed_buffers >= 0) {
  1626         print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
  1628       if (parallel) {
  1629         print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
  1630         print_par_stats(2, "Update RS (Start)", _par_last_update_rs_start_times_ms, false);
  1631         print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
  1632         print_par_buffers(3, "Processed Buffers",
  1633                           _par_last_update_rs_processed_buffers, true);
  1634         print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
  1635         print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
  1636         print_par_stats(2, "Scan-Only Scanning", _par_last_scan_only_times_ms);
  1637         print_par_buffers(3, "Scan-Only Regions",
  1638                           _par_last_scan_only_regions_scanned, true);
  1639         print_par_stats(2, "Scan RS", _par_last_scan_rs_times_ms);
  1640         print_par_stats(2, "Object Copy", _par_last_obj_copy_times_ms);
  1641         print_par_stats(2, "Termination", _par_last_termination_times_ms);
  1642         print_stats(2, "Other", parallel_other_time);
  1643         print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
  1644       } else {
  1645         print_stats(1, "Update RS", update_rs_time);
  1646         print_stats(2, "Processed Buffers",
  1647                     (int)update_rs_processed_buffers);
  1648         print_stats(1, "Ext Root Scanning", ext_root_scan_time);
  1649         print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
  1650         print_stats(1, "Scan-Only Scanning", scan_only_time);
  1651         print_stats(1, "Scan RS", scan_rs_time);
  1652         print_stats(1, "Object Copying", obj_copy_time);
  1655     print_stats(1, "Other", other_time_ms);
  1656     for (int i = 0; i < _aux_num; ++i) {
  1657       if (_cur_aux_times_set[i]) {
  1658         char buffer[96];
  1659         sprintf(buffer, "Aux%d", i);
  1660         print_stats(1, buffer, _cur_aux_times_ms[i]);
  1664   if (PrintGCDetails)
  1665     gclog_or_tty->print("   [");
  1666   if (PrintGC || PrintGCDetails)
  1667     _g1->print_size_transition(gclog_or_tty,
  1668                                _cur_collection_pause_used_at_start_bytes,
  1669                                _g1->used(), _g1->capacity());
  1670   if (PrintGCDetails)
  1671     gclog_or_tty->print_cr("]");
  1673   _all_pause_times_ms->add(elapsed_ms);
  1674   if (update_stats) {
  1675     summary->record_total_time_ms(elapsed_ms);
  1676     summary->record_other_time_ms(other_time_ms);
  1678   for (int i = 0; i < _aux_num; ++i)
  1679     if (_cur_aux_times_set[i])
  1680       _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
  1682   // Reset marks-between-pauses counter.
  1683   _n_marks_since_last_pause = 0;
  1685   // Update the efficiency-since-mark vars.
  1686   double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
  1687   if (elapsed_ms < MIN_TIMER_GRANULARITY) {
  1688     // This usually happens due to the timer not having the required
  1689     // granularity. Some Linuxes are the usual culprits.
  1690     // We'll just set it to something (arbitrarily) small.
  1691     proc_ms = 1.0;
  1693   double cur_efficiency = (double) freed_bytes / proc_ms;
  1695   bool new_in_marking_window = _in_marking_window;
  1696   bool new_in_marking_window_im = false;
  1697   if (_should_initiate_conc_mark) {
  1698     new_in_marking_window = true;
  1699     new_in_marking_window_im = true;
  1702   if (in_young_gc_mode()) {
  1703     if (_last_full_young_gc) {
  1704       set_full_young_gcs(false);
  1705       _last_full_young_gc = false;
  1708     if ( !_last_young_gc_full ) {
  1709       if ( _should_revert_to_full_young_gcs ||
  1710            _known_garbage_ratio < 0.05 ||
  1711            (adaptive_young_list_length() &&
  1712            (get_gc_eff_factor() * cur_efficiency < predict_young_gc_eff())) ) {
  1713         set_full_young_gcs(true);
  1716     _should_revert_to_full_young_gcs = false;
  1718     if (_last_young_gc_full && !_during_marking)
  1719       _young_gc_eff_seq->add(cur_efficiency);
  1722   _short_lived_surv_rate_group->start_adding_regions();
  1723   // do that for any other surv rate groupsx
  1725   // <NEW PREDICTION>
  1727   if (update_stats) {
  1728     double pause_time_ms = elapsed_ms;
  1730     size_t diff = 0;
  1731     if (_max_pending_cards >= _pending_cards)
  1732       diff = _max_pending_cards - _pending_cards;
  1733     _pending_card_diff_seq->add((double) diff);
  1735     double cost_per_card_ms = 0.0;
  1736     if (_pending_cards > 0) {
  1737       cost_per_card_ms = update_rs_time / (double) _pending_cards;
  1738       _cost_per_card_ms_seq->add(cost_per_card_ms);
  1741     double cost_per_scan_only_region_ms = 0.0;
  1742     if (scan_only_regions_scanned > 0.0) {
  1743       cost_per_scan_only_region_ms =
  1744         scan_only_time / scan_only_regions_scanned;
  1745       if (_in_marking_window_im)
  1746         _cost_per_scan_only_region_ms_during_cm_seq->add(cost_per_scan_only_region_ms);
  1747       else
  1748         _cost_per_scan_only_region_ms_seq->add(cost_per_scan_only_region_ms);
  1751     size_t cards_scanned = _g1->cards_scanned();
  1753     double cost_per_entry_ms = 0.0;
  1754     if (cards_scanned > 10) {
  1755       cost_per_entry_ms = scan_rs_time / (double) cards_scanned;
  1756       if (_last_young_gc_full)
  1757         _cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1758       else
  1759         _partially_young_cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1762     if (_max_rs_lengths > 0) {
  1763       double cards_per_entry_ratio =
  1764         (double) cards_scanned / (double) _max_rs_lengths;
  1765       if (_last_young_gc_full)
  1766         _fully_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1767       else
  1768         _partially_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1771     size_t rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
  1772     if (rs_length_diff >= 0)
  1773       _rs_length_diff_seq->add((double) rs_length_diff);
  1775     size_t copied_bytes = surviving_bytes;
  1776     double cost_per_byte_ms = 0.0;
  1777     if (copied_bytes > 0) {
  1778       cost_per_byte_ms = obj_copy_time / (double) copied_bytes;
  1779       if (_in_marking_window)
  1780         _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
  1781       else
  1782         _cost_per_byte_ms_seq->add(cost_per_byte_ms);
  1785     double all_other_time_ms = pause_time_ms -
  1786       (update_rs_time + scan_only_time + scan_rs_time + obj_copy_time +
  1787        _mark_closure_time_ms + termination_time);
  1789     double young_other_time_ms = 0.0;
  1790     if (_recorded_young_regions > 0) {
  1791       young_other_time_ms =
  1792         _recorded_young_cset_choice_time_ms +
  1793         _recorded_young_free_cset_time_ms;
  1794       _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
  1795                                              (double) _recorded_young_regions);
  1797     double non_young_other_time_ms = 0.0;
  1798     if (_recorded_non_young_regions > 0) {
  1799       non_young_other_time_ms =
  1800         _recorded_non_young_cset_choice_time_ms +
  1801         _recorded_non_young_free_cset_time_ms;
  1803       _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
  1804                                          (double) _recorded_non_young_regions);
  1807     double constant_other_time_ms = all_other_time_ms -
  1808       (young_other_time_ms + non_young_other_time_ms);
  1809     _constant_other_time_ms_seq->add(constant_other_time_ms);
  1811     double survival_ratio = 0.0;
  1812     if (_bytes_in_collection_set_before_gc > 0) {
  1813       survival_ratio = (double) bytes_in_to_space_during_gc() /
  1814         (double) _bytes_in_collection_set_before_gc;
  1817     _pending_cards_seq->add((double) _pending_cards);
  1818     _scanned_cards_seq->add((double) cards_scanned);
  1819     _rs_lengths_seq->add((double) _max_rs_lengths);
  1821     double expensive_region_limit_ms =
  1822       (double) MaxGCPauseMillis - predict_constant_other_time_ms();
  1823     if (expensive_region_limit_ms < 0.0) {
  1824       // this means that the other time was predicted to be longer than
  1825       // than the max pause time
  1826       expensive_region_limit_ms = (double) MaxGCPauseMillis;
  1828     _expensive_region_limit_ms = expensive_region_limit_ms;
  1830     if (PREDICTIONS_VERBOSE) {
  1831       gclog_or_tty->print_cr("");
  1832       gclog_or_tty->print_cr("PREDICTIONS %1.4lf %d "
  1833                     "REGIONS %d %d %d %d "
  1834                     "PENDING_CARDS %d %d "
  1835                     "CARDS_SCANNED %d %d "
  1836                     "RS_LENGTHS %d %d "
  1837                     "SCAN_ONLY_SCAN %1.6lf %1.6lf "
  1838                     "RS_UPDATE %1.6lf %1.6lf RS_SCAN %1.6lf %1.6lf "
  1839                     "SURVIVAL_RATIO %1.6lf %1.6lf "
  1840                     "OBJECT_COPY %1.6lf %1.6lf OTHER_CONSTANT %1.6lf %1.6lf "
  1841                     "OTHER_YOUNG %1.6lf %1.6lf "
  1842                     "OTHER_NON_YOUNG %1.6lf %1.6lf "
  1843                     "VTIME_DIFF %1.6lf TERMINATION %1.6lf "
  1844                     "ELAPSED %1.6lf %1.6lf ",
  1845                     _cur_collection_start_sec,
  1846                     (!_last_young_gc_full) ? 2 :
  1847                     (last_pause_included_initial_mark) ? 1 : 0,
  1848                     _recorded_region_num,
  1849                     _recorded_young_regions,
  1850                     _recorded_scan_only_regions,
  1851                     _recorded_non_young_regions,
  1852                     _predicted_pending_cards, _pending_cards,
  1853                     _predicted_cards_scanned, cards_scanned,
  1854                     _predicted_rs_lengths, _max_rs_lengths,
  1855                     _predicted_scan_only_scan_time_ms, scan_only_time,
  1856                     _predicted_rs_update_time_ms, update_rs_time,
  1857                     _predicted_rs_scan_time_ms, scan_rs_time,
  1858                     _predicted_survival_ratio, survival_ratio,
  1859                     _predicted_object_copy_time_ms, obj_copy_time,
  1860                     _predicted_constant_other_time_ms, constant_other_time_ms,
  1861                     _predicted_young_other_time_ms, young_other_time_ms,
  1862                     _predicted_non_young_other_time_ms,
  1863                     non_young_other_time_ms,
  1864                     _vtime_diff_ms, termination_time,
  1865                     _predicted_pause_time_ms, elapsed_ms);
  1868     if (G1PolicyVerbose > 0) {
  1869       gclog_or_tty->print_cr("Pause Time, predicted: %1.4lfms (predicted %s), actual: %1.4lfms",
  1870                     _predicted_pause_time_ms,
  1871                     (_within_target) ? "within" : "outside",
  1872                     elapsed_ms);
  1877   _in_marking_window = new_in_marking_window;
  1878   _in_marking_window_im = new_in_marking_window_im;
  1879   _free_regions_at_end_of_collection = _g1->free_regions();
  1880   _scan_only_regions_at_end_of_collection = _g1->young_list_length();
  1881   calculate_young_list_min_length();
  1882   calculate_young_list_target_config();
  1884   // </NEW PREDICTION>
  1886   _target_pause_time_ms = -1.0;
  1889 // <NEW PREDICTION>
  1891 double
  1892 G1CollectorPolicy::
  1893 predict_young_collection_elapsed_time_ms(size_t adjustment) {
  1894   guarantee( adjustment == 0 || adjustment == 1, "invariant" );
  1896   G1CollectedHeap* g1h = G1CollectedHeap::heap();
  1897   size_t young_num = g1h->young_list_length();
  1898   if (young_num == 0)
  1899     return 0.0;
  1901   young_num += adjustment;
  1902   size_t pending_cards = predict_pending_cards();
  1903   size_t rs_lengths = g1h->young_list_sampled_rs_lengths() +
  1904                       predict_rs_length_diff();
  1905   size_t card_num;
  1906   if (full_young_gcs())
  1907     card_num = predict_young_card_num(rs_lengths);
  1908   else
  1909     card_num = predict_non_young_card_num(rs_lengths);
  1910   size_t young_byte_size = young_num * HeapRegion::GrainBytes;
  1911   double accum_yg_surv_rate =
  1912     _short_lived_surv_rate_group->accum_surv_rate(adjustment);
  1914   size_t bytes_to_copy =
  1915     (size_t) (accum_yg_surv_rate * (double) HeapRegion::GrainBytes);
  1917   return
  1918     predict_rs_update_time_ms(pending_cards) +
  1919     predict_rs_scan_time_ms(card_num) +
  1920     predict_object_copy_time_ms(bytes_to_copy) +
  1921     predict_young_other_time_ms(young_num) +
  1922     predict_constant_other_time_ms();
  1925 double
  1926 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
  1927   size_t rs_length = predict_rs_length_diff();
  1928   size_t card_num;
  1929   if (full_young_gcs())
  1930     card_num = predict_young_card_num(rs_length);
  1931   else
  1932     card_num = predict_non_young_card_num(rs_length);
  1933   return predict_base_elapsed_time_ms(pending_cards, card_num);
  1936 double
  1937 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
  1938                                                 size_t scanned_cards) {
  1939   return
  1940     predict_rs_update_time_ms(pending_cards) +
  1941     predict_rs_scan_time_ms(scanned_cards) +
  1942     predict_constant_other_time_ms();
  1945 double
  1946 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
  1947                                                   bool young) {
  1948   size_t rs_length = hr->rem_set()->occupied();
  1949   size_t card_num;
  1950   if (full_young_gcs())
  1951     card_num = predict_young_card_num(rs_length);
  1952   else
  1953     card_num = predict_non_young_card_num(rs_length);
  1954   size_t bytes_to_copy = predict_bytes_to_copy(hr);
  1956   double region_elapsed_time_ms =
  1957     predict_rs_scan_time_ms(card_num) +
  1958     predict_object_copy_time_ms(bytes_to_copy);
  1960   if (young)
  1961     region_elapsed_time_ms += predict_young_other_time_ms(1);
  1962   else
  1963     region_elapsed_time_ms += predict_non_young_other_time_ms(1);
  1965   return region_elapsed_time_ms;
  1968 size_t
  1969 G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
  1970   size_t bytes_to_copy;
  1971   if (hr->is_marked())
  1972     bytes_to_copy = hr->max_live_bytes();
  1973   else {
  1974     guarantee( hr->is_young() && hr->age_in_surv_rate_group() != -1,
  1975                "invariant" );
  1976     int age = hr->age_in_surv_rate_group();
  1977     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
  1978     bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
  1981   return bytes_to_copy;
  1984 void
  1985 G1CollectorPolicy::start_recording_regions() {
  1986   _recorded_rs_lengths            = 0;
  1987   _recorded_scan_only_regions     = 0;
  1988   _recorded_young_regions         = 0;
  1989   _recorded_non_young_regions     = 0;
  1991 #if PREDICTIONS_VERBOSE
  1992   _predicted_rs_lengths           = 0;
  1993   _predicted_cards_scanned        = 0;
  1995   _recorded_marked_bytes          = 0;
  1996   _recorded_young_bytes           = 0;
  1997   _predicted_bytes_to_copy        = 0;
  1998 #endif // PREDICTIONS_VERBOSE
  2001 void
  2002 G1CollectorPolicy::record_cset_region(HeapRegion* hr, bool young) {
  2003   if (young) {
  2004     ++_recorded_young_regions;
  2005   } else {
  2006     ++_recorded_non_young_regions;
  2008 #if PREDICTIONS_VERBOSE
  2009   if (young) {
  2010     _recorded_young_bytes += hr->used();
  2011   } else {
  2012     _recorded_marked_bytes += hr->max_live_bytes();
  2014   _predicted_bytes_to_copy += predict_bytes_to_copy(hr);
  2015 #endif // PREDICTIONS_VERBOSE
  2017   size_t rs_length = hr->rem_set()->occupied();
  2018   _recorded_rs_lengths += rs_length;
  2021 void
  2022 G1CollectorPolicy::record_scan_only_regions(size_t scan_only_length) {
  2023   _recorded_scan_only_regions = scan_only_length;
  2026 void
  2027 G1CollectorPolicy::end_recording_regions() {
  2028 #if PREDICTIONS_VERBOSE
  2029   _predicted_pending_cards = predict_pending_cards();
  2030   _predicted_rs_lengths = _recorded_rs_lengths + predict_rs_length_diff();
  2031   if (full_young_gcs())
  2032     _predicted_cards_scanned += predict_young_card_num(_predicted_rs_lengths);
  2033   else
  2034     _predicted_cards_scanned +=
  2035       predict_non_young_card_num(_predicted_rs_lengths);
  2036   _recorded_region_num = _recorded_young_regions + _recorded_non_young_regions;
  2038   _predicted_scan_only_scan_time_ms =
  2039     predict_scan_only_time_ms(_recorded_scan_only_regions);
  2040   _predicted_rs_update_time_ms =
  2041     predict_rs_update_time_ms(_g1->pending_card_num());
  2042   _predicted_rs_scan_time_ms =
  2043     predict_rs_scan_time_ms(_predicted_cards_scanned);
  2044   _predicted_object_copy_time_ms =
  2045     predict_object_copy_time_ms(_predicted_bytes_to_copy);
  2046   _predicted_constant_other_time_ms =
  2047     predict_constant_other_time_ms();
  2048   _predicted_young_other_time_ms =
  2049     predict_young_other_time_ms(_recorded_young_regions);
  2050   _predicted_non_young_other_time_ms =
  2051     predict_non_young_other_time_ms(_recorded_non_young_regions);
  2053   _predicted_pause_time_ms =
  2054     _predicted_scan_only_scan_time_ms +
  2055     _predicted_rs_update_time_ms +
  2056     _predicted_rs_scan_time_ms +
  2057     _predicted_object_copy_time_ms +
  2058     _predicted_constant_other_time_ms +
  2059     _predicted_young_other_time_ms +
  2060     _predicted_non_young_other_time_ms;
  2061 #endif // PREDICTIONS_VERBOSE
  2064 void G1CollectorPolicy::check_if_region_is_too_expensive(double
  2065                                                            predicted_time_ms) {
  2066   // I don't think we need to do this when in young GC mode since
  2067   // marking will be initiated next time we hit the soft limit anyway...
  2068   if (predicted_time_ms > _expensive_region_limit_ms) {
  2069     if (!in_young_gc_mode()) {
  2070         set_full_young_gcs(true);
  2071       _should_initiate_conc_mark = true;
  2072     } else
  2073       // no point in doing another partial one
  2074       _should_revert_to_full_young_gcs = true;
  2078 // </NEW PREDICTION>
  2081 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
  2082                                                double elapsed_ms) {
  2083   _recent_gc_times_ms->add(elapsed_ms);
  2084   _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
  2085   _prev_collection_pause_end_ms = end_time_sec * 1000.0;
  2088 double G1CollectorPolicy::recent_avg_time_for_pauses_ms() {
  2089   if (_recent_pause_times_ms->num() == 0) return (double) MaxGCPauseMillis;
  2090   else return _recent_pause_times_ms->avg();
  2093 double G1CollectorPolicy::recent_avg_time_for_CH_strong_ms() {
  2094   if (_recent_CH_strong_roots_times_ms->num() == 0)
  2095     return (double)MaxGCPauseMillis/3.0;
  2096   else return _recent_CH_strong_roots_times_ms->avg();
  2099 double G1CollectorPolicy::recent_avg_time_for_G1_strong_ms() {
  2100   if (_recent_G1_strong_roots_times_ms->num() == 0)
  2101     return (double)MaxGCPauseMillis/3.0;
  2102   else return _recent_G1_strong_roots_times_ms->avg();
  2105 double G1CollectorPolicy::recent_avg_time_for_evac_ms() {
  2106   if (_recent_evac_times_ms->num() == 0) return (double)MaxGCPauseMillis/3.0;
  2107   else return _recent_evac_times_ms->avg();
  2110 int G1CollectorPolicy::number_of_recent_gcs() {
  2111   assert(_recent_CH_strong_roots_times_ms->num() ==
  2112          _recent_G1_strong_roots_times_ms->num(), "Sequence out of sync");
  2113   assert(_recent_G1_strong_roots_times_ms->num() ==
  2114          _recent_evac_times_ms->num(), "Sequence out of sync");
  2115   assert(_recent_evac_times_ms->num() ==
  2116          _recent_pause_times_ms->num(), "Sequence out of sync");
  2117   assert(_recent_pause_times_ms->num() ==
  2118          _recent_CS_bytes_used_before->num(), "Sequence out of sync");
  2119   assert(_recent_CS_bytes_used_before->num() ==
  2120          _recent_CS_bytes_surviving->num(), "Sequence out of sync");
  2121   return _recent_pause_times_ms->num();
  2124 double G1CollectorPolicy::recent_avg_survival_fraction() {
  2125   return recent_avg_survival_fraction_work(_recent_CS_bytes_surviving,
  2126                                            _recent_CS_bytes_used_before);
  2129 double G1CollectorPolicy::last_survival_fraction() {
  2130   return last_survival_fraction_work(_recent_CS_bytes_surviving,
  2131                                      _recent_CS_bytes_used_before);
  2134 double
  2135 G1CollectorPolicy::recent_avg_survival_fraction_work(TruncatedSeq* surviving,
  2136                                                      TruncatedSeq* before) {
  2137   assert(surviving->num() == before->num(), "Sequence out of sync");
  2138   if (before->sum() > 0.0) {
  2139       double recent_survival_rate = surviving->sum() / before->sum();
  2140       // We exempt parallel collection from this check because Alloc Buffer
  2141       // fragmentation can produce negative collections.
  2142       // Further, we're now always doing parallel collection.  But I'm still
  2143       // leaving this here as a placeholder for a more precise assertion later.
  2144       // (DLD, 10/05.)
  2145       assert((true || ParallelGCThreads > 0) ||
  2146              _g1->evacuation_failed() ||
  2147              recent_survival_rate <= 1.0, "Or bad frac");
  2148       return recent_survival_rate;
  2149   } else {
  2150     return 1.0; // Be conservative.
  2154 double
  2155 G1CollectorPolicy::last_survival_fraction_work(TruncatedSeq* surviving,
  2156                                                TruncatedSeq* before) {
  2157   assert(surviving->num() == before->num(), "Sequence out of sync");
  2158   if (surviving->num() > 0 && before->last() > 0.0) {
  2159     double last_survival_rate = surviving->last() / before->last();
  2160     // We exempt parallel collection from this check because Alloc Buffer
  2161     // fragmentation can produce negative collections.
  2162     // Further, we're now always doing parallel collection.  But I'm still
  2163     // leaving this here as a placeholder for a more precise assertion later.
  2164     // (DLD, 10/05.)
  2165     assert((true || ParallelGCThreads > 0) ||
  2166            last_survival_rate <= 1.0, "Or bad frac");
  2167     return last_survival_rate;
  2168   } else {
  2169     return 1.0;
  2173 static const int survival_min_obs = 5;
  2174 static double survival_min_obs_limits[] = { 0.9, 0.7, 0.5, 0.3, 0.1 };
  2175 static const double min_survival_rate = 0.1;
  2177 double
  2178 G1CollectorPolicy::conservative_avg_survival_fraction_work(double avg,
  2179                                                            double latest) {
  2180   double res = avg;
  2181   if (number_of_recent_gcs() < survival_min_obs) {
  2182     res = MAX2(res, survival_min_obs_limits[number_of_recent_gcs()]);
  2184   res = MAX2(res, latest);
  2185   res = MAX2(res, min_survival_rate);
  2186   // In the parallel case, LAB fragmentation can produce "negative
  2187   // collections"; so can evac failure.  Cap at 1.0
  2188   res = MIN2(res, 1.0);
  2189   return res;
  2192 size_t G1CollectorPolicy::expansion_amount() {
  2193   if ((int)(recent_avg_pause_time_ratio() * 100.0) > G1GCPercent) {
  2194     // We will double the existing space, or take
  2195     // G1ExpandByPercentOfAvailable % of the available expansion
  2196     // space, whichever is smaller, bounded below by a minimum
  2197     // expansion (unless that's all that's left.)
  2198     const size_t min_expand_bytes = 1*M;
  2199     size_t reserved_bytes = _g1->g1_reserved_obj_bytes();
  2200     size_t committed_bytes = _g1->capacity();
  2201     size_t uncommitted_bytes = reserved_bytes - committed_bytes;
  2202     size_t expand_bytes;
  2203     size_t expand_bytes_via_pct =
  2204       uncommitted_bytes * G1ExpandByPercentOfAvailable / 100;
  2205     expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
  2206     expand_bytes = MAX2(expand_bytes, min_expand_bytes);
  2207     expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
  2208     if (G1PolicyVerbose > 1) {
  2209       gclog_or_tty->print("Decided to expand: ratio = %5.2f, "
  2210                  "committed = %d%s, uncommited = %d%s, via pct = %d%s.\n"
  2211                  "                   Answer = %d.\n",
  2212                  recent_avg_pause_time_ratio(),
  2213                  byte_size_in_proper_unit(committed_bytes),
  2214                  proper_unit_for_byte_size(committed_bytes),
  2215                  byte_size_in_proper_unit(uncommitted_bytes),
  2216                  proper_unit_for_byte_size(uncommitted_bytes),
  2217                  byte_size_in_proper_unit(expand_bytes_via_pct),
  2218                  proper_unit_for_byte_size(expand_bytes_via_pct),
  2219                  byte_size_in_proper_unit(expand_bytes),
  2220                  proper_unit_for_byte_size(expand_bytes));
  2222     return expand_bytes;
  2223   } else {
  2224     return 0;
  2228 void G1CollectorPolicy::note_start_of_mark_thread() {
  2229   _mark_thread_startup_sec = os::elapsedTime();
  2232 class CountCSClosure: public HeapRegionClosure {
  2233   G1CollectorPolicy* _g1_policy;
  2234 public:
  2235   CountCSClosure(G1CollectorPolicy* g1_policy) :
  2236     _g1_policy(g1_policy) {}
  2237   bool doHeapRegion(HeapRegion* r) {
  2238     _g1_policy->_bytes_in_collection_set_before_gc += r->used();
  2239     return false;
  2241 };
  2243 void G1CollectorPolicy::count_CS_bytes_used() {
  2244   CountCSClosure cs_closure(this);
  2245   _g1->collection_set_iterate(&cs_closure);
  2248 static void print_indent(int level) {
  2249   for (int j = 0; j < level+1; ++j)
  2250     gclog_or_tty->print("   ");
  2253 void G1CollectorPolicy::print_summary (int level,
  2254                                        const char* str,
  2255                                        NumberSeq* seq) const {
  2256   double sum = seq->sum();
  2257   print_indent(level);
  2258   gclog_or_tty->print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
  2259                 str, sum / 1000.0, seq->avg());
  2262 void G1CollectorPolicy::print_summary_sd (int level,
  2263                                           const char* str,
  2264                                           NumberSeq* seq) const {
  2265   print_summary(level, str, seq);
  2266   print_indent(level + 5);
  2267   gclog_or_tty->print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
  2268                 seq->num(), seq->sd(), seq->maximum());
  2271 void G1CollectorPolicy::check_other_times(int level,
  2272                                         NumberSeq* other_times_ms,
  2273                                         NumberSeq* calc_other_times_ms) const {
  2274   bool should_print = false;
  2276   double max_sum = MAX2(fabs(other_times_ms->sum()),
  2277                         fabs(calc_other_times_ms->sum()));
  2278   double min_sum = MIN2(fabs(other_times_ms->sum()),
  2279                         fabs(calc_other_times_ms->sum()));
  2280   double sum_ratio = max_sum / min_sum;
  2281   if (sum_ratio > 1.1) {
  2282     should_print = true;
  2283     print_indent(level + 1);
  2284     gclog_or_tty->print_cr("## CALCULATED OTHER SUM DOESN'T MATCH RECORDED ###");
  2287   double max_avg = MAX2(fabs(other_times_ms->avg()),
  2288                         fabs(calc_other_times_ms->avg()));
  2289   double min_avg = MIN2(fabs(other_times_ms->avg()),
  2290                         fabs(calc_other_times_ms->avg()));
  2291   double avg_ratio = max_avg / min_avg;
  2292   if (avg_ratio > 1.1) {
  2293     should_print = true;
  2294     print_indent(level + 1);
  2295     gclog_or_tty->print_cr("## CALCULATED OTHER AVG DOESN'T MATCH RECORDED ###");
  2298   if (other_times_ms->sum() < -0.01) {
  2299     print_indent(level + 1);
  2300     gclog_or_tty->print_cr("## RECORDED OTHER SUM IS NEGATIVE ###");
  2303   if (other_times_ms->avg() < -0.01) {
  2304     print_indent(level + 1);
  2305     gclog_or_tty->print_cr("## RECORDED OTHER AVG IS NEGATIVE ###");
  2308   if (calc_other_times_ms->sum() < -0.01) {
  2309     should_print = true;
  2310     print_indent(level + 1);
  2311     gclog_or_tty->print_cr("## CALCULATED OTHER SUM IS NEGATIVE ###");
  2314   if (calc_other_times_ms->avg() < -0.01) {
  2315     should_print = true;
  2316     print_indent(level + 1);
  2317     gclog_or_tty->print_cr("## CALCULATED OTHER AVG IS NEGATIVE ###");
  2320   if (should_print)
  2321     print_summary(level, "Other(Calc)", calc_other_times_ms);
  2324 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
  2325   bool parallel = ParallelGCThreads > 0;
  2326   MainBodySummary*    body_summary = summary->main_body_summary();
  2327   if (summary->get_total_seq()->num() > 0) {
  2328     print_summary_sd(0, "Evacuation Pauses", summary->get_total_seq());
  2329     if (body_summary != NULL) {
  2330       print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
  2331       if (parallel) {
  2332         print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
  2333         print_summary(2, "Update RS", body_summary->get_update_rs_seq());
  2334         print_summary(2, "Ext Root Scanning",
  2335                       body_summary->get_ext_root_scan_seq());
  2336         print_summary(2, "Mark Stack Scanning",
  2337                       body_summary->get_mark_stack_scan_seq());
  2338         print_summary(2, "Scan-Only Scanning",
  2339                       body_summary->get_scan_only_seq());
  2340         print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
  2341         print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
  2342         print_summary(2, "Termination", body_summary->get_termination_seq());
  2343         print_summary(2, "Other", body_summary->get_parallel_other_seq());
  2345           NumberSeq* other_parts[] = {
  2346             body_summary->get_update_rs_seq(),
  2347             body_summary->get_ext_root_scan_seq(),
  2348             body_summary->get_mark_stack_scan_seq(),
  2349             body_summary->get_scan_only_seq(),
  2350             body_summary->get_scan_rs_seq(),
  2351             body_summary->get_obj_copy_seq(),
  2352             body_summary->get_termination_seq()
  2353           };
  2354           NumberSeq calc_other_times_ms(body_summary->get_parallel_seq(),
  2355                                         7, other_parts);
  2356           check_other_times(2, body_summary->get_parallel_other_seq(),
  2357                             &calc_other_times_ms);
  2359         print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
  2360         print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
  2361       } else {
  2362         print_summary(1, "Update RS", body_summary->get_update_rs_seq());
  2363         print_summary(1, "Ext Root Scanning",
  2364                       body_summary->get_ext_root_scan_seq());
  2365         print_summary(1, "Mark Stack Scanning",
  2366                       body_summary->get_mark_stack_scan_seq());
  2367         print_summary(1, "Scan-Only Scanning",
  2368                       body_summary->get_scan_only_seq());
  2369         print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
  2370         print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
  2373     print_summary(1, "Other", summary->get_other_seq());
  2375       NumberSeq calc_other_times_ms;
  2376       if (body_summary != NULL) {
  2377         // not abandoned
  2378         if (parallel) {
  2379           // parallel
  2380           NumberSeq* other_parts[] = {
  2381             body_summary->get_satb_drain_seq(),
  2382             body_summary->get_parallel_seq(),
  2383             body_summary->get_clear_ct_seq()
  2384           };
  2385           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2386                                           3, other_parts);
  2387         } else {
  2388           // serial
  2389           NumberSeq* other_parts[] = {
  2390             body_summary->get_satb_drain_seq(),
  2391             body_summary->get_update_rs_seq(),
  2392             body_summary->get_ext_root_scan_seq(),
  2393             body_summary->get_mark_stack_scan_seq(),
  2394             body_summary->get_scan_only_seq(),
  2395             body_summary->get_scan_rs_seq(),
  2396             body_summary->get_obj_copy_seq()
  2397           };
  2398           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2399                                           7, other_parts);
  2401       } else {
  2402         // abandoned
  2403         calc_other_times_ms = NumberSeq();
  2405       check_other_times(1,  summary->get_other_seq(), &calc_other_times_ms);
  2407   } else {
  2408     print_indent(0);
  2409     gclog_or_tty->print_cr("none");
  2411   gclog_or_tty->print_cr("");
  2414 void
  2415 G1CollectorPolicy::print_abandoned_summary(PauseSummary* summary) const {
  2416   bool printed = false;
  2417   if (summary->get_total_seq()->num() > 0) {
  2418     printed = true;
  2419     print_summary(summary);
  2421   if (!printed) {
  2422     print_indent(0);
  2423     gclog_or_tty->print_cr("none");
  2424     gclog_or_tty->print_cr("");
  2428 void G1CollectorPolicy::print_tracing_info() const {
  2429   if (TraceGen0Time) {
  2430     gclog_or_tty->print_cr("ALL PAUSES");
  2431     print_summary_sd(0, "Total", _all_pause_times_ms);
  2432     gclog_or_tty->print_cr("");
  2433     gclog_or_tty->print_cr("");
  2434     gclog_or_tty->print_cr("   Full Young GC Pauses:    %8d", _full_young_pause_num);
  2435     gclog_or_tty->print_cr("   Partial Young GC Pauses: %8d", _partial_young_pause_num);
  2436     gclog_or_tty->print_cr("");
  2438     gclog_or_tty->print_cr("EVACUATION PAUSES");
  2439     print_summary(_summary);
  2441     gclog_or_tty->print_cr("ABANDONED PAUSES");
  2442     print_abandoned_summary(_abandoned_summary);
  2444     gclog_or_tty->print_cr("MISC");
  2445     print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
  2446     print_summary_sd(0, "Yields", _all_yield_times_ms);
  2447     for (int i = 0; i < _aux_num; ++i) {
  2448       if (_all_aux_times_ms[i].num() > 0) {
  2449         char buffer[96];
  2450         sprintf(buffer, "Aux%d", i);
  2451         print_summary_sd(0, buffer, &_all_aux_times_ms[i]);
  2455     size_t all_region_num = _region_num_young + _region_num_tenured;
  2456     gclog_or_tty->print_cr("   New Regions %8d, Young %8d (%6.2lf%%), "
  2457                "Tenured %8d (%6.2lf%%)",
  2458                all_region_num,
  2459                _region_num_young,
  2460                (double) _region_num_young / (double) all_region_num * 100.0,
  2461                _region_num_tenured,
  2462                (double) _region_num_tenured / (double) all_region_num * 100.0);
  2464   if (TraceGen1Time) {
  2465     if (_all_full_gc_times_ms->num() > 0) {
  2466       gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
  2467                  _all_full_gc_times_ms->num(),
  2468                  _all_full_gc_times_ms->sum() / 1000.0);
  2469       gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times_ms->avg());
  2470       gclog_or_tty->print_cr("                     [std. dev = %8.2f ms, max = %8.2f ms]",
  2471                     _all_full_gc_times_ms->sd(),
  2472                     _all_full_gc_times_ms->maximum());
  2477 void G1CollectorPolicy::print_yg_surv_rate_info() const {
  2478 #ifndef PRODUCT
  2479   _short_lived_surv_rate_group->print_surv_rate_summary();
  2480   // add this call for any other surv rate groups
  2481 #endif // PRODUCT
  2484 bool
  2485 G1CollectorPolicy::should_add_next_region_to_young_list() {
  2486   assert(in_young_gc_mode(), "should be in young GC mode");
  2487   bool ret;
  2488   size_t young_list_length = _g1->young_list_length();
  2489   size_t young_list_max_length = _young_list_target_length;
  2490   if (G1FixedEdenSize) {
  2491     young_list_max_length -= _max_survivor_regions;
  2493   if (young_list_length < young_list_max_length) {
  2494     ret = true;
  2495     ++_region_num_young;
  2496   } else {
  2497     ret = false;
  2498     ++_region_num_tenured;
  2501   return ret;
  2504 #ifndef PRODUCT
  2505 // for debugging, bit of a hack...
  2506 static char*
  2507 region_num_to_mbs(int length) {
  2508   static char buffer[64];
  2509   double bytes = (double) (length * HeapRegion::GrainBytes);
  2510   double mbs = bytes / (double) (1024 * 1024);
  2511   sprintf(buffer, "%7.2lfMB", mbs);
  2512   return buffer;
  2514 #endif // PRODUCT
  2516 void
  2517 G1CollectorPolicy::checkpoint_conc_overhead() {
  2518   double conc_overhead = 0.0;
  2519   if (G1AccountConcurrentOverhead)
  2520     conc_overhead = COTracker::totalPredConcOverhead();
  2521   _mmu_tracker->update_conc_overhead(conc_overhead);
  2522 #if 0
  2523   gclog_or_tty->print(" CO %1.4lf TARGET %1.4lf",
  2524              conc_overhead, _mmu_tracker->max_gc_time());
  2525 #endif
  2529 size_t G1CollectorPolicy::max_regions(int purpose) {
  2530   switch (purpose) {
  2531     case GCAllocForSurvived:
  2532       return _max_survivor_regions;
  2533     case GCAllocForTenured:
  2534       return REGIONS_UNLIMITED;
  2535     default:
  2536       ShouldNotReachHere();
  2537       return REGIONS_UNLIMITED;
  2538   };
  2541 // Calculates survivor space parameters.
  2542 void G1CollectorPolicy::calculate_survivors_policy()
  2544   if (!G1UseSurvivorSpaces) {
  2545     return;
  2547   if (G1FixedSurvivorSpaceSize == 0) {
  2548     _max_survivor_regions = _young_list_target_length / SurvivorRatio;
  2549   } else {
  2550     _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
  2553   if (G1FixedTenuringThreshold) {
  2554     _tenuring_threshold = MaxTenuringThreshold;
  2555   } else {
  2556     _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
  2557         HeapRegion::GrainWords * _max_survivor_regions);
  2561 bool
  2562 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
  2563                                                                word_size) {
  2564   assert(_g1->regions_accounted_for(), "Region leakage!");
  2565   // Initiate a pause when we reach the steady-state "used" target.
  2566   size_t used_hard = (_g1->capacity() / 100) * G1SteadyStateUsed;
  2567   size_t used_soft =
  2568    MAX2((_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta),
  2569         used_hard/2);
  2570   size_t used = _g1->used();
  2572   double max_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
  2574   size_t young_list_length = _g1->young_list_length();
  2575   size_t young_list_max_length = _young_list_target_length;
  2576   if (G1FixedEdenSize) {
  2577     young_list_max_length -= _max_survivor_regions;
  2579   bool reached_target_length = young_list_length >= young_list_max_length;
  2581   if (in_young_gc_mode()) {
  2582     if (reached_target_length) {
  2583       assert( young_list_length > 0 && _g1->young_list_length() > 0,
  2584               "invariant" );
  2585       _target_pause_time_ms = max_pause_time_ms;
  2586       return true;
  2588   } else {
  2589     guarantee( false, "should not reach here" );
  2592   return false;
  2595 #ifndef PRODUCT
  2596 class HRSortIndexIsOKClosure: public HeapRegionClosure {
  2597   CollectionSetChooser* _chooser;
  2598 public:
  2599   HRSortIndexIsOKClosure(CollectionSetChooser* chooser) :
  2600     _chooser(chooser) {}
  2602   bool doHeapRegion(HeapRegion* r) {
  2603     if (!r->continuesHumongous()) {
  2604       assert(_chooser->regionProperlyOrdered(r), "Ought to be.");
  2606     return false;
  2608 };
  2610 bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() {
  2611   HRSortIndexIsOKClosure cl(_collectionSetChooser);
  2612   _g1->heap_region_iterate(&cl);
  2613   return true;
  2615 #endif
  2617 void
  2618 G1CollectorPolicy_BestRegionsFirst::
  2619 record_collection_pause_start(double start_time_sec, size_t start_used) {
  2620   G1CollectorPolicy::record_collection_pause_start(start_time_sec, start_used);
  2623 class NextNonCSElemFinder: public HeapRegionClosure {
  2624   HeapRegion* _res;
  2625 public:
  2626   NextNonCSElemFinder(): _res(NULL) {}
  2627   bool doHeapRegion(HeapRegion* r) {
  2628     if (!r->in_collection_set()) {
  2629       _res = r;
  2630       return true;
  2631     } else {
  2632       return false;
  2635   HeapRegion* res() { return _res; }
  2636 };
  2638 class KnownGarbageClosure: public HeapRegionClosure {
  2639   CollectionSetChooser* _hrSorted;
  2641 public:
  2642   KnownGarbageClosure(CollectionSetChooser* hrSorted) :
  2643     _hrSorted(hrSorted)
  2644   {}
  2646   bool doHeapRegion(HeapRegion* r) {
  2647     // We only include humongous regions in collection
  2648     // sets when concurrent mark shows that their contained object is
  2649     // unreachable.
  2651     // Do we have any marking information for this region?
  2652     if (r->is_marked()) {
  2653       // We don't include humongous regions in collection
  2654       // sets because we collect them immediately at the end of a marking
  2655       // cycle.  We also don't include young regions because we *must*
  2656       // include them in the next collection pause.
  2657       if (!r->isHumongous() && !r->is_young()) {
  2658         _hrSorted->addMarkedHeapRegion(r);
  2661     return false;
  2663 };
  2665 class ParKnownGarbageHRClosure: public HeapRegionClosure {
  2666   CollectionSetChooser* _hrSorted;
  2667   jint _marked_regions_added;
  2668   jint _chunk_size;
  2669   jint _cur_chunk_idx;
  2670   jint _cur_chunk_end; // Cur chunk [_cur_chunk_idx, _cur_chunk_end)
  2671   int _worker;
  2672   int _invokes;
  2674   void get_new_chunk() {
  2675     _cur_chunk_idx = _hrSorted->getParMarkedHeapRegionChunk(_chunk_size);
  2676     _cur_chunk_end = _cur_chunk_idx + _chunk_size;
  2678   void add_region(HeapRegion* r) {
  2679     if (_cur_chunk_idx == _cur_chunk_end) {
  2680       get_new_chunk();
  2682     assert(_cur_chunk_idx < _cur_chunk_end, "postcondition");
  2683     _hrSorted->setMarkedHeapRegion(_cur_chunk_idx, r);
  2684     _marked_regions_added++;
  2685     _cur_chunk_idx++;
  2688 public:
  2689   ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
  2690                            jint chunk_size,
  2691                            int worker) :
  2692     _hrSorted(hrSorted), _chunk_size(chunk_size), _worker(worker),
  2693     _marked_regions_added(0), _cur_chunk_idx(0), _cur_chunk_end(0),
  2694     _invokes(0)
  2695   {}
  2697   bool doHeapRegion(HeapRegion* r) {
  2698     // We only include humongous regions in collection
  2699     // sets when concurrent mark shows that their contained object is
  2700     // unreachable.
  2701     _invokes++;
  2703     // Do we have any marking information for this region?
  2704     if (r->is_marked()) {
  2705       // We don't include humongous regions in collection
  2706       // sets because we collect them immediately at the end of a marking
  2707       // cycle.
  2708       // We also do not include young regions in collection sets
  2709       if (!r->isHumongous() && !r->is_young()) {
  2710         add_region(r);
  2713     return false;
  2715   jint marked_regions_added() { return _marked_regions_added; }
  2716   int invokes() { return _invokes; }
  2717 };
  2719 class ParKnownGarbageTask: public AbstractGangTask {
  2720   CollectionSetChooser* _hrSorted;
  2721   jint _chunk_size;
  2722   G1CollectedHeap* _g1;
  2723 public:
  2724   ParKnownGarbageTask(CollectionSetChooser* hrSorted, jint chunk_size) :
  2725     AbstractGangTask("ParKnownGarbageTask"),
  2726     _hrSorted(hrSorted), _chunk_size(chunk_size),
  2727     _g1(G1CollectedHeap::heap())
  2728   {}
  2730   void work(int i) {
  2731     ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size, i);
  2732     // Back to zero for the claim value.
  2733     _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, i,
  2734                                          HeapRegion::InitialClaimValue);
  2735     jint regions_added = parKnownGarbageCl.marked_regions_added();
  2736     _hrSorted->incNumMarkedHeapRegions(regions_added);
  2737     if (G1PrintParCleanupStats) {
  2738       gclog_or_tty->print("     Thread %d called %d times, added %d regions to list.\n",
  2739                  i, parKnownGarbageCl.invokes(), regions_added);
  2742 };
  2744 void
  2745 G1CollectorPolicy_BestRegionsFirst::
  2746 record_concurrent_mark_cleanup_end(size_t freed_bytes,
  2747                                    size_t max_live_bytes) {
  2748   double start;
  2749   if (G1PrintParCleanupStats) start = os::elapsedTime();
  2750   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  2752   _collectionSetChooser->clearMarkedHeapRegions();
  2753   double clear_marked_end;
  2754   if (G1PrintParCleanupStats) {
  2755     clear_marked_end = os::elapsedTime();
  2756     gclog_or_tty->print_cr("  clear marked regions + work1: %8.3f ms.",
  2757                   (clear_marked_end - start)*1000.0);
  2759   if (ParallelGCThreads > 0) {
  2760     const size_t OverpartitionFactor = 4;
  2761     const size_t MinChunkSize = 8;
  2762     const size_t ChunkSize =
  2763       MAX2(_g1->n_regions() / (ParallelGCThreads * OverpartitionFactor),
  2764            MinChunkSize);
  2765     _collectionSetChooser->prepareForAddMarkedHeapRegionsPar(_g1->n_regions(),
  2766                                                              ChunkSize);
  2767     ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
  2768                                             (int) ChunkSize);
  2769     _g1->workers()->run_task(&parKnownGarbageTask);
  2771     assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  2772            "sanity check");
  2773   } else {
  2774     KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
  2775     _g1->heap_region_iterate(&knownGarbagecl);
  2777   double known_garbage_end;
  2778   if (G1PrintParCleanupStats) {
  2779     known_garbage_end = os::elapsedTime();
  2780     gclog_or_tty->print_cr("  compute known garbage: %8.3f ms.",
  2781                   (known_garbage_end - clear_marked_end)*1000.0);
  2783   _collectionSetChooser->sortMarkedHeapRegions();
  2784   double sort_end;
  2785   if (G1PrintParCleanupStats) {
  2786     sort_end = os::elapsedTime();
  2787     gclog_or_tty->print_cr("  sorting: %8.3f ms.",
  2788                   (sort_end - known_garbage_end)*1000.0);
  2791   record_concurrent_mark_cleanup_end_work2();
  2792   double work2_end;
  2793   if (G1PrintParCleanupStats) {
  2794     work2_end = os::elapsedTime();
  2795     gclog_or_tty->print_cr("  work2: %8.3f ms.",
  2796                   (work2_end - sort_end)*1000.0);
  2800 // Add the heap region to the collection set and return the conservative
  2801 // estimate of the number of live bytes.
  2802 void G1CollectorPolicy::
  2803 add_to_collection_set(HeapRegion* hr) {
  2804   if (G1PrintRegions) {
  2805     gclog_or_tty->print_cr("added region to cset %d:["PTR_FORMAT", "PTR_FORMAT"], "
  2806                   "top "PTR_FORMAT", young %s",
  2807                   hr->hrs_index(), hr->bottom(), hr->end(),
  2808                   hr->top(), (hr->is_young()) ? "YES" : "NO");
  2811   if (_g1->mark_in_progress())
  2812     _g1->concurrent_mark()->registerCSetRegion(hr);
  2814   assert(!hr->in_collection_set(),
  2815               "should not already be in the CSet");
  2816   hr->set_in_collection_set(true);
  2817   hr->set_next_in_collection_set(_collection_set);
  2818   _collection_set = hr;
  2819   _collection_set_size++;
  2820   _collection_set_bytes_used_before += hr->used();
  2821   _g1->register_region_with_in_cset_fast_test(hr);
  2824 void
  2825 G1CollectorPolicy_BestRegionsFirst::
  2826 choose_collection_set() {
  2827   double non_young_start_time_sec;
  2828   start_recording_regions();
  2830   guarantee(_target_pause_time_ms > -1.0,
  2831             "_target_pause_time_ms should have been set!");
  2832   assert(_collection_set == NULL, "Precondition");
  2834   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
  2835   double predicted_pause_time_ms = base_time_ms;
  2837   double target_time_ms = _target_pause_time_ms;
  2838   double time_remaining_ms = target_time_ms - base_time_ms;
  2840   // the 10% and 50% values are arbitrary...
  2841   if (time_remaining_ms < 0.10*target_time_ms) {
  2842     time_remaining_ms = 0.50 * target_time_ms;
  2843     _within_target = false;
  2844   } else {
  2845     _within_target = true;
  2848   // We figure out the number of bytes available for future to-space.
  2849   // For new regions without marking information, we must assume the
  2850   // worst-case of complete survival.  If we have marking information for a
  2851   // region, we can bound the amount of live data.  We can add a number of
  2852   // such regions, as long as the sum of the live data bounds does not
  2853   // exceed the available evacuation space.
  2854   size_t max_live_bytes = _g1->free_regions() * HeapRegion::GrainBytes;
  2856   size_t expansion_bytes =
  2857     _g1->expansion_regions() * HeapRegion::GrainBytes;
  2859   _collection_set_bytes_used_before = 0;
  2860   _collection_set_size = 0;
  2862   // Adjust for expansion and slop.
  2863   max_live_bytes = max_live_bytes + expansion_bytes;
  2865   assert(_g1->regions_accounted_for(), "Region leakage!");
  2867   HeapRegion* hr;
  2868   if (in_young_gc_mode()) {
  2869     double young_start_time_sec = os::elapsedTime();
  2871     if (G1PolicyVerbose > 0) {
  2872       gclog_or_tty->print_cr("Adding %d young regions to the CSet",
  2873                     _g1->young_list_length());
  2875     _young_cset_length  = 0;
  2876     _last_young_gc_full = full_young_gcs() ? true : false;
  2877     if (_last_young_gc_full)
  2878       ++_full_young_pause_num;
  2879     else
  2880       ++_partial_young_pause_num;
  2881     hr = _g1->pop_region_from_young_list();
  2882     while (hr != NULL) {
  2884       assert( hr->young_index_in_cset() == -1, "invariant" );
  2885       assert( hr->age_in_surv_rate_group() != -1, "invariant" );
  2886       hr->set_young_index_in_cset((int) _young_cset_length);
  2888       ++_young_cset_length;
  2889       double predicted_time_ms = predict_region_elapsed_time_ms(hr, true);
  2890       time_remaining_ms -= predicted_time_ms;
  2891       predicted_pause_time_ms += predicted_time_ms;
  2892       assert(!hr->in_collection_set(), "invariant");
  2893       add_to_collection_set(hr);
  2894       record_cset_region(hr, true);
  2895       max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  2896       if (G1PolicyVerbose > 0) {
  2897         gclog_or_tty->print_cr("  Added [" PTR_FORMAT ", " PTR_FORMAT") to CS.",
  2898                       hr->bottom(), hr->end());
  2899         gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  2900                       max_live_bytes/K);
  2902       hr = _g1->pop_region_from_young_list();
  2905     record_scan_only_regions(_g1->young_list_scan_only_length());
  2907     double young_end_time_sec = os::elapsedTime();
  2908     _recorded_young_cset_choice_time_ms =
  2909       (young_end_time_sec - young_start_time_sec) * 1000.0;
  2911     non_young_start_time_sec = os::elapsedTime();
  2913     if (_young_cset_length > 0 && _last_young_gc_full) {
  2914       // don't bother adding more regions...
  2915       goto choose_collection_set_end;
  2919   if (!in_young_gc_mode() || !full_young_gcs()) {
  2920     bool should_continue = true;
  2921     NumberSeq seq;
  2922     double avg_prediction = 100000000000000000.0; // something very large
  2923     do {
  2924       hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
  2925                                                       avg_prediction);
  2926       if (hr != NULL) {
  2927         double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
  2928         time_remaining_ms -= predicted_time_ms;
  2929         predicted_pause_time_ms += predicted_time_ms;
  2930         add_to_collection_set(hr);
  2931         record_cset_region(hr, false);
  2932         max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  2933         if (G1PolicyVerbose > 0) {
  2934           gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  2935                         max_live_bytes/K);
  2937         seq.add(predicted_time_ms);
  2938         avg_prediction = seq.avg() + seq.sd();
  2940       should_continue =
  2941         ( hr != NULL) &&
  2942         ( (adaptive_young_list_length()) ? time_remaining_ms > 0.0
  2943           : _collection_set_size < _young_list_fixed_length );
  2944     } while (should_continue);
  2946     if (!adaptive_young_list_length() &&
  2947         _collection_set_size < _young_list_fixed_length)
  2948       _should_revert_to_full_young_gcs  = true;
  2951 choose_collection_set_end:
  2952   count_CS_bytes_used();
  2954   end_recording_regions();
  2956   double non_young_end_time_sec = os::elapsedTime();
  2957   _recorded_non_young_cset_choice_time_ms =
  2958     (non_young_end_time_sec - non_young_start_time_sec) * 1000.0;
  2961 void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() {
  2962   G1CollectorPolicy::record_full_collection_end();
  2963   _collectionSetChooser->updateAfterFullCollection();
  2966 void G1CollectorPolicy_BestRegionsFirst::
  2967 expand_if_possible(size_t numRegions) {
  2968   size_t expansion_bytes = numRegions * HeapRegion::GrainBytes;
  2969   _g1->expand(expansion_bytes);
  2972 void G1CollectorPolicy_BestRegionsFirst::
  2973 record_collection_pause_end(bool abandoned) {
  2974   G1CollectorPolicy::record_collection_pause_end(abandoned);
  2975   assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
  2978 // Local Variables: ***
  2979 // c-indentation-style: gnu ***
  2980 // End: ***

mercurial