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

Fri, 06 Feb 2009 01:38:50 +0300

author
apetrusenko
date
Fri, 06 Feb 2009 01:38:50 +0300
changeset 980
58054a18d735
parent 961
818efdefcc99
child 982
1e458753107d
permissions
-rw-r--r--

6484959: G1: introduce survivor spaces
6797754: G1: combined bugfix
Summary: Implemented a policy to control G1 survivor space parameters.
Reviewed-by: tonyp, iveresov

     1 /*
     2  * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 #include "incls/_precompiled.incl"
    26 #include "incls/_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   _non_pop_summary(new NonPopSummary()),
    95   _pop_summary(new PopSummary()),
    96   _non_pop_abandoned_summary(new NonPopAbandonedSummary()),
    97   _pop_abandoned_summary(new PopAbandonedSummary()),
    99   _cur_clear_ct_time_ms(0.0),
   101   _region_num_young(0),
   102   _region_num_tenured(0),
   103   _prev_region_num_young(0),
   104   _prev_region_num_tenured(0),
   106   _aux_num(10),
   107   _all_aux_times_ms(new NumberSeq[_aux_num]),
   108   _cur_aux_start_times_ms(new double[_aux_num]),
   109   _cur_aux_times_ms(new double[_aux_num]),
   110   _cur_aux_times_set(new bool[_aux_num]),
   112   _pop_compute_rc_start(0.0),
   113   _pop_evac_start(0.0),
   115   _concurrent_mark_init_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   116   _concurrent_mark_remark_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   117   _concurrent_mark_cleanup_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
   119   // <NEW PREDICTION>
   121   _alloc_rate_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   122   _prev_collection_pause_end_ms(0.0),
   123   _pending_card_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
   124   _rs_length_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
   125   _cost_per_card_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   126   _cost_per_scan_only_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   127   _fully_young_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),
   128   _partially_young_cards_per_entry_ratio_seq(
   129                                          new TruncatedSeq(TruncatedSeqLength)),
   130   _cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   131   _partially_young_cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   132   _cost_per_byte_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   133   _cost_per_byte_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
   134   _cost_per_scan_only_region_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
   135   _constant_other_time_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   136   _young_other_cost_per_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
   137   _non_young_other_cost_per_region_ms_seq(
   138                                          new TruncatedSeq(TruncatedSeqLength)),
   140   _pending_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
   141   _scanned_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
   142   _rs_lengths_seq(new TruncatedSeq(TruncatedSeqLength)),
   144   _pause_time_target_ms((double) G1MaxPauseTimeMS),
   146   // </NEW PREDICTION>
   148   _in_young_gc_mode(false),
   149   _full_young_gcs(true),
   150   _full_young_pause_num(0),
   151   _partial_young_pause_num(0),
   153   _during_marking(false),
   154   _in_marking_window(false),
   155   _in_marking_window_im(false),
   157   _known_garbage_ratio(0.0),
   158   _known_garbage_bytes(0),
   160   _young_gc_eff_seq(new TruncatedSeq(TruncatedSeqLength)),
   161   _target_pause_time_ms(-1.0),
   163    _recent_prev_end_times_for_all_gcs_sec(new TruncatedSeq(NumPrevPausesForHeuristics)),
   165   _recent_CS_bytes_used_before(new TruncatedSeq(NumPrevPausesForHeuristics)),
   166   _recent_CS_bytes_surviving(new TruncatedSeq(NumPrevPausesForHeuristics)),
   168   _recent_avg_pause_time_ratio(0.0),
   169   _num_markings(0),
   170   _n_marks(0),
   171   _n_pauses_at_mark_end(0),
   173   _all_full_gc_times_ms(new NumberSeq()),
   175   _conc_refine_enabled(0),
   176   _conc_refine_zero_traversals(0),
   177   _conc_refine_max_traversals(0),
   178   _conc_refine_current_delta(G1ConcRefineInitialDelta),
   180   // G1PausesBtwnConcMark defaults to -1
   181   // so the hack is to do the cast  QQQ FIXME
   182   _pauses_btwn_concurrent_mark((size_t)G1PausesBtwnConcMark),
   183   _n_marks_since_last_pause(0),
   184   _conc_mark_initiated(false),
   185   _should_initiate_conc_mark(false),
   186   _should_revert_to_full_young_gcs(false),
   187   _last_full_young_gc(false),
   189   _prev_collection_pause_used_at_end_bytes(0),
   191   _collection_set(NULL),
   192 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
   193 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
   194 #endif // _MSC_VER
   196   _short_lived_surv_rate_group(new SurvRateGroup(this, "Short Lived",
   197                                                  G1YoungSurvRateNumRegionsSummary)),
   198   _survivor_surv_rate_group(new SurvRateGroup(this, "Survivor",
   199                                               G1YoungSurvRateNumRegionsSummary)),
   200   // add here any more surv rate groups
   201   _recorded_survivor_regions(0),
   202   _recorded_survivor_head(NULL),
   203   _recorded_survivor_tail(NULL),
   204   _survivors_age_table(true)
   206 {
   207   _recent_prev_end_times_for_all_gcs_sec->add(os::elapsedTime());
   208   _prev_collection_pause_end_ms = os::elapsedTime() * 1000.0;
   210   _par_last_ext_root_scan_times_ms = new double[_parallel_gc_threads];
   211   _par_last_mark_stack_scan_times_ms = new double[_parallel_gc_threads];
   212   _par_last_scan_only_times_ms = new double[_parallel_gc_threads];
   213   _par_last_scan_only_regions_scanned = new double[_parallel_gc_threads];
   215   _par_last_update_rs_start_times_ms = new double[_parallel_gc_threads];
   216   _par_last_update_rs_times_ms = new double[_parallel_gc_threads];
   217   _par_last_update_rs_processed_buffers = new double[_parallel_gc_threads];
   219   _par_last_scan_rs_start_times_ms = new double[_parallel_gc_threads];
   220   _par_last_scan_rs_times_ms = new double[_parallel_gc_threads];
   221   _par_last_scan_new_refs_times_ms = new double[_parallel_gc_threads];
   223   _par_last_obj_copy_times_ms = new double[_parallel_gc_threads];
   225   _par_last_termination_times_ms = new double[_parallel_gc_threads];
   227   // we store the data from the first pass during popularity pauses
   228   _pop_par_last_update_rs_start_times_ms = new double[_parallel_gc_threads];
   229   _pop_par_last_update_rs_times_ms = new double[_parallel_gc_threads];
   230   _pop_par_last_update_rs_processed_buffers = new double[_parallel_gc_threads];
   232   _pop_par_last_scan_rs_start_times_ms = new double[_parallel_gc_threads];
   233   _pop_par_last_scan_rs_times_ms = new double[_parallel_gc_threads];
   235   _pop_par_last_closure_app_times_ms = new double[_parallel_gc_threads];
   237   // start conservatively
   238   _expensive_region_limit_ms = 0.5 * (double) G1MaxPauseTimeMS;
   240   // <NEW PREDICTION>
   242   int index;
   243   if (ParallelGCThreads == 0)
   244     index = 0;
   245   else if (ParallelGCThreads > 8)
   246     index = 7;
   247   else
   248     index = ParallelGCThreads - 1;
   250   _pending_card_diff_seq->add(0.0);
   251   _rs_length_diff_seq->add(rs_length_diff_defaults[index]);
   252   _cost_per_card_ms_seq->add(cost_per_card_ms_defaults[index]);
   253   _cost_per_scan_only_region_ms_seq->add(
   254                                  cost_per_scan_only_region_ms_defaults[index]);
   255   _fully_young_cards_per_entry_ratio_seq->add(
   256                             fully_young_cards_per_entry_ratio_defaults[index]);
   257   _cost_per_entry_ms_seq->add(cost_per_entry_ms_defaults[index]);
   258   _cost_per_byte_ms_seq->add(cost_per_byte_ms_defaults[index]);
   259   _constant_other_time_ms_seq->add(constant_other_time_ms_defaults[index]);
   260   _young_other_cost_per_region_ms_seq->add(
   261                                young_other_cost_per_region_ms_defaults[index]);
   262   _non_young_other_cost_per_region_ms_seq->add(
   263                            non_young_other_cost_per_region_ms_defaults[index]);
   265   // </NEW PREDICTION>
   267   double time_slice  = (double) G1TimeSliceMS / 1000.0;
   268   double max_gc_time = (double) G1MaxPauseTimeMS / 1000.0;
   269   guarantee(max_gc_time < time_slice,
   270             "Max GC time should not be greater than the time slice");
   271   _mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);
   272   _sigma = (double) G1ConfidencePerc / 100.0;
   274   // start conservatively (around 50ms is about right)
   275   _concurrent_mark_init_times_ms->add(0.05);
   276   _concurrent_mark_remark_times_ms->add(0.05);
   277   _concurrent_mark_cleanup_times_ms->add(0.20);
   278   _tenuring_threshold = MaxTenuringThreshold;
   280   if (G1UseSurvivorSpace) {
   281     // if G1FixedSurvivorSpaceSize is 0 which means the size is not
   282     // fixed, then _max_survivor_regions will be calculated at
   283     // calculate_young_list_target_config diring initialization
   284     _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
   285   } else {
   286     _max_survivor_regions = 0;
   287   }
   289   initialize_all();
   290 }
   292 // Increment "i", mod "len"
   293 static void inc_mod(int& i, int len) {
   294   i++; if (i == len) i = 0;
   295 }
   297 void G1CollectorPolicy::initialize_flags() {
   298   set_min_alignment(HeapRegion::GrainBytes);
   299   set_max_alignment(GenRemSet::max_alignment_constraint(rem_set_name()));
   300   CollectorPolicy::initialize_flags();
   301 }
   303 void G1CollectorPolicy::init() {
   304   // Set aside an initial future to_space.
   305   _g1 = G1CollectedHeap::heap();
   306   size_t regions = Universe::heap()->capacity() / HeapRegion::GrainBytes;
   308   assert(Heap_lock->owned_by_self(), "Locking discipline.");
   310   if (G1SteadyStateUsed < 50) {
   311     vm_exit_during_initialization("G1SteadyStateUsed must be at least 50%.");
   312   }
   313   if (UseConcMarkSweepGC) {
   314     vm_exit_during_initialization("-XX:+UseG1GC is incompatible with "
   315                                   "-XX:+UseConcMarkSweepGC.");
   316   }
   318   initialize_gc_policy_counters();
   320   if (G1Gen) {
   321     _in_young_gc_mode = true;
   323     if (G1YoungGenSize == 0) {
   324       set_adaptive_young_list_length(true);
   325       _young_list_fixed_length = 0;
   326     } else {
   327       set_adaptive_young_list_length(false);
   328       _young_list_fixed_length = (G1YoungGenSize / HeapRegion::GrainBytes);
   329     }
   330      _free_regions_at_end_of_collection = _g1->free_regions();
   331      _scan_only_regions_at_end_of_collection = 0;
   332      calculate_young_list_min_length();
   333      guarantee( _young_list_min_length == 0, "invariant, not enough info" );
   334      calculate_young_list_target_config();
   335    } else {
   336      _young_list_fixed_length = 0;
   337     _in_young_gc_mode = false;
   338   }
   339 }
   341 // Create the jstat counters for the policy.
   342 void G1CollectorPolicy::initialize_gc_policy_counters()
   343 {
   344   _gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 2 + G1Gen);
   345 }
   347 void G1CollectorPolicy::calculate_young_list_min_length() {
   348   _young_list_min_length = 0;
   350   if (!adaptive_young_list_length())
   351     return;
   353   if (_alloc_rate_ms_seq->num() > 3) {
   354     double now_sec = os::elapsedTime();
   355     double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;
   356     double alloc_rate_ms = predict_alloc_rate_ms();
   357     int min_regions = (int) ceil(alloc_rate_ms * when_ms);
   358     int current_region_num = (int) _g1->young_list_length();
   359     _young_list_min_length = min_regions + current_region_num;
   360   }
   361 }
   363 void G1CollectorPolicy::calculate_young_list_target_config() {
   364   if (adaptive_young_list_length()) {
   365     size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
   366     calculate_young_list_target_config(rs_lengths);
   367   } else {
   368     if (full_young_gcs())
   369       _young_list_target_length = _young_list_fixed_length;
   370     else
   371       _young_list_target_length = _young_list_fixed_length / 2;
   372     _young_list_target_length = MAX2(_young_list_target_length, (size_t)1);
   373     size_t so_length = calculate_optimal_so_length(_young_list_target_length);
   374     guarantee( so_length < _young_list_target_length, "invariant" );
   375     _young_list_so_prefix_length = so_length;
   376   }
   377   calculate_survivors_policy();
   378 }
   380 // This method calculate the optimal scan-only set for a fixed young
   381 // gen size. I couldn't work out how to reuse the more elaborate one,
   382 // i.e. calculate_young_list_target_config(rs_length), as the loops are
   383 // fundamentally different (the other one finds a config for different
   384 // S-O lengths, whereas here we need to do the opposite).
   385 size_t G1CollectorPolicy::calculate_optimal_so_length(
   386                                                     size_t young_list_length) {
   387   if (!G1UseScanOnlyPrefix)
   388     return 0;
   390   if (_all_pause_times_ms->num() < 3) {
   391     // we won't use a scan-only set at the beginning to allow the rest
   392     // of the predictors to warm up
   393     return 0;
   394   }
   396   if (_cost_per_scan_only_region_ms_seq->num() < 3) {
   397     // then, we'll only set the S-O set to 1 for a little bit of time,
   398     // to get enough information on the scanning cost
   399     return 1;
   400   }
   402   size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
   403   size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
   404   size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
   405   size_t scanned_cards;
   406   if (full_young_gcs())
   407     scanned_cards = predict_young_card_num(adj_rs_lengths);
   408   else
   409     scanned_cards = predict_non_young_card_num(adj_rs_lengths);
   410   double base_time_ms = predict_base_elapsed_time_ms(pending_cards,
   411                                                      scanned_cards);
   413   size_t so_length = 0;
   414   double max_gc_eff = 0.0;
   415   for (size_t i = 0; i < young_list_length; ++i) {
   416     double gc_eff = 0.0;
   417     double pause_time_ms = 0.0;
   418     predict_gc_eff(young_list_length, i, base_time_ms,
   419                    &gc_eff, &pause_time_ms);
   420     if (gc_eff > max_gc_eff) {
   421       max_gc_eff = gc_eff;
   422       so_length = i;
   423     }
   424   }
   426   // set it to 95% of the optimal to make sure we sample the "area"
   427   // around the optimal length to get up-to-date survival rate data
   428   return so_length * 950 / 1000;
   429 }
   431 // This is a really cool piece of code! It finds the best
   432 // target configuration (young length / scan-only prefix length) so
   433 // that GC efficiency is maximized and that we also meet a pause
   434 // time. It's a triple nested loop. These loops are explained below
   435 // from the inside-out :-)
   436 //
   437 // (a) The innermost loop will try to find the optimal young length
   438 // for a fixed S-O length. It uses a binary search to speed up the
   439 // process. We assume that, for a fixed S-O length, as we add more
   440 // young regions to the CSet, the GC efficiency will only go up (I'll
   441 // skip the proof). So, using a binary search to optimize this process
   442 // makes perfect sense.
   443 //
   444 // (b) The middle loop will fix the S-O length before calling the
   445 // innermost one. It will vary it between two parameters, increasing
   446 // it by a given increment.
   447 //
   448 // (c) The outermost loop will call the middle loop three times.
   449 //   (1) The first time it will explore all possible S-O length values
   450 //   from 0 to as large as it can get, using a coarse increment (to
   451 //   quickly "home in" to where the optimal seems to be).
   452 //   (2) The second time it will explore the values around the optimal
   453 //   that was found by the first iteration using a fine increment.
   454 //   (3) Once the optimal config has been determined by the second
   455 //   iteration, we'll redo the calculation, but setting the S-O length
   456 //   to 95% of the optimal to make sure we sample the "area"
   457 //   around the optimal length to get up-to-date survival rate data
   458 //
   459 // Termination conditions for the iterations are several: the pause
   460 // time is over the limit, we do not have enough to-space, etc.
   462 void G1CollectorPolicy::calculate_young_list_target_config(size_t rs_lengths) {
   463   guarantee( adaptive_young_list_length(), "pre-condition" );
   465   double start_time_sec = os::elapsedTime();
   466   size_t min_reserve_perc = MAX2((size_t)2, (size_t)G1MinReservePerc);
   467   min_reserve_perc = MIN2((size_t) 50, min_reserve_perc);
   468   size_t reserve_regions =
   469     (size_t) ((double) min_reserve_perc * (double) _g1->n_regions() / 100.0);
   471   if (full_young_gcs() && _free_regions_at_end_of_collection > 0) {
   472     // we are in fully-young mode and there are free regions in the heap
   474     double survivor_regions_evac_time =
   475         predict_survivor_regions_evac_time();
   477     size_t min_so_length = 0;
   478     size_t max_so_length = 0;
   480     if (G1UseScanOnlyPrefix) {
   481       if (_all_pause_times_ms->num() < 3) {
   482         // we won't use a scan-only set at the beginning to allow the rest
   483         // of the predictors to warm up
   484         min_so_length = 0;
   485         max_so_length = 0;
   486       } else if (_cost_per_scan_only_region_ms_seq->num() < 3) {
   487         // then, we'll only set the S-O set to 1 for a little bit of time,
   488         // to get enough information on the scanning cost
   489         min_so_length = 1;
   490         max_so_length = 1;
   491       } else if (_in_marking_window || _last_full_young_gc) {
   492         // no S-O prefix during a marking phase either, as at the end
   493         // of the marking phase we'll have to use a very small young
   494         // length target to fill up the rest of the CSet with
   495         // non-young regions and, if we have lots of scan-only regions
   496         // left-over, we will not be able to add any more non-young
   497         // regions.
   498         min_so_length = 0;
   499         max_so_length = 0;
   500       } else {
   501         // this is the common case; we'll never reach the maximum, we
   502         // one of the end conditions will fire well before that
   503         // (hopefully!)
   504         min_so_length = 0;
   505         max_so_length = _free_regions_at_end_of_collection - 1;
   506       }
   507     } else {
   508       // no S-O prefix, as the switch is not set, but we still need to
   509       // do one iteration to calculate the best young target that
   510       // meets the pause time; this way we reuse the same code instead
   511       // of replicating it
   512       min_so_length = 0;
   513       max_so_length = 0;
   514     }
   516     double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
   517     size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
   518     size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
   519     size_t scanned_cards;
   520     if (full_young_gcs())
   521       scanned_cards = predict_young_card_num(adj_rs_lengths);
   522     else
   523       scanned_cards = predict_non_young_card_num(adj_rs_lengths);
   524     // calculate this once, so that we don't have to recalculate it in
   525     // the innermost loop
   526     double base_time_ms = predict_base_elapsed_time_ms(pending_cards, scanned_cards)
   527                           + survivor_regions_evac_time;
   528     // the result
   529     size_t final_young_length = 0;
   530     size_t final_so_length = 0;
   531     double final_gc_eff = 0.0;
   532     // we'll also keep track of how many times we go into the inner loop
   533     // this is for profiling reasons
   534     size_t calculations = 0;
   536     // this determines which of the three iterations the outer loop is in
   537     typedef enum {
   538       pass_type_coarse,
   539       pass_type_fine,
   540       pass_type_final
   541     } pass_type_t;
   543     // range of the outer loop's iteration
   544     size_t from_so_length   = min_so_length;
   545     size_t to_so_length     = max_so_length;
   546     guarantee( from_so_length <= to_so_length, "invariant" );
   548     // this will keep the S-O length that's found by the second
   549     // iteration of the outer loop; we'll keep it just in case the third
   550     // iteration fails to find something
   551     size_t fine_so_length   = 0;
   553     // the increment step for the coarse (first) iteration
   554     size_t so_coarse_increments = 5;
   556     // the common case, we'll start with the coarse iteration
   557     pass_type_t pass = pass_type_coarse;
   558     size_t so_length_incr = so_coarse_increments;
   560     if (from_so_length == to_so_length) {
   561       // not point in doing the coarse iteration, we'll go directly into
   562       // the fine one (we essentially trying to find the optimal young
   563       // length for a fixed S-O length).
   564       so_length_incr = 1;
   565       pass = pass_type_final;
   566     } else if (to_so_length - from_so_length < 3 * so_coarse_increments) {
   567       // again, the range is too short so no point in foind the coarse
   568       // iteration either
   569       so_length_incr = 1;
   570       pass = pass_type_fine;
   571     }
   573     bool done = false;
   574     // this is the outermost loop
   575     while (!done) {
   576 #ifdef TRACE_CALC_YOUNG_CONFIG
   577       // leave this in for debugging, just in case
   578       gclog_or_tty->print_cr("searching between " SIZE_FORMAT " and " SIZE_FORMAT
   579                              ", incr " SIZE_FORMAT ", pass %s",
   580                              from_so_length, to_so_length, so_length_incr,
   581                              (pass == pass_type_coarse) ? "coarse" :
   582                              (pass == pass_type_fine) ? "fine" : "final");
   583 #endif // TRACE_CALC_YOUNG_CONFIG
   585       size_t so_length = from_so_length;
   586       size_t init_free_regions =
   587         MAX2((size_t)0,
   588              _free_regions_at_end_of_collection +
   589              _scan_only_regions_at_end_of_collection - reserve_regions);
   591       // this determines whether a configuration was found
   592       bool gc_eff_set = false;
   593       // this is the middle loop
   594       while (so_length <= to_so_length) {
   595         // base time, which excludes region-related time; again we
   596         // calculate it once to avoid recalculating it in the
   597         // innermost loop
   598         double base_time_with_so_ms =
   599                            base_time_ms + predict_scan_only_time_ms(so_length);
   600         // it's already over the pause target, go around
   601         if (base_time_with_so_ms > target_pause_time_ms)
   602           break;
   604         size_t starting_young_length = so_length+1;
   606         // we make sure that the short young length that makes sense
   607         // (one more than the S-O length) is feasible
   608         size_t min_young_length = starting_young_length;
   609         double min_gc_eff;
   610         bool min_ok;
   611         ++calculations;
   612         min_ok = predict_gc_eff(min_young_length, so_length,
   613                                 base_time_with_so_ms,
   614                                 init_free_regions, target_pause_time_ms,
   615                                 &min_gc_eff);
   617         if (min_ok) {
   618           // the shortest young length is indeed feasible; we'll know
   619           // set up the max young length and we'll do a binary search
   620           // between min_young_length and max_young_length
   621           size_t max_young_length = _free_regions_at_end_of_collection - 1;
   622           double max_gc_eff = 0.0;
   623           bool max_ok = false;
   625           // the innermost loop! (finally!)
   626           while (max_young_length > min_young_length) {
   627             // we'll make sure that min_young_length is always at a
   628             // feasible config
   629             guarantee( min_ok, "invariant" );
   631             ++calculations;
   632             max_ok = predict_gc_eff(max_young_length, so_length,
   633                                     base_time_with_so_ms,
   634                                     init_free_regions, target_pause_time_ms,
   635                                     &max_gc_eff);
   637             size_t diff = (max_young_length - min_young_length) / 2;
   638             if (max_ok) {
   639               min_young_length = max_young_length;
   640               min_gc_eff = max_gc_eff;
   641               min_ok = true;
   642             }
   643             max_young_length = min_young_length + diff;
   644           }
   646           // the innermost loop found a config
   647           guarantee( min_ok, "invariant" );
   648           if (min_gc_eff > final_gc_eff) {
   649             // it's the best config so far, so we'll keep it
   650             final_gc_eff = min_gc_eff;
   651             final_young_length = min_young_length;
   652             final_so_length = so_length;
   653             gc_eff_set = true;
   654           }
   655         }
   657         // incremental the fixed S-O length and go around
   658         so_length += so_length_incr;
   659       }
   661       // this is the end of the outermost loop and we need to decide
   662       // what to do during the next iteration
   663       if (pass == pass_type_coarse) {
   664         // we just did the coarse pass (first iteration)
   666         if (!gc_eff_set)
   667           // we didn't find a feasible config so we'll just bail out; of
   668           // course, it might be the case that we missed it; but I'd say
   669           // it's a bit unlikely
   670           done = true;
   671         else {
   672           // We did find a feasible config with optimal GC eff during
   673           // the first pass. So the second pass we'll only consider the
   674           // S-O lengths around that config with a fine increment.
   676           guarantee( so_length_incr == so_coarse_increments, "invariant" );
   677           guarantee( final_so_length >= min_so_length, "invariant" );
   679 #ifdef TRACE_CALC_YOUNG_CONFIG
   680           // leave this in for debugging, just in case
   681           gclog_or_tty->print_cr("  coarse pass: SO length " SIZE_FORMAT,
   682                                  final_so_length);
   683 #endif // TRACE_CALC_YOUNG_CONFIG
   685           from_so_length =
   686             (final_so_length - min_so_length > so_coarse_increments) ?
   687             final_so_length - so_coarse_increments + 1 : min_so_length;
   688           to_so_length =
   689             (max_so_length - final_so_length > so_coarse_increments) ?
   690             final_so_length + so_coarse_increments - 1 : max_so_length;
   692           pass = pass_type_fine;
   693           so_length_incr = 1;
   694         }
   695       } else if (pass == pass_type_fine) {
   696         // we just finished the second pass
   698         if (!gc_eff_set) {
   699           // we didn't find a feasible config (yes, it's possible;
   700           // notice that, sometimes, we go directly into the fine
   701           // iteration and skip the coarse one) so we bail out
   702           done = true;
   703         } else {
   704           // We did find a feasible config with optimal GC eff
   705           guarantee( so_length_incr == 1, "invariant" );
   707           if (final_so_length == 0) {
   708             // The config is of an empty S-O set, so we'll just bail out
   709             done = true;
   710           } else {
   711             // we'll go around once more, setting the S-O length to 95%
   712             // of the optimal
   713             size_t new_so_length = 950 * final_so_length / 1000;
   715 #ifdef TRACE_CALC_YOUNG_CONFIG
   716             // leave this in for debugging, just in case
   717             gclog_or_tty->print_cr("  fine pass: SO length " SIZE_FORMAT
   718                                    ", setting it to " SIZE_FORMAT,
   719                                     final_so_length, new_so_length);
   720 #endif // TRACE_CALC_YOUNG_CONFIG
   722             from_so_length = new_so_length;
   723             to_so_length = new_so_length;
   724             fine_so_length = final_so_length;
   726             pass = pass_type_final;
   727           }
   728         }
   729       } else if (pass == pass_type_final) {
   730         // we just finished the final (third) pass
   732         if (!gc_eff_set)
   733           // we didn't find a feasible config, so we'll just use the one
   734           // we found during the second pass, which we saved
   735           final_so_length = fine_so_length;
   737         // and we're done!
   738         done = true;
   739       } else {
   740         guarantee( false, "should never reach here" );
   741       }
   743       // we now go around the outermost loop
   744     }
   746     // we should have at least one region in the target young length
   747     _young_list_target_length =
   748         MAX2((size_t) 1, final_young_length + _recorded_survivor_regions);
   749     if (final_so_length >= final_young_length)
   750       // and we need to ensure that the S-O length is not greater than
   751       // the target young length (this is being a bit careful)
   752       final_so_length = 0;
   753     _young_list_so_prefix_length = final_so_length;
   754     guarantee( !_in_marking_window || !_last_full_young_gc ||
   755                _young_list_so_prefix_length == 0, "invariant" );
   757     // let's keep an eye of how long we spend on this calculation
   758     // right now, I assume that we'll print it when we need it; we
   759     // should really adde it to the breakdown of a pause
   760     double end_time_sec = os::elapsedTime();
   761     double elapsed_time_ms = (end_time_sec - start_time_sec) * 1000.0;
   763 #ifdef TRACE_CALC_YOUNG_CONFIG
   764     // leave this in for debugging, just in case
   765     gclog_or_tty->print_cr("target = %1.1lf ms, young = " SIZE_FORMAT
   766                            ", SO = " SIZE_FORMAT ", "
   767                            "elapsed %1.2lf ms, calcs: " SIZE_FORMAT " (%s%s) "
   768                            SIZE_FORMAT SIZE_FORMAT,
   769                            target_pause_time_ms,
   770                            _young_list_target_length - _young_list_so_prefix_length,
   771                            _young_list_so_prefix_length,
   772                            elapsed_time_ms,
   773                            calculations,
   774                            full_young_gcs() ? "full" : "partial",
   775                            should_initiate_conc_mark() ? " i-m" : "",
   776                            _in_marking_window,
   777                            _in_marking_window_im);
   778 #endif // TRACE_CALC_YOUNG_CONFIG
   780     if (_young_list_target_length < _young_list_min_length) {
   781       // bummer; this means that, if we do a pause when the optimal
   782       // config dictates, we'll violate the pause spacing target (the
   783       // min length was calculate based on the application's current
   784       // alloc rate);
   786       // so, we have to bite the bullet, and allocate the minimum
   787       // number. We'll violate our target, but we just can't meet it.
   789       size_t so_length = 0;
   790       // a note further up explains why we do not want an S-O length
   791       // during marking
   792       if (!_in_marking_window && !_last_full_young_gc)
   793         // but we can still try to see whether we can find an optimal
   794         // S-O length
   795         so_length = calculate_optimal_so_length(_young_list_min_length);
   797 #ifdef TRACE_CALC_YOUNG_CONFIG
   798       // leave this in for debugging, just in case
   799       gclog_or_tty->print_cr("adjusted target length from "
   800                              SIZE_FORMAT " to " SIZE_FORMAT
   801                              ", SO " SIZE_FORMAT,
   802                              _young_list_target_length, _young_list_min_length,
   803                              so_length);
   804 #endif // TRACE_CALC_YOUNG_CONFIG
   806       _young_list_target_length =
   807         MAX2(_young_list_min_length, (size_t)1);
   808       _young_list_so_prefix_length = so_length;
   809     }
   810   } else {
   811     // we are in a partially-young mode or we've run out of regions (due
   812     // to evacuation failure)
   814 #ifdef TRACE_CALC_YOUNG_CONFIG
   815     // leave this in for debugging, just in case
   816     gclog_or_tty->print_cr("(partial) setting target to " SIZE_FORMAT
   817                            ", SO " SIZE_FORMAT,
   818                            _young_list_min_length, 0);
   819 #endif // TRACE_CALC_YOUNG_CONFIG
   821     // we'll do the pause as soon as possible and with no S-O prefix
   822     // (see above for the reasons behind the latter)
   823     _young_list_target_length =
   824       MAX2(_young_list_min_length, (size_t) 1);
   825     _young_list_so_prefix_length = 0;
   826   }
   828   _rs_lengths_prediction = rs_lengths;
   829 }
   831 // This is used by: calculate_optimal_so_length(length). It returns
   832 // the GC eff and predicted pause time for a particular config
   833 void
   834 G1CollectorPolicy::predict_gc_eff(size_t young_length,
   835                                   size_t so_length,
   836                                   double base_time_ms,
   837                                   double* ret_gc_eff,
   838                                   double* ret_pause_time_ms) {
   839   double so_time_ms = predict_scan_only_time_ms(so_length);
   840   double accum_surv_rate_adj = 0.0;
   841   if (so_length > 0)
   842     accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
   843   double accum_surv_rate =
   844     accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
   845   size_t bytes_to_copy =
   846     (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
   847   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
   848   double young_other_time_ms =
   849                        predict_young_other_time_ms(young_length - so_length);
   850   double pause_time_ms =
   851                 base_time_ms + so_time_ms + copy_time_ms + young_other_time_ms;
   852   size_t reclaimed_bytes =
   853     (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
   854   double gc_eff = (double) reclaimed_bytes / pause_time_ms;
   856   *ret_gc_eff = gc_eff;
   857   *ret_pause_time_ms = pause_time_ms;
   858 }
   860 // This is used by: calculate_young_list_target_config(rs_length). It
   861 // returns the GC eff of a particular config. It returns false if that
   862 // config violates any of the end conditions of the search in the
   863 // calling method, or true upon success. The end conditions were put
   864 // here since it's called twice and it was best not to replicate them
   865 // in the caller. Also, passing the parameteres avoids having to
   866 // recalculate them in the innermost loop.
   867 bool
   868 G1CollectorPolicy::predict_gc_eff(size_t young_length,
   869                                   size_t so_length,
   870                                   double base_time_with_so_ms,
   871                                   size_t init_free_regions,
   872                                   double target_pause_time_ms,
   873                                   double* ret_gc_eff) {
   874   *ret_gc_eff = 0.0;
   876   if (young_length >= init_free_regions)
   877     // end condition 1: not enough space for the young regions
   878     return false;
   880   double accum_surv_rate_adj = 0.0;
   881   if (so_length > 0)
   882     accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
   883   double accum_surv_rate =
   884     accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
   885   size_t bytes_to_copy =
   886     (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
   887   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
   888   double young_other_time_ms =
   889                        predict_young_other_time_ms(young_length - so_length);
   890   double pause_time_ms =
   891                    base_time_with_so_ms + copy_time_ms + young_other_time_ms;
   893   if (pause_time_ms > target_pause_time_ms)
   894     // end condition 2: over the target pause time
   895     return false;
   897   size_t reclaimed_bytes =
   898     (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
   899   size_t free_bytes =
   900                  (init_free_regions - young_length) * HeapRegion::GrainBytes;
   902   if ((2.0 + sigma()) * (double) bytes_to_copy > (double) free_bytes)
   903     // end condition 3: out of to-space (conservatively)
   904     return false;
   906   // success!
   907   double gc_eff = (double) reclaimed_bytes / pause_time_ms;
   908   *ret_gc_eff = gc_eff;
   910   return true;
   911 }
   913 double G1CollectorPolicy::predict_survivor_regions_evac_time() {
   914   double survivor_regions_evac_time = 0.0;
   915   for (HeapRegion * r = _recorded_survivor_head;
   916        r != NULL && r != _recorded_survivor_tail->get_next_young_region();
   917        r = r->get_next_young_region()) {
   918     survivor_regions_evac_time += predict_region_elapsed_time_ms(r, true);
   919   }
   920   return survivor_regions_evac_time;
   921 }
   923 void G1CollectorPolicy::check_prediction_validity() {
   924   guarantee( adaptive_young_list_length(), "should not call this otherwise" );
   926   size_t rs_lengths = _g1->young_list_sampled_rs_lengths();
   927   if (rs_lengths > _rs_lengths_prediction) {
   928     // add 10% to avoid having to recalculate often
   929     size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;
   930     calculate_young_list_target_config(rs_lengths_prediction);
   931   }
   932 }
   934 HeapWord* G1CollectorPolicy::mem_allocate_work(size_t size,
   935                                                bool is_tlab,
   936                                                bool* gc_overhead_limit_was_exceeded) {
   937   guarantee(false, "Not using this policy feature yet.");
   938   return NULL;
   939 }
   941 // This method controls how a collector handles one or more
   942 // of its generations being fully allocated.
   943 HeapWord* G1CollectorPolicy::satisfy_failed_allocation(size_t size,
   944                                                        bool is_tlab) {
   945   guarantee(false, "Not using this policy feature yet.");
   946   return NULL;
   947 }
   950 #ifndef PRODUCT
   951 bool G1CollectorPolicy::verify_young_ages() {
   952   HeapRegion* head = _g1->young_list_first_region();
   953   return
   954     verify_young_ages(head, _short_lived_surv_rate_group);
   955   // also call verify_young_ages on any additional surv rate groups
   956 }
   958 bool
   959 G1CollectorPolicy::verify_young_ages(HeapRegion* head,
   960                                      SurvRateGroup *surv_rate_group) {
   961   guarantee( surv_rate_group != NULL, "pre-condition" );
   963   const char* name = surv_rate_group->name();
   964   bool ret = true;
   965   int prev_age = -1;
   967   for (HeapRegion* curr = head;
   968        curr != NULL;
   969        curr = curr->get_next_young_region()) {
   970     SurvRateGroup* group = curr->surv_rate_group();
   971     if (group == NULL && !curr->is_survivor()) {
   972       gclog_or_tty->print_cr("## %s: encountered NULL surv_rate_group", name);
   973       ret = false;
   974     }
   976     if (surv_rate_group == group) {
   977       int age = curr->age_in_surv_rate_group();
   979       if (age < 0) {
   980         gclog_or_tty->print_cr("## %s: encountered negative age", name);
   981         ret = false;
   982       }
   984       if (age <= prev_age) {
   985         gclog_or_tty->print_cr("## %s: region ages are not strictly increasing "
   986                                "(%d, %d)", name, age, prev_age);
   987         ret = false;
   988       }
   989       prev_age = age;
   990     }
   991   }
   993   return ret;
   994 }
   995 #endif // PRODUCT
   997 void G1CollectorPolicy::record_full_collection_start() {
   998   _cur_collection_start_sec = os::elapsedTime();
   999   // Release the future to-space so that it is available for compaction into.
  1000   _g1->set_full_collection();
  1003 void G1CollectorPolicy::record_full_collection_end() {
  1004   // Consider this like a collection pause for the purposes of allocation
  1005   // since last pause.
  1006   double end_sec = os::elapsedTime();
  1007   double full_gc_time_sec = end_sec - _cur_collection_start_sec;
  1008   double full_gc_time_ms = full_gc_time_sec * 1000.0;
  1010   checkpoint_conc_overhead();
  1012   _all_full_gc_times_ms->add(full_gc_time_ms);
  1014   update_recent_gc_times(end_sec, full_gc_time_sec);
  1016   _g1->clear_full_collection();
  1018   // "Nuke" the heuristics that control the fully/partially young GC
  1019   // transitions and make sure we start with fully young GCs after the
  1020   // Full GC.
  1021   set_full_young_gcs(true);
  1022   _last_full_young_gc = false;
  1023   _should_revert_to_full_young_gcs = false;
  1024   _should_initiate_conc_mark = false;
  1025   _known_garbage_bytes = 0;
  1026   _known_garbage_ratio = 0.0;
  1027   _in_marking_window = false;
  1028   _in_marking_window_im = false;
  1030   _short_lived_surv_rate_group->record_scan_only_prefix(0);
  1031   _short_lived_surv_rate_group->start_adding_regions();
  1032   // also call this on any additional surv rate groups
  1034   record_survivor_regions(0, NULL, NULL);
  1036   _prev_region_num_young   = _region_num_young;
  1037   _prev_region_num_tenured = _region_num_tenured;
  1039   _free_regions_at_end_of_collection = _g1->free_regions();
  1040   _scan_only_regions_at_end_of_collection = 0;
  1041   // Reset survivors SurvRateGroup.
  1042   _survivor_surv_rate_group->reset();
  1043   calculate_young_list_min_length();
  1044   calculate_young_list_target_config();
  1047 void G1CollectorPolicy::record_pop_compute_rc_start() {
  1048   _pop_compute_rc_start = os::elapsedTime();
  1050 void G1CollectorPolicy::record_pop_compute_rc_end() {
  1051   double ms = (os::elapsedTime() - _pop_compute_rc_start)*1000.0;
  1052   _cur_popular_compute_rc_time_ms = ms;
  1053   _pop_compute_rc_start = 0.0;
  1055 void G1CollectorPolicy::record_pop_evac_start() {
  1056   _pop_evac_start = os::elapsedTime();
  1058 void G1CollectorPolicy::record_pop_evac_end() {
  1059   double ms = (os::elapsedTime() - _pop_evac_start)*1000.0;
  1060   _cur_popular_evac_time_ms = ms;
  1061   _pop_evac_start = 0.0;
  1064 void G1CollectorPolicy::record_before_bytes(size_t bytes) {
  1065   _bytes_in_to_space_before_gc += bytes;
  1068 void G1CollectorPolicy::record_after_bytes(size_t bytes) {
  1069   _bytes_in_to_space_after_gc += bytes;
  1072 void G1CollectorPolicy::record_stop_world_start() {
  1073   _stop_world_start = os::elapsedTime();
  1076 void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
  1077                                                       size_t start_used) {
  1078   if (PrintGCDetails) {
  1079     gclog_or_tty->stamp(PrintGCTimeStamps);
  1080     gclog_or_tty->print("[GC pause");
  1081     if (in_young_gc_mode())
  1082       gclog_or_tty->print(" (%s)", full_young_gcs() ? "young" : "partial");
  1085   assert(_g1->used_regions() == _g1->recalculate_used_regions(),
  1086          "sanity");
  1088   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
  1089   _all_stop_world_times_ms->add(s_w_t_ms);
  1090   _stop_world_start = 0.0;
  1092   _cur_collection_start_sec = start_time_sec;
  1093   _cur_collection_pause_used_at_start_bytes = start_used;
  1094   _cur_collection_pause_used_regions_at_start = _g1->used_regions();
  1095   _pending_cards = _g1->pending_card_num();
  1096   _max_pending_cards = _g1->max_pending_card_num();
  1098   _bytes_in_to_space_before_gc = 0;
  1099   _bytes_in_to_space_after_gc = 0;
  1100   _bytes_in_collection_set_before_gc = 0;
  1102 #ifdef DEBUG
  1103   // initialise these to something well known so that we can spot
  1104   // if they are not set properly
  1106   for (int i = 0; i < _parallel_gc_threads; ++i) {
  1107     _par_last_ext_root_scan_times_ms[i] = -666.0;
  1108     _par_last_mark_stack_scan_times_ms[i] = -666.0;
  1109     _par_last_scan_only_times_ms[i] = -666.0;
  1110     _par_last_scan_only_regions_scanned[i] = -666.0;
  1111     _par_last_update_rs_start_times_ms[i] = -666.0;
  1112     _par_last_update_rs_times_ms[i] = -666.0;
  1113     _par_last_update_rs_processed_buffers[i] = -666.0;
  1114     _par_last_scan_rs_start_times_ms[i] = -666.0;
  1115     _par_last_scan_rs_times_ms[i] = -666.0;
  1116     _par_last_scan_new_refs_times_ms[i] = -666.0;
  1117     _par_last_obj_copy_times_ms[i] = -666.0;
  1118     _par_last_termination_times_ms[i] = -666.0;
  1120     _pop_par_last_update_rs_start_times_ms[i] = -666.0;
  1121     _pop_par_last_update_rs_times_ms[i] = -666.0;
  1122     _pop_par_last_update_rs_processed_buffers[i] = -666.0;
  1123     _pop_par_last_scan_rs_start_times_ms[i] = -666.0;
  1124     _pop_par_last_scan_rs_times_ms[i] = -666.0;
  1125     _pop_par_last_closure_app_times_ms[i] = -666.0;
  1127 #endif
  1129   for (int i = 0; i < _aux_num; ++i) {
  1130     _cur_aux_times_ms[i] = 0.0;
  1131     _cur_aux_times_set[i] = false;
  1134   _satb_drain_time_set = false;
  1135   _last_satb_drain_processed_buffers = -1;
  1137   if (in_young_gc_mode())
  1138     _last_young_gc_full = false;
  1141   // do that for any other surv rate groups
  1142   _short_lived_surv_rate_group->stop_adding_regions();
  1143   size_t short_lived_so_length = _young_list_so_prefix_length;
  1144   _short_lived_surv_rate_group->record_scan_only_prefix(short_lived_so_length);
  1145   tag_scan_only(short_lived_so_length);
  1147   if (G1UseSurvivorSpace) {
  1148     _survivors_age_table.clear();
  1151   assert( verify_young_ages(), "region age verification" );
  1154 void G1CollectorPolicy::tag_scan_only(size_t short_lived_scan_only_length) {
  1155   // done in a way that it can be extended for other surv rate groups too...
  1157   HeapRegion* head = _g1->young_list_first_region();
  1158   bool finished_short_lived = (short_lived_scan_only_length == 0);
  1160   if (finished_short_lived)
  1161     return;
  1163   for (HeapRegion* curr = head;
  1164        curr != NULL;
  1165        curr = curr->get_next_young_region()) {
  1166     SurvRateGroup* surv_rate_group = curr->surv_rate_group();
  1167     int age = curr->age_in_surv_rate_group();
  1169     if (surv_rate_group == _short_lived_surv_rate_group) {
  1170       if ((size_t)age < short_lived_scan_only_length)
  1171         curr->set_scan_only();
  1172       else
  1173         finished_short_lived = true;
  1177     if (finished_short_lived)
  1178       return;
  1181   guarantee( false, "we should never reach here" );
  1184 void G1CollectorPolicy::record_popular_pause_preamble_start() {
  1185   _cur_popular_preamble_start_ms = os::elapsedTime() * 1000.0;
  1188 void G1CollectorPolicy::record_popular_pause_preamble_end() {
  1189   _cur_popular_preamble_time_ms =
  1190     (os::elapsedTime() * 1000.0) - _cur_popular_preamble_start_ms;
  1192   // copy the recorded statistics of the first pass to temporary arrays
  1193   for (int i = 0; i < _parallel_gc_threads; ++i) {
  1194     _pop_par_last_update_rs_start_times_ms[i] = _par_last_update_rs_start_times_ms[i];
  1195     _pop_par_last_update_rs_times_ms[i] = _par_last_update_rs_times_ms[i];
  1196     _pop_par_last_update_rs_processed_buffers[i] = _par_last_update_rs_processed_buffers[i];
  1197     _pop_par_last_scan_rs_start_times_ms[i] = _par_last_scan_rs_start_times_ms[i];
  1198     _pop_par_last_scan_rs_times_ms[i] = _par_last_scan_rs_times_ms[i];
  1199     _pop_par_last_closure_app_times_ms[i] = _par_last_obj_copy_times_ms[i];
  1203 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
  1204   _mark_closure_time_ms = mark_closure_time_ms;
  1207 void G1CollectorPolicy::record_concurrent_mark_init_start() {
  1208   _mark_init_start_sec = os::elapsedTime();
  1209   guarantee(!in_young_gc_mode(), "should not do be here in young GC mode");
  1212 void G1CollectorPolicy::record_concurrent_mark_init_end_pre(double
  1213                                                    mark_init_elapsed_time_ms) {
  1214   _during_marking = true;
  1215   _should_initiate_conc_mark = false;
  1216   _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
  1219 void G1CollectorPolicy::record_concurrent_mark_init_end() {
  1220   double end_time_sec = os::elapsedTime();
  1221   double elapsed_time_ms = (end_time_sec - _mark_init_start_sec) * 1000.0;
  1222   _concurrent_mark_init_times_ms->add(elapsed_time_ms);
  1223   checkpoint_conc_overhead();
  1224   record_concurrent_mark_init_end_pre(elapsed_time_ms);
  1226   _mmu_tracker->add_pause(_mark_init_start_sec, end_time_sec, true);
  1229 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
  1230   _mark_remark_start_sec = os::elapsedTime();
  1231   _during_marking = false;
  1234 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
  1235   double end_time_sec = os::elapsedTime();
  1236   double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
  1237   checkpoint_conc_overhead();
  1238   _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
  1239   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1240   _prev_collection_pause_end_ms += elapsed_time_ms;
  1242   _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
  1245 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
  1246   _mark_cleanup_start_sec = os::elapsedTime();
  1249 void
  1250 G1CollectorPolicy::record_concurrent_mark_cleanup_end(size_t freed_bytes,
  1251                                                       size_t max_live_bytes) {
  1252   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  1253   record_concurrent_mark_cleanup_end_work2();
  1256 void
  1257 G1CollectorPolicy::
  1258 record_concurrent_mark_cleanup_end_work1(size_t freed_bytes,
  1259                                          size_t max_live_bytes) {
  1260   if (_n_marks < 2) _n_marks++;
  1261   if (G1PolicyVerbose > 0)
  1262     gclog_or_tty->print_cr("At end of marking, max_live is " SIZE_FORMAT " MB "
  1263                            " (of " SIZE_FORMAT " MB heap).",
  1264                            max_live_bytes/M, _g1->capacity()/M);
  1267 // The important thing about this is that it includes "os::elapsedTime".
  1268 void G1CollectorPolicy::record_concurrent_mark_cleanup_end_work2() {
  1269   checkpoint_conc_overhead();
  1270   double end_time_sec = os::elapsedTime();
  1271   double elapsed_time_ms = (end_time_sec - _mark_cleanup_start_sec)*1000.0;
  1272   _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
  1273   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1274   _prev_collection_pause_end_ms += elapsed_time_ms;
  1276   _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_time_sec, true);
  1278   _num_markings++;
  1280   // We did a marking, so reset the "since_last_mark" variables.
  1281   double considerConcMarkCost = 1.0;
  1282   // If there are available processors, concurrent activity is free...
  1283   if (Threads::number_of_non_daemon_threads() * 2 <
  1284       os::active_processor_count()) {
  1285     considerConcMarkCost = 0.0;
  1287   _n_pauses_at_mark_end = _n_pauses;
  1288   _n_marks_since_last_pause++;
  1289   _conc_mark_initiated = false;
  1292 void
  1293 G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
  1294   if (in_young_gc_mode()) {
  1295     _should_revert_to_full_young_gcs = false;
  1296     _last_full_young_gc = true;
  1297     _in_marking_window = false;
  1298     if (adaptive_young_list_length())
  1299       calculate_young_list_target_config();
  1303 void G1CollectorPolicy::record_concurrent_pause() {
  1304   if (_stop_world_start > 0.0) {
  1305     double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
  1306     _all_yield_times_ms->add(yield_ms);
  1310 void G1CollectorPolicy::record_concurrent_pause_end() {
  1313 void G1CollectorPolicy::record_collection_pause_end_CH_strong_roots() {
  1314   _cur_CH_strong_roots_end_sec = os::elapsedTime();
  1315   _cur_CH_strong_roots_dur_ms =
  1316     (_cur_CH_strong_roots_end_sec - _cur_collection_start_sec) * 1000.0;
  1319 void G1CollectorPolicy::record_collection_pause_end_G1_strong_roots() {
  1320   _cur_G1_strong_roots_end_sec = os::elapsedTime();
  1321   _cur_G1_strong_roots_dur_ms =
  1322     (_cur_G1_strong_roots_end_sec - _cur_CH_strong_roots_end_sec) * 1000.0;
  1325 template<class T>
  1326 T sum_of(T* sum_arr, int start, int n, int N) {
  1327   T sum = (T)0;
  1328   for (int i = 0; i < n; i++) {
  1329     int j = (start + i) % N;
  1330     sum += sum_arr[j];
  1332   return sum;
  1335 void G1CollectorPolicy::print_par_stats (int level,
  1336                                          const char* str,
  1337                                          double* data,
  1338                                          bool summary) {
  1339   double min = data[0], max = data[0];
  1340   double total = 0.0;
  1341   int j;
  1342   for (j = 0; j < level; ++j)
  1343     gclog_or_tty->print("   ");
  1344   gclog_or_tty->print("[%s (ms):", str);
  1345   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1346     double val = data[i];
  1347     if (val < min)
  1348       min = val;
  1349     if (val > max)
  1350       max = val;
  1351     total += val;
  1352     gclog_or_tty->print("  %3.1lf", val);
  1354   if (summary) {
  1355     gclog_or_tty->print_cr("");
  1356     double avg = total / (double) ParallelGCThreads;
  1357     gclog_or_tty->print(" ");
  1358     for (j = 0; j < level; ++j)
  1359       gclog_or_tty->print("   ");
  1360     gclog_or_tty->print("Avg: %5.1lf, Min: %5.1lf, Max: %5.1lf",
  1361                         avg, min, max);
  1363   gclog_or_tty->print_cr("]");
  1366 void G1CollectorPolicy::print_par_buffers (int level,
  1367                                          const char* str,
  1368                                          double* data,
  1369                                          bool summary) {
  1370   double min = data[0], max = data[0];
  1371   double total = 0.0;
  1372   int j;
  1373   for (j = 0; j < level; ++j)
  1374     gclog_or_tty->print("   ");
  1375   gclog_or_tty->print("[%s :", str);
  1376   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1377     double val = data[i];
  1378     if (val < min)
  1379       min = val;
  1380     if (val > max)
  1381       max = val;
  1382     total += val;
  1383     gclog_or_tty->print(" %d", (int) val);
  1385   if (summary) {
  1386     gclog_or_tty->print_cr("");
  1387     double avg = total / (double) ParallelGCThreads;
  1388     gclog_or_tty->print(" ");
  1389     for (j = 0; j < level; ++j)
  1390       gclog_or_tty->print("   ");
  1391     gclog_or_tty->print("Sum: %d, Avg: %d, Min: %d, Max: %d",
  1392                (int)total, (int)avg, (int)min, (int)max);
  1394   gclog_or_tty->print_cr("]");
  1397 void G1CollectorPolicy::print_stats (int level,
  1398                                      const char* str,
  1399                                      double value) {
  1400   for (int j = 0; j < level; ++j)
  1401     gclog_or_tty->print("   ");
  1402   gclog_or_tty->print_cr("[%s: %5.1lf ms]", str, value);
  1405 void G1CollectorPolicy::print_stats (int level,
  1406                                      const char* str,
  1407                                      int value) {
  1408   for (int j = 0; j < level; ++j)
  1409     gclog_or_tty->print("   ");
  1410   gclog_or_tty->print_cr("[%s: %d]", str, value);
  1413 double G1CollectorPolicy::avg_value (double* data) {
  1414   if (ParallelGCThreads > 0) {
  1415     double ret = 0.0;
  1416     for (uint i = 0; i < ParallelGCThreads; ++i)
  1417       ret += data[i];
  1418     return ret / (double) ParallelGCThreads;
  1419   } else {
  1420     return data[0];
  1424 double G1CollectorPolicy::max_value (double* data) {
  1425   if (ParallelGCThreads > 0) {
  1426     double ret = data[0];
  1427     for (uint i = 1; i < ParallelGCThreads; ++i)
  1428       if (data[i] > ret)
  1429         ret = data[i];
  1430     return ret;
  1431   } else {
  1432     return data[0];
  1436 double G1CollectorPolicy::sum_of_values (double* data) {
  1437   if (ParallelGCThreads > 0) {
  1438     double sum = 0.0;
  1439     for (uint i = 0; i < ParallelGCThreads; i++)
  1440       sum += data[i];
  1441     return sum;
  1442   } else {
  1443     return data[0];
  1447 double G1CollectorPolicy::max_sum (double* data1,
  1448                                    double* data2) {
  1449   double ret = data1[0] + data2[0];
  1451   if (ParallelGCThreads > 0) {
  1452     for (uint i = 1; i < ParallelGCThreads; ++i) {
  1453       double data = data1[i] + data2[i];
  1454       if (data > ret)
  1455         ret = data;
  1458   return ret;
  1461 // Anything below that is considered to be zero
  1462 #define MIN_TIMER_GRANULARITY 0.0000001
  1464 void G1CollectorPolicy::record_collection_pause_end(bool popular,
  1465                                                     bool abandoned) {
  1466   double end_time_sec = os::elapsedTime();
  1467   double elapsed_ms = _last_pause_time_ms;
  1468   bool parallel = ParallelGCThreads > 0;
  1469   double evac_ms = (end_time_sec - _cur_G1_strong_roots_end_sec) * 1000.0;
  1470   size_t rs_size =
  1471     _cur_collection_pause_used_regions_at_start - collection_set_size();
  1472   size_t cur_used_bytes = _g1->used();
  1473   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
  1474   bool last_pause_included_initial_mark = false;
  1476 #ifndef PRODUCT
  1477   if (G1YoungSurvRateVerbose) {
  1478     gclog_or_tty->print_cr("");
  1479     _short_lived_surv_rate_group->print();
  1480     // do that for any other surv rate groups too
  1482 #endif // PRODUCT
  1484   checkpoint_conc_overhead();
  1486   if (in_young_gc_mode()) {
  1487     last_pause_included_initial_mark = _should_initiate_conc_mark;
  1488     if (last_pause_included_initial_mark)
  1489       record_concurrent_mark_init_end_pre(0.0);
  1491     size_t min_used_targ =
  1492       (_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta);
  1494     if (cur_used_bytes > min_used_targ) {
  1495       if (cur_used_bytes <= _prev_collection_pause_used_at_end_bytes) {
  1496       } else if (!_g1->mark_in_progress() && !_last_full_young_gc) {
  1497         _should_initiate_conc_mark = true;
  1501     _prev_collection_pause_used_at_end_bytes = cur_used_bytes;
  1504   _mmu_tracker->add_pause(end_time_sec - elapsed_ms/1000.0,
  1505                           end_time_sec, false);
  1507   guarantee(_cur_collection_pause_used_regions_at_start >=
  1508             collection_set_size(),
  1509             "Negative RS size?");
  1511   // This assert is exempted when we're doing parallel collection pauses,
  1512   // because the fragmentation caused by the parallel GC allocation buffers
  1513   // can lead to more memory being used during collection than was used
  1514   // before. Best leave this out until the fragmentation problem is fixed.
  1515   // Pauses in which evacuation failed can also lead to negative
  1516   // collections, since no space is reclaimed from a region containing an
  1517   // object whose evacuation failed.
  1518   // Further, we're now always doing parallel collection.  But I'm still
  1519   // leaving this here as a placeholder for a more precise assertion later.
  1520   // (DLD, 10/05.)
  1521   assert((true || parallel) // Always using GC LABs now.
  1522          || _g1->evacuation_failed()
  1523          || _cur_collection_pause_used_at_start_bytes >= cur_used_bytes,
  1524          "Negative collection");
  1526   size_t freed_bytes =
  1527     _cur_collection_pause_used_at_start_bytes - cur_used_bytes;
  1528   size_t surviving_bytes = _collection_set_bytes_used_before - freed_bytes;
  1529   double survival_fraction =
  1530     (double)surviving_bytes/
  1531     (double)_collection_set_bytes_used_before;
  1533   _n_pauses++;
  1535   if (!abandoned) {
  1536     _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
  1537     _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
  1538     _recent_evac_times_ms->add(evac_ms);
  1539     _recent_pause_times_ms->add(elapsed_ms);
  1541     _recent_rs_sizes->add(rs_size);
  1543     // We exempt parallel collection from this check because Alloc Buffer
  1544     // fragmentation can produce negative collections.  Same with evac
  1545     // failure.
  1546     // Further, we're now always doing parallel collection.  But I'm still
  1547     // leaving this here as a placeholder for a more precise assertion later.
  1548     // (DLD, 10/05.
  1549     assert((true || parallel)
  1550            || _g1->evacuation_failed()
  1551            || surviving_bytes <= _collection_set_bytes_used_before,
  1552            "Or else negative collection!");
  1553     _recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
  1554     _recent_CS_bytes_surviving->add(surviving_bytes);
  1556     // this is where we update the allocation rate of the application
  1557     double app_time_ms =
  1558       (_cur_collection_start_sec * 1000.0 - _prev_collection_pause_end_ms);
  1559     if (app_time_ms < MIN_TIMER_GRANULARITY) {
  1560       // This usually happens due to the timer not having the required
  1561       // granularity. Some Linuxes are the usual culprits.
  1562       // We'll just set it to something (arbitrarily) small.
  1563       app_time_ms = 1.0;
  1565     size_t regions_allocated =
  1566       (_region_num_young - _prev_region_num_young) +
  1567       (_region_num_tenured - _prev_region_num_tenured);
  1568     double alloc_rate_ms = (double) regions_allocated / app_time_ms;
  1569     _alloc_rate_ms_seq->add(alloc_rate_ms);
  1570     _prev_region_num_young   = _region_num_young;
  1571     _prev_region_num_tenured = _region_num_tenured;
  1573     double interval_ms =
  1574       (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
  1575     update_recent_gc_times(end_time_sec, elapsed_ms);
  1576     _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
  1577     assert(recent_avg_pause_time_ratio() < 1.00, "All GC?");
  1580   if (G1PolicyVerbose > 1) {
  1581     gclog_or_tty->print_cr("   Recording collection pause(%d)", _n_pauses);
  1584   PauseSummary* summary;
  1585   if (!abandoned && !popular)
  1586     summary = _non_pop_summary;
  1587   else if (!abandoned && popular)
  1588     summary = _pop_summary;
  1589   else if (abandoned && !popular)
  1590     summary = _non_pop_abandoned_summary;
  1591   else if (abandoned && popular)
  1592     summary = _pop_abandoned_summary;
  1593   else
  1594     guarantee(false, "should not get here!");
  1596   double pop_update_rs_time;
  1597   double pop_update_rs_processed_buffers;
  1598   double pop_scan_rs_time;
  1599   double pop_closure_app_time;
  1600   double pop_other_time;
  1602   if (popular) {
  1603     PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
  1604     guarantee(preamble_summary != NULL, "should not be null!");
  1606     pop_update_rs_time = avg_value(_pop_par_last_update_rs_times_ms);
  1607     pop_update_rs_processed_buffers =
  1608       sum_of_values(_pop_par_last_update_rs_processed_buffers);
  1609     pop_scan_rs_time = avg_value(_pop_par_last_scan_rs_times_ms);
  1610     pop_closure_app_time = avg_value(_pop_par_last_closure_app_times_ms);
  1611     pop_other_time = _cur_popular_preamble_time_ms -
  1612       (pop_update_rs_time + pop_scan_rs_time + pop_closure_app_time +
  1613        _cur_popular_evac_time_ms);
  1615     preamble_summary->record_pop_preamble_time_ms(_cur_popular_preamble_time_ms);
  1616     preamble_summary->record_pop_update_rs_time_ms(pop_update_rs_time);
  1617     preamble_summary->record_pop_scan_rs_time_ms(pop_scan_rs_time);
  1618     preamble_summary->record_pop_closure_app_time_ms(pop_closure_app_time);
  1619     preamble_summary->record_pop_evacuation_time_ms(_cur_popular_evac_time_ms);
  1620     preamble_summary->record_pop_other_time_ms(pop_other_time);
  1623   double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
  1624   double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
  1625   double scan_only_time = avg_value(_par_last_scan_only_times_ms);
  1626   double scan_only_regions_scanned =
  1627     sum_of_values(_par_last_scan_only_regions_scanned);
  1628   double update_rs_time = avg_value(_par_last_update_rs_times_ms);
  1629   double update_rs_processed_buffers =
  1630     sum_of_values(_par_last_update_rs_processed_buffers);
  1631   double scan_rs_time = avg_value(_par_last_scan_rs_times_ms);
  1632   double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
  1633   double termination_time = avg_value(_par_last_termination_times_ms);
  1635   double parallel_other_time;
  1636   if (!abandoned) {
  1637     MainBodySummary* body_summary = summary->main_body_summary();
  1638     guarantee(body_summary != NULL, "should not be null!");
  1640     if (_satb_drain_time_set)
  1641       body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
  1642     else
  1643       body_summary->record_satb_drain_time_ms(0.0);
  1644     body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
  1645     body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
  1646     body_summary->record_scan_only_time_ms(scan_only_time);
  1647     body_summary->record_update_rs_time_ms(update_rs_time);
  1648     body_summary->record_scan_rs_time_ms(scan_rs_time);
  1649     body_summary->record_obj_copy_time_ms(obj_copy_time);
  1650     if (parallel) {
  1651       body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
  1652       body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
  1653       body_summary->record_termination_time_ms(termination_time);
  1654       parallel_other_time = _cur_collection_par_time_ms -
  1655         (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
  1656          scan_only_time + scan_rs_time + obj_copy_time + termination_time);
  1657       body_summary->record_parallel_other_time_ms(parallel_other_time);
  1659     body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
  1662   if (G1PolicyVerbose > 1) {
  1663     gclog_or_tty->print_cr("      ET: %10.6f ms           (avg: %10.6f ms)\n"
  1664                            "        CH Strong: %10.6f ms    (avg: %10.6f ms)\n"
  1665                            "        G1 Strong: %10.6f ms    (avg: %10.6f ms)\n"
  1666                            "        Evac:      %10.6f ms    (avg: %10.6f ms)\n"
  1667                            "       ET-RS:  %10.6f ms      (avg: %10.6f ms)\n"
  1668                            "      |RS|: " SIZE_FORMAT,
  1669                            elapsed_ms, recent_avg_time_for_pauses_ms(),
  1670                            _cur_CH_strong_roots_dur_ms, recent_avg_time_for_CH_strong_ms(),
  1671                            _cur_G1_strong_roots_dur_ms, recent_avg_time_for_G1_strong_ms(),
  1672                            evac_ms, recent_avg_time_for_evac_ms(),
  1673                            scan_rs_time,
  1674                            recent_avg_time_for_pauses_ms() -
  1675                            recent_avg_time_for_G1_strong_ms(),
  1676                            rs_size);
  1678     gclog_or_tty->print_cr("       Used at start: " SIZE_FORMAT"K"
  1679                            "       At end " SIZE_FORMAT "K\n"
  1680                            "       garbage      : " SIZE_FORMAT "K"
  1681                            "       of     " SIZE_FORMAT "K\n"
  1682                            "       survival     : %6.2f%%  (%6.2f%% avg)",
  1683                            _cur_collection_pause_used_at_start_bytes/K,
  1684                            _g1->used()/K, freed_bytes/K,
  1685                            _collection_set_bytes_used_before/K,
  1686                            survival_fraction*100.0,
  1687                            recent_avg_survival_fraction()*100.0);
  1688     gclog_or_tty->print_cr("       Recent %% gc pause time: %6.2f",
  1689                            recent_avg_pause_time_ratio() * 100.0);
  1692   double other_time_ms = elapsed_ms;
  1693   if (popular)
  1694     other_time_ms -= _cur_popular_preamble_time_ms;
  1696   if (!abandoned) {
  1697     if (_satb_drain_time_set)
  1698       other_time_ms -= _cur_satb_drain_time_ms;
  1700     if (parallel)
  1701       other_time_ms -= _cur_collection_par_time_ms + _cur_clear_ct_time_ms;
  1702     else
  1703       other_time_ms -=
  1704         update_rs_time +
  1705         ext_root_scan_time + mark_stack_scan_time + scan_only_time +
  1706         scan_rs_time + obj_copy_time;
  1709   if (PrintGCDetails) {
  1710     gclog_or_tty->print_cr("%s%s, %1.8lf secs]",
  1711                            (popular && !abandoned) ? " (popular)" :
  1712                            (!popular && abandoned) ? " (abandoned)" :
  1713                            (popular && abandoned) ? " (popular/abandoned)" : "",
  1714                            (last_pause_included_initial_mark) ? " (initial-mark)" : "",
  1715                            elapsed_ms / 1000.0);
  1717     if (!abandoned) {
  1718       if (_satb_drain_time_set)
  1719         print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
  1720       if (_last_satb_drain_processed_buffers >= 0)
  1721         print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
  1723     if (popular)
  1724       print_stats(1, "Popularity Preamble", _cur_popular_preamble_time_ms);
  1725     if (parallel) {
  1726       if (popular) {
  1727         print_par_stats(2, "Update RS (Start)", _pop_par_last_update_rs_start_times_ms, false);
  1728         print_par_stats(2, "Update RS", _pop_par_last_update_rs_times_ms);
  1729         if (G1RSBarrierUseQueue)
  1730           print_par_buffers(3, "Processed Buffers",
  1731                             _pop_par_last_update_rs_processed_buffers, true);
  1732         print_par_stats(2, "Scan RS", _pop_par_last_scan_rs_times_ms);
  1733         print_par_stats(2, "Closure app", _pop_par_last_closure_app_times_ms);
  1734         print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
  1735         print_stats(2, "Other", pop_other_time);
  1737       if (!abandoned) {
  1738         print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
  1739         if (!popular) {
  1740           print_par_stats(2, "Update RS (Start)", _par_last_update_rs_start_times_ms, false);
  1741           print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
  1742           if (G1RSBarrierUseQueue)
  1743             print_par_buffers(3, "Processed Buffers",
  1744                               _par_last_update_rs_processed_buffers, true);
  1746         print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
  1747         print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
  1748         print_par_stats(2, "Scan-Only Scanning", _par_last_scan_only_times_ms);
  1749         print_par_buffers(3, "Scan-Only Regions",
  1750                           _par_last_scan_only_regions_scanned, true);
  1751         print_par_stats(2, "Scan RS", _par_last_scan_rs_times_ms);
  1752         print_par_stats(2, "Object Copy", _par_last_obj_copy_times_ms);
  1753         print_par_stats(2, "Termination", _par_last_termination_times_ms);
  1754         print_stats(2, "Other", parallel_other_time);
  1755         print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
  1757     } else {
  1758       if (popular) {
  1759         print_stats(2, "Update RS", pop_update_rs_time);
  1760         if (G1RSBarrierUseQueue)
  1761           print_stats(3, "Processed Buffers",
  1762                       (int)pop_update_rs_processed_buffers);
  1763         print_stats(2, "Scan RS", pop_scan_rs_time);
  1764         print_stats(2, "Closure App", pop_closure_app_time);
  1765         print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
  1766         print_stats(2, "Other", pop_other_time);
  1768       if (!abandoned) {
  1769         if (!popular) {
  1770           print_stats(1, "Update RS", update_rs_time);
  1771           if (G1RSBarrierUseQueue)
  1772             print_stats(2, "Processed Buffers",
  1773                         (int)update_rs_processed_buffers);
  1775         print_stats(1, "Ext Root Scanning", ext_root_scan_time);
  1776         print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
  1777         print_stats(1, "Scan-Only Scanning", scan_only_time);
  1778         print_stats(1, "Scan RS", scan_rs_time);
  1779         print_stats(1, "Object Copying", obj_copy_time);
  1782     print_stats(1, "Other", other_time_ms);
  1783     for (int i = 0; i < _aux_num; ++i) {
  1784       if (_cur_aux_times_set[i]) {
  1785         char buffer[96];
  1786         sprintf(buffer, "Aux%d", i);
  1787         print_stats(1, buffer, _cur_aux_times_ms[i]);
  1791   if (PrintGCDetails)
  1792     gclog_or_tty->print("   [");
  1793   if (PrintGC || PrintGCDetails)
  1794     _g1->print_size_transition(gclog_or_tty,
  1795                                _cur_collection_pause_used_at_start_bytes,
  1796                                _g1->used(), _g1->capacity());
  1797   if (PrintGCDetails)
  1798     gclog_or_tty->print_cr("]");
  1800   _all_pause_times_ms->add(elapsed_ms);
  1801   summary->record_total_time_ms(elapsed_ms);
  1802   summary->record_other_time_ms(other_time_ms);
  1803   for (int i = 0; i < _aux_num; ++i)
  1804     if (_cur_aux_times_set[i])
  1805       _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
  1807   // Reset marks-between-pauses counter.
  1808   _n_marks_since_last_pause = 0;
  1810   // Update the efficiency-since-mark vars.
  1811   double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
  1812   if (elapsed_ms < MIN_TIMER_GRANULARITY) {
  1813     // This usually happens due to the timer not having the required
  1814     // granularity. Some Linuxes are the usual culprits.
  1815     // We'll just set it to something (arbitrarily) small.
  1816     proc_ms = 1.0;
  1818   double cur_efficiency = (double) freed_bytes / proc_ms;
  1820   bool new_in_marking_window = _in_marking_window;
  1821   bool new_in_marking_window_im = false;
  1822   if (_should_initiate_conc_mark) {
  1823     new_in_marking_window = true;
  1824     new_in_marking_window_im = true;
  1827   if (in_young_gc_mode()) {
  1828     if (_last_full_young_gc) {
  1829       set_full_young_gcs(false);
  1830       _last_full_young_gc = false;
  1833     if ( !_last_young_gc_full ) {
  1834       if ( _should_revert_to_full_young_gcs ||
  1835            _known_garbage_ratio < 0.05 ||
  1836            (adaptive_young_list_length() &&
  1837            (get_gc_eff_factor() * cur_efficiency < predict_young_gc_eff())) ) {
  1838         set_full_young_gcs(true);
  1841     _should_revert_to_full_young_gcs = false;
  1843     if (_last_young_gc_full && !_during_marking)
  1844       _young_gc_eff_seq->add(cur_efficiency);
  1847   _short_lived_surv_rate_group->start_adding_regions();
  1848   // do that for any other surv rate groupsx
  1850   // <NEW PREDICTION>
  1852   if (!popular && !abandoned) {
  1853     double pause_time_ms = elapsed_ms;
  1855     size_t diff = 0;
  1856     if (_max_pending_cards >= _pending_cards)
  1857       diff = _max_pending_cards - _pending_cards;
  1858     _pending_card_diff_seq->add((double) diff);
  1860     double cost_per_card_ms = 0.0;
  1861     if (_pending_cards > 0) {
  1862       cost_per_card_ms = update_rs_time / (double) _pending_cards;
  1863       _cost_per_card_ms_seq->add(cost_per_card_ms);
  1866     double cost_per_scan_only_region_ms = 0.0;
  1867     if (scan_only_regions_scanned > 0.0) {
  1868       cost_per_scan_only_region_ms =
  1869         scan_only_time / scan_only_regions_scanned;
  1870       if (_in_marking_window_im)
  1871         _cost_per_scan_only_region_ms_during_cm_seq->add(cost_per_scan_only_region_ms);
  1872       else
  1873         _cost_per_scan_only_region_ms_seq->add(cost_per_scan_only_region_ms);
  1876     size_t cards_scanned = _g1->cards_scanned();
  1878     double cost_per_entry_ms = 0.0;
  1879     if (cards_scanned > 10) {
  1880       cost_per_entry_ms = scan_rs_time / (double) cards_scanned;
  1881       if (_last_young_gc_full)
  1882         _cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1883       else
  1884         _partially_young_cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1887     if (_max_rs_lengths > 0) {
  1888       double cards_per_entry_ratio =
  1889         (double) cards_scanned / (double) _max_rs_lengths;
  1890       if (_last_young_gc_full)
  1891         _fully_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1892       else
  1893         _partially_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1896     size_t rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
  1897     if (rs_length_diff >= 0)
  1898       _rs_length_diff_seq->add((double) rs_length_diff);
  1900     size_t copied_bytes = surviving_bytes;
  1901     double cost_per_byte_ms = 0.0;
  1902     if (copied_bytes > 0) {
  1903       cost_per_byte_ms = obj_copy_time / (double) copied_bytes;
  1904       if (_in_marking_window)
  1905         _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
  1906       else
  1907         _cost_per_byte_ms_seq->add(cost_per_byte_ms);
  1910     double all_other_time_ms = pause_time_ms -
  1911       (update_rs_time + scan_only_time + scan_rs_time + obj_copy_time +
  1912        _mark_closure_time_ms + termination_time);
  1914     double young_other_time_ms = 0.0;
  1915     if (_recorded_young_regions > 0) {
  1916       young_other_time_ms =
  1917         _recorded_young_cset_choice_time_ms +
  1918         _recorded_young_free_cset_time_ms;
  1919       _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
  1920                                              (double) _recorded_young_regions);
  1922     double non_young_other_time_ms = 0.0;
  1923     if (_recorded_non_young_regions > 0) {
  1924       non_young_other_time_ms =
  1925         _recorded_non_young_cset_choice_time_ms +
  1926         _recorded_non_young_free_cset_time_ms;
  1928       _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
  1929                                          (double) _recorded_non_young_regions);
  1932     double constant_other_time_ms = all_other_time_ms -
  1933       (young_other_time_ms + non_young_other_time_ms);
  1934     _constant_other_time_ms_seq->add(constant_other_time_ms);
  1936     double survival_ratio = 0.0;
  1937     if (_bytes_in_collection_set_before_gc > 0) {
  1938       survival_ratio = (double) bytes_in_to_space_during_gc() /
  1939         (double) _bytes_in_collection_set_before_gc;
  1942     _pending_cards_seq->add((double) _pending_cards);
  1943     _scanned_cards_seq->add((double) cards_scanned);
  1944     _rs_lengths_seq->add((double) _max_rs_lengths);
  1946     double expensive_region_limit_ms =
  1947       (double) G1MaxPauseTimeMS - predict_constant_other_time_ms();
  1948     if (expensive_region_limit_ms < 0.0) {
  1949       // this means that the other time was predicted to be longer than
  1950       // than the max pause time
  1951       expensive_region_limit_ms = (double) G1MaxPauseTimeMS;
  1953     _expensive_region_limit_ms = expensive_region_limit_ms;
  1955     if (PREDICTIONS_VERBOSE) {
  1956       gclog_or_tty->print_cr("");
  1957       gclog_or_tty->print_cr("PREDICTIONS %1.4lf %d "
  1958                     "REGIONS %d %d %d %d "
  1959                     "PENDING_CARDS %d %d "
  1960                     "CARDS_SCANNED %d %d "
  1961                     "RS_LENGTHS %d %d "
  1962                     "SCAN_ONLY_SCAN %1.6lf %1.6lf "
  1963                     "RS_UPDATE %1.6lf %1.6lf RS_SCAN %1.6lf %1.6lf "
  1964                     "SURVIVAL_RATIO %1.6lf %1.6lf "
  1965                     "OBJECT_COPY %1.6lf %1.6lf OTHER_CONSTANT %1.6lf %1.6lf "
  1966                     "OTHER_YOUNG %1.6lf %1.6lf "
  1967                     "OTHER_NON_YOUNG %1.6lf %1.6lf "
  1968                     "VTIME_DIFF %1.6lf TERMINATION %1.6lf "
  1969                     "ELAPSED %1.6lf %1.6lf ",
  1970                     _cur_collection_start_sec,
  1971                     (!_last_young_gc_full) ? 2 :
  1972                     (last_pause_included_initial_mark) ? 1 : 0,
  1973                     _recorded_region_num,
  1974                     _recorded_young_regions,
  1975                     _recorded_scan_only_regions,
  1976                     _recorded_non_young_regions,
  1977                     _predicted_pending_cards, _pending_cards,
  1978                     _predicted_cards_scanned, cards_scanned,
  1979                     _predicted_rs_lengths, _max_rs_lengths,
  1980                     _predicted_scan_only_scan_time_ms, scan_only_time,
  1981                     _predicted_rs_update_time_ms, update_rs_time,
  1982                     _predicted_rs_scan_time_ms, scan_rs_time,
  1983                     _predicted_survival_ratio, survival_ratio,
  1984                     _predicted_object_copy_time_ms, obj_copy_time,
  1985                     _predicted_constant_other_time_ms, constant_other_time_ms,
  1986                     _predicted_young_other_time_ms, young_other_time_ms,
  1987                     _predicted_non_young_other_time_ms,
  1988                     non_young_other_time_ms,
  1989                     _vtime_diff_ms, termination_time,
  1990                     _predicted_pause_time_ms, elapsed_ms);
  1993     if (G1PolicyVerbose > 0) {
  1994       gclog_or_tty->print_cr("Pause Time, predicted: %1.4lfms (predicted %s), actual: %1.4lfms",
  1995                     _predicted_pause_time_ms,
  1996                     (_within_target) ? "within" : "outside",
  1997                     elapsed_ms);
  2002   _in_marking_window = new_in_marking_window;
  2003   _in_marking_window_im = new_in_marking_window_im;
  2004   _free_regions_at_end_of_collection = _g1->free_regions();
  2005   _scan_only_regions_at_end_of_collection = _g1->young_list_length();
  2006   calculate_young_list_min_length();
  2007   calculate_young_list_target_config();
  2009   // </NEW PREDICTION>
  2011   _target_pause_time_ms = -1.0;
  2014 // <NEW PREDICTION>
  2016 double
  2017 G1CollectorPolicy::
  2018 predict_young_collection_elapsed_time_ms(size_t adjustment) {
  2019   guarantee( adjustment == 0 || adjustment == 1, "invariant" );
  2021   G1CollectedHeap* g1h = G1CollectedHeap::heap();
  2022   size_t young_num = g1h->young_list_length();
  2023   if (young_num == 0)
  2024     return 0.0;
  2026   young_num += adjustment;
  2027   size_t pending_cards = predict_pending_cards();
  2028   size_t rs_lengths = g1h->young_list_sampled_rs_lengths() +
  2029                       predict_rs_length_diff();
  2030   size_t card_num;
  2031   if (full_young_gcs())
  2032     card_num = predict_young_card_num(rs_lengths);
  2033   else
  2034     card_num = predict_non_young_card_num(rs_lengths);
  2035   size_t young_byte_size = young_num * HeapRegion::GrainBytes;
  2036   double accum_yg_surv_rate =
  2037     _short_lived_surv_rate_group->accum_surv_rate(adjustment);
  2039   size_t bytes_to_copy =
  2040     (size_t) (accum_yg_surv_rate * (double) HeapRegion::GrainBytes);
  2042   return
  2043     predict_rs_update_time_ms(pending_cards) +
  2044     predict_rs_scan_time_ms(card_num) +
  2045     predict_object_copy_time_ms(bytes_to_copy) +
  2046     predict_young_other_time_ms(young_num) +
  2047     predict_constant_other_time_ms();
  2050 double
  2051 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
  2052   size_t rs_length = predict_rs_length_diff();
  2053   size_t card_num;
  2054   if (full_young_gcs())
  2055     card_num = predict_young_card_num(rs_length);
  2056   else
  2057     card_num = predict_non_young_card_num(rs_length);
  2058   return predict_base_elapsed_time_ms(pending_cards, card_num);
  2061 double
  2062 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
  2063                                                 size_t scanned_cards) {
  2064   return
  2065     predict_rs_update_time_ms(pending_cards) +
  2066     predict_rs_scan_time_ms(scanned_cards) +
  2067     predict_constant_other_time_ms();
  2070 double
  2071 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
  2072                                                   bool young) {
  2073   size_t rs_length = hr->rem_set()->occupied();
  2074   size_t card_num;
  2075   if (full_young_gcs())
  2076     card_num = predict_young_card_num(rs_length);
  2077   else
  2078     card_num = predict_non_young_card_num(rs_length);
  2079   size_t bytes_to_copy = predict_bytes_to_copy(hr);
  2081   double region_elapsed_time_ms =
  2082     predict_rs_scan_time_ms(card_num) +
  2083     predict_object_copy_time_ms(bytes_to_copy);
  2085   if (young)
  2086     region_elapsed_time_ms += predict_young_other_time_ms(1);
  2087   else
  2088     region_elapsed_time_ms += predict_non_young_other_time_ms(1);
  2090   return region_elapsed_time_ms;
  2093 size_t
  2094 G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
  2095   size_t bytes_to_copy;
  2096   if (hr->is_marked())
  2097     bytes_to_copy = hr->max_live_bytes();
  2098   else {
  2099     guarantee( hr->is_young() && hr->age_in_surv_rate_group() != -1,
  2100                "invariant" );
  2101     int age = hr->age_in_surv_rate_group();
  2102     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
  2103     bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
  2106   return bytes_to_copy;
  2109 void
  2110 G1CollectorPolicy::start_recording_regions() {
  2111   _recorded_rs_lengths            = 0;
  2112   _recorded_scan_only_regions     = 0;
  2113   _recorded_young_regions         = 0;
  2114   _recorded_non_young_regions     = 0;
  2116 #if PREDICTIONS_VERBOSE
  2117   _predicted_rs_lengths           = 0;
  2118   _predicted_cards_scanned        = 0;
  2120   _recorded_marked_bytes          = 0;
  2121   _recorded_young_bytes           = 0;
  2122   _predicted_bytes_to_copy        = 0;
  2123 #endif // PREDICTIONS_VERBOSE
  2126 void
  2127 G1CollectorPolicy::record_cset_region(HeapRegion* hr, bool young) {
  2128   if (young) {
  2129     ++_recorded_young_regions;
  2130   } else {
  2131     ++_recorded_non_young_regions;
  2133 #if PREDICTIONS_VERBOSE
  2134   if (young) {
  2135     _recorded_young_bytes += hr->used();
  2136   } else {
  2137     _recorded_marked_bytes += hr->max_live_bytes();
  2139   _predicted_bytes_to_copy += predict_bytes_to_copy(hr);
  2140 #endif // PREDICTIONS_VERBOSE
  2142   size_t rs_length = hr->rem_set()->occupied();
  2143   _recorded_rs_lengths += rs_length;
  2146 void
  2147 G1CollectorPolicy::record_scan_only_regions(size_t scan_only_length) {
  2148   _recorded_scan_only_regions = scan_only_length;
  2151 void
  2152 G1CollectorPolicy::end_recording_regions() {
  2153 #if PREDICTIONS_VERBOSE
  2154   _predicted_pending_cards = predict_pending_cards();
  2155   _predicted_rs_lengths = _recorded_rs_lengths + predict_rs_length_diff();
  2156   if (full_young_gcs())
  2157     _predicted_cards_scanned += predict_young_card_num(_predicted_rs_lengths);
  2158   else
  2159     _predicted_cards_scanned +=
  2160       predict_non_young_card_num(_predicted_rs_lengths);
  2161   _recorded_region_num = _recorded_young_regions + _recorded_non_young_regions;
  2163   _predicted_scan_only_scan_time_ms =
  2164     predict_scan_only_time_ms(_recorded_scan_only_regions);
  2165   _predicted_rs_update_time_ms =
  2166     predict_rs_update_time_ms(_g1->pending_card_num());
  2167   _predicted_rs_scan_time_ms =
  2168     predict_rs_scan_time_ms(_predicted_cards_scanned);
  2169   _predicted_object_copy_time_ms =
  2170     predict_object_copy_time_ms(_predicted_bytes_to_copy);
  2171   _predicted_constant_other_time_ms =
  2172     predict_constant_other_time_ms();
  2173   _predicted_young_other_time_ms =
  2174     predict_young_other_time_ms(_recorded_young_regions);
  2175   _predicted_non_young_other_time_ms =
  2176     predict_non_young_other_time_ms(_recorded_non_young_regions);
  2178   _predicted_pause_time_ms =
  2179     _predicted_scan_only_scan_time_ms +
  2180     _predicted_rs_update_time_ms +
  2181     _predicted_rs_scan_time_ms +
  2182     _predicted_object_copy_time_ms +
  2183     _predicted_constant_other_time_ms +
  2184     _predicted_young_other_time_ms +
  2185     _predicted_non_young_other_time_ms;
  2186 #endif // PREDICTIONS_VERBOSE
  2189 void G1CollectorPolicy::check_if_region_is_too_expensive(double
  2190                                                            predicted_time_ms) {
  2191   // I don't think we need to do this when in young GC mode since
  2192   // marking will be initiated next time we hit the soft limit anyway...
  2193   if (predicted_time_ms > _expensive_region_limit_ms) {
  2194     if (!in_young_gc_mode()) {
  2195         set_full_young_gcs(true);
  2196       _should_initiate_conc_mark = true;
  2197     } else
  2198       // no point in doing another partial one
  2199       _should_revert_to_full_young_gcs = true;
  2203 // </NEW PREDICTION>
  2206 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
  2207                                                double elapsed_ms) {
  2208   _recent_gc_times_ms->add(elapsed_ms);
  2209   _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
  2210   _prev_collection_pause_end_ms = end_time_sec * 1000.0;
  2213 double G1CollectorPolicy::recent_avg_time_for_pauses_ms() {
  2214   if (_recent_pause_times_ms->num() == 0) return (double) G1MaxPauseTimeMS;
  2215   else return _recent_pause_times_ms->avg();
  2218 double G1CollectorPolicy::recent_avg_time_for_CH_strong_ms() {
  2219   if (_recent_CH_strong_roots_times_ms->num() == 0)
  2220     return (double)G1MaxPauseTimeMS/3.0;
  2221   else return _recent_CH_strong_roots_times_ms->avg();
  2224 double G1CollectorPolicy::recent_avg_time_for_G1_strong_ms() {
  2225   if (_recent_G1_strong_roots_times_ms->num() == 0)
  2226     return (double)G1MaxPauseTimeMS/3.0;
  2227   else return _recent_G1_strong_roots_times_ms->avg();
  2230 double G1CollectorPolicy::recent_avg_time_for_evac_ms() {
  2231   if (_recent_evac_times_ms->num() == 0) return (double)G1MaxPauseTimeMS/3.0;
  2232   else return _recent_evac_times_ms->avg();
  2235 int G1CollectorPolicy::number_of_recent_gcs() {
  2236   assert(_recent_CH_strong_roots_times_ms->num() ==
  2237          _recent_G1_strong_roots_times_ms->num(), "Sequence out of sync");
  2238   assert(_recent_G1_strong_roots_times_ms->num() ==
  2239          _recent_evac_times_ms->num(), "Sequence out of sync");
  2240   assert(_recent_evac_times_ms->num() ==
  2241          _recent_pause_times_ms->num(), "Sequence out of sync");
  2242   assert(_recent_pause_times_ms->num() ==
  2243          _recent_CS_bytes_used_before->num(), "Sequence out of sync");
  2244   assert(_recent_CS_bytes_used_before->num() ==
  2245          _recent_CS_bytes_surviving->num(), "Sequence out of sync");
  2246   return _recent_pause_times_ms->num();
  2249 double G1CollectorPolicy::recent_avg_survival_fraction() {
  2250   return recent_avg_survival_fraction_work(_recent_CS_bytes_surviving,
  2251                                            _recent_CS_bytes_used_before);
  2254 double G1CollectorPolicy::last_survival_fraction() {
  2255   return last_survival_fraction_work(_recent_CS_bytes_surviving,
  2256                                      _recent_CS_bytes_used_before);
  2259 double
  2260 G1CollectorPolicy::recent_avg_survival_fraction_work(TruncatedSeq* surviving,
  2261                                                      TruncatedSeq* before) {
  2262   assert(surviving->num() == before->num(), "Sequence out of sync");
  2263   if (before->sum() > 0.0) {
  2264       double recent_survival_rate = surviving->sum() / before->sum();
  2265       // We exempt parallel collection from this check because Alloc Buffer
  2266       // fragmentation can produce negative collections.
  2267       // Further, we're now always doing parallel collection.  But I'm still
  2268       // leaving this here as a placeholder for a more precise assertion later.
  2269       // (DLD, 10/05.)
  2270       assert((true || ParallelGCThreads > 0) ||
  2271              _g1->evacuation_failed() ||
  2272              recent_survival_rate <= 1.0, "Or bad frac");
  2273       return recent_survival_rate;
  2274   } else {
  2275     return 1.0; // Be conservative.
  2279 double
  2280 G1CollectorPolicy::last_survival_fraction_work(TruncatedSeq* surviving,
  2281                                                TruncatedSeq* before) {
  2282   assert(surviving->num() == before->num(), "Sequence out of sync");
  2283   if (surviving->num() > 0 && before->last() > 0.0) {
  2284     double last_survival_rate = surviving->last() / before->last();
  2285     // We exempt parallel collection from this check because Alloc Buffer
  2286     // fragmentation can produce negative collections.
  2287     // Further, we're now always doing parallel collection.  But I'm still
  2288     // leaving this here as a placeholder for a more precise assertion later.
  2289     // (DLD, 10/05.)
  2290     assert((true || ParallelGCThreads > 0) ||
  2291            last_survival_rate <= 1.0, "Or bad frac");
  2292     return last_survival_rate;
  2293   } else {
  2294     return 1.0;
  2298 static const int survival_min_obs = 5;
  2299 static double survival_min_obs_limits[] = { 0.9, 0.7, 0.5, 0.3, 0.1 };
  2300 static const double min_survival_rate = 0.1;
  2302 double
  2303 G1CollectorPolicy::conservative_avg_survival_fraction_work(double avg,
  2304                                                            double latest) {
  2305   double res = avg;
  2306   if (number_of_recent_gcs() < survival_min_obs) {
  2307     res = MAX2(res, survival_min_obs_limits[number_of_recent_gcs()]);
  2309   res = MAX2(res, latest);
  2310   res = MAX2(res, min_survival_rate);
  2311   // In the parallel case, LAB fragmentation can produce "negative
  2312   // collections"; so can evac failure.  Cap at 1.0
  2313   res = MIN2(res, 1.0);
  2314   return res;
  2317 size_t G1CollectorPolicy::expansion_amount() {
  2318   if ((int)(recent_avg_pause_time_ratio() * 100.0) > G1GCPct) {
  2319     // We will double the existing space, or take G1ExpandByPctOfAvail % of
  2320     // the available expansion space, whichever is smaller, bounded below
  2321     // by a minimum expansion (unless that's all that's left.)
  2322     const size_t min_expand_bytes = 1*M;
  2323     size_t reserved_bytes = _g1->g1_reserved_obj_bytes();
  2324     size_t committed_bytes = _g1->capacity();
  2325     size_t uncommitted_bytes = reserved_bytes - committed_bytes;
  2326     size_t expand_bytes;
  2327     size_t expand_bytes_via_pct =
  2328       uncommitted_bytes * G1ExpandByPctOfAvail / 100;
  2329     expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
  2330     expand_bytes = MAX2(expand_bytes, min_expand_bytes);
  2331     expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
  2332     if (G1PolicyVerbose > 1) {
  2333       gclog_or_tty->print("Decided to expand: ratio = %5.2f, "
  2334                  "committed = %d%s, uncommited = %d%s, via pct = %d%s.\n"
  2335                  "                   Answer = %d.\n",
  2336                  recent_avg_pause_time_ratio(),
  2337                  byte_size_in_proper_unit(committed_bytes),
  2338                  proper_unit_for_byte_size(committed_bytes),
  2339                  byte_size_in_proper_unit(uncommitted_bytes),
  2340                  proper_unit_for_byte_size(uncommitted_bytes),
  2341                  byte_size_in_proper_unit(expand_bytes_via_pct),
  2342                  proper_unit_for_byte_size(expand_bytes_via_pct),
  2343                  byte_size_in_proper_unit(expand_bytes),
  2344                  proper_unit_for_byte_size(expand_bytes));
  2346     return expand_bytes;
  2347   } else {
  2348     return 0;
  2352 void G1CollectorPolicy::note_start_of_mark_thread() {
  2353   _mark_thread_startup_sec = os::elapsedTime();
  2356 class CountCSClosure: public HeapRegionClosure {
  2357   G1CollectorPolicy* _g1_policy;
  2358 public:
  2359   CountCSClosure(G1CollectorPolicy* g1_policy) :
  2360     _g1_policy(g1_policy) {}
  2361   bool doHeapRegion(HeapRegion* r) {
  2362     _g1_policy->_bytes_in_collection_set_before_gc += r->used();
  2363     return false;
  2365 };
  2367 void G1CollectorPolicy::count_CS_bytes_used() {
  2368   CountCSClosure cs_closure(this);
  2369   _g1->collection_set_iterate(&cs_closure);
  2372 static void print_indent(int level) {
  2373   for (int j = 0; j < level+1; ++j)
  2374     gclog_or_tty->print("   ");
  2377 void G1CollectorPolicy::print_summary (int level,
  2378                                        const char* str,
  2379                                        NumberSeq* seq) const {
  2380   double sum = seq->sum();
  2381   print_indent(level);
  2382   gclog_or_tty->print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
  2383                 str, sum / 1000.0, seq->avg());
  2386 void G1CollectorPolicy::print_summary_sd (int level,
  2387                                           const char* str,
  2388                                           NumberSeq* seq) const {
  2389   print_summary(level, str, seq);
  2390   print_indent(level + 5);
  2391   gclog_or_tty->print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
  2392                 seq->num(), seq->sd(), seq->maximum());
  2395 void G1CollectorPolicy::check_other_times(int level,
  2396                                         NumberSeq* other_times_ms,
  2397                                         NumberSeq* calc_other_times_ms) const {
  2398   bool should_print = false;
  2400   double max_sum = MAX2(fabs(other_times_ms->sum()),
  2401                         fabs(calc_other_times_ms->sum()));
  2402   double min_sum = MIN2(fabs(other_times_ms->sum()),
  2403                         fabs(calc_other_times_ms->sum()));
  2404   double sum_ratio = max_sum / min_sum;
  2405   if (sum_ratio > 1.1) {
  2406     should_print = true;
  2407     print_indent(level + 1);
  2408     gclog_or_tty->print_cr("## CALCULATED OTHER SUM DOESN'T MATCH RECORDED ###");
  2411   double max_avg = MAX2(fabs(other_times_ms->avg()),
  2412                         fabs(calc_other_times_ms->avg()));
  2413   double min_avg = MIN2(fabs(other_times_ms->avg()),
  2414                         fabs(calc_other_times_ms->avg()));
  2415   double avg_ratio = max_avg / min_avg;
  2416   if (avg_ratio > 1.1) {
  2417     should_print = true;
  2418     print_indent(level + 1);
  2419     gclog_or_tty->print_cr("## CALCULATED OTHER AVG DOESN'T MATCH RECORDED ###");
  2422   if (other_times_ms->sum() < -0.01) {
  2423     print_indent(level + 1);
  2424     gclog_or_tty->print_cr("## RECORDED OTHER SUM IS NEGATIVE ###");
  2427   if (other_times_ms->avg() < -0.01) {
  2428     print_indent(level + 1);
  2429     gclog_or_tty->print_cr("## RECORDED OTHER AVG IS NEGATIVE ###");
  2432   if (calc_other_times_ms->sum() < -0.01) {
  2433     should_print = true;
  2434     print_indent(level + 1);
  2435     gclog_or_tty->print_cr("## CALCULATED OTHER SUM IS NEGATIVE ###");
  2438   if (calc_other_times_ms->avg() < -0.01) {
  2439     should_print = true;
  2440     print_indent(level + 1);
  2441     gclog_or_tty->print_cr("## CALCULATED OTHER AVG IS NEGATIVE ###");
  2444   if (should_print)
  2445     print_summary(level, "Other(Calc)", calc_other_times_ms);
  2448 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
  2449   bool parallel = ParallelGCThreads > 0;
  2450   MainBodySummary*    body_summary = summary->main_body_summary();
  2451   PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
  2453   if (summary->get_total_seq()->num() > 0) {
  2454     print_summary_sd(0,
  2455                      (preamble_summary == NULL) ? "Non-Popular Pauses" :
  2456                      "Popular Pauses",
  2457                      summary->get_total_seq());
  2458     if (preamble_summary != NULL) {
  2459       print_summary(1, "Popularity Preamble",
  2460                     preamble_summary->get_pop_preamble_seq());
  2461       print_summary(2, "Update RS", preamble_summary->get_pop_update_rs_seq());
  2462       print_summary(2, "Scan RS", preamble_summary->get_pop_scan_rs_seq());
  2463       print_summary(2, "Closure App",
  2464                     preamble_summary->get_pop_closure_app_seq());
  2465       print_summary(2, "Evacuation",
  2466                     preamble_summary->get_pop_evacuation_seq());
  2467       print_summary(2, "Other", preamble_summary->get_pop_other_seq());
  2469         NumberSeq* other_parts[] = {
  2470           preamble_summary->get_pop_update_rs_seq(),
  2471           preamble_summary->get_pop_scan_rs_seq(),
  2472           preamble_summary->get_pop_closure_app_seq(),
  2473           preamble_summary->get_pop_evacuation_seq()
  2474         };
  2475         NumberSeq calc_other_times_ms(preamble_summary->get_pop_preamble_seq(),
  2476                                       4, other_parts);
  2477         check_other_times(2, preamble_summary->get_pop_other_seq(),
  2478                           &calc_other_times_ms);
  2481     if (body_summary != NULL) {
  2482       print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
  2483       if (parallel) {
  2484         print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
  2485         print_summary(2, "Update RS", body_summary->get_update_rs_seq());
  2486         print_summary(2, "Ext Root Scanning",
  2487                       body_summary->get_ext_root_scan_seq());
  2488         print_summary(2, "Mark Stack Scanning",
  2489                       body_summary->get_mark_stack_scan_seq());
  2490         print_summary(2, "Scan-Only Scanning",
  2491                       body_summary->get_scan_only_seq());
  2492         print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
  2493         print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
  2494         print_summary(2, "Termination", body_summary->get_termination_seq());
  2495         print_summary(2, "Other", body_summary->get_parallel_other_seq());
  2497           NumberSeq* other_parts[] = {
  2498             body_summary->get_update_rs_seq(),
  2499             body_summary->get_ext_root_scan_seq(),
  2500             body_summary->get_mark_stack_scan_seq(),
  2501             body_summary->get_scan_only_seq(),
  2502             body_summary->get_scan_rs_seq(),
  2503             body_summary->get_obj_copy_seq(),
  2504             body_summary->get_termination_seq()
  2505           };
  2506           NumberSeq calc_other_times_ms(body_summary->get_parallel_seq(),
  2507                                         7, other_parts);
  2508           check_other_times(2, body_summary->get_parallel_other_seq(),
  2509                             &calc_other_times_ms);
  2511         print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
  2512         print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
  2513       } else {
  2514         print_summary(1, "Update RS", body_summary->get_update_rs_seq());
  2515         print_summary(1, "Ext Root Scanning",
  2516                       body_summary->get_ext_root_scan_seq());
  2517         print_summary(1, "Mark Stack Scanning",
  2518                       body_summary->get_mark_stack_scan_seq());
  2519         print_summary(1, "Scan-Only Scanning",
  2520                       body_summary->get_scan_only_seq());
  2521         print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
  2522         print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
  2525     print_summary(1, "Other", summary->get_other_seq());
  2527       NumberSeq calc_other_times_ms;
  2528       if (body_summary != NULL) {
  2529         // not abandoned
  2530         if (parallel) {
  2531           // parallel
  2532           NumberSeq* other_parts[] = {
  2533             body_summary->get_satb_drain_seq(),
  2534             (preamble_summary == NULL) ? NULL :
  2535               preamble_summary->get_pop_preamble_seq(),
  2536             body_summary->get_parallel_seq(),
  2537             body_summary->get_clear_ct_seq()
  2538           };
  2539           calc_other_times_ms = NumberSeq (summary->get_total_seq(),
  2540                                           4, other_parts);
  2541         } else {
  2542           // serial
  2543           NumberSeq* other_parts[] = {
  2544             body_summary->get_satb_drain_seq(),
  2545             (preamble_summary == NULL) ? NULL :
  2546               preamble_summary->get_pop_preamble_seq(),
  2547             body_summary->get_update_rs_seq(),
  2548             body_summary->get_ext_root_scan_seq(),
  2549             body_summary->get_mark_stack_scan_seq(),
  2550             body_summary->get_scan_only_seq(),
  2551             body_summary->get_scan_rs_seq(),
  2552             body_summary->get_obj_copy_seq()
  2553           };
  2554           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2555                                           8, other_parts);
  2557       } else {
  2558         // abandoned
  2559         NumberSeq* other_parts[] = {
  2560           (preamble_summary == NULL) ? NULL :
  2561             preamble_summary->get_pop_preamble_seq()
  2562         };
  2563         calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2564                                         1, other_parts);
  2566       check_other_times(1,  summary->get_other_seq(), &calc_other_times_ms);
  2568   } else {
  2569     print_indent(0);
  2570     gclog_or_tty->print_cr("none");
  2572   gclog_or_tty->print_cr("");
  2575 void
  2576 G1CollectorPolicy::print_abandoned_summary(PauseSummary* non_pop_summary,
  2577                                            PauseSummary* pop_summary) const {
  2578   bool printed = false;
  2579   if (non_pop_summary->get_total_seq()->num() > 0) {
  2580     printed = true;
  2581     print_summary(non_pop_summary);
  2583   if (pop_summary->get_total_seq()->num() > 0) {
  2584     printed = true;
  2585     print_summary(pop_summary);
  2588   if (!printed) {
  2589     print_indent(0);
  2590     gclog_or_tty->print_cr("none");
  2591     gclog_or_tty->print_cr("");
  2595 void G1CollectorPolicy::print_tracing_info() const {
  2596   if (TraceGen0Time) {
  2597     gclog_or_tty->print_cr("ALL PAUSES");
  2598     print_summary_sd(0, "Total", _all_pause_times_ms);
  2599     gclog_or_tty->print_cr("");
  2600     gclog_or_tty->print_cr("");
  2601     gclog_or_tty->print_cr("   Full Young GC Pauses:    %8d", _full_young_pause_num);
  2602     gclog_or_tty->print_cr("   Partial Young GC Pauses: %8d", _partial_young_pause_num);
  2603     gclog_or_tty->print_cr("");
  2605     gclog_or_tty->print_cr("NON-POPULAR PAUSES");
  2606     print_summary(_non_pop_summary);
  2608     gclog_or_tty->print_cr("POPULAR PAUSES");
  2609     print_summary(_pop_summary);
  2611     gclog_or_tty->print_cr("ABANDONED PAUSES");
  2612     print_abandoned_summary(_non_pop_abandoned_summary,
  2613                             _pop_abandoned_summary);
  2615     gclog_or_tty->print_cr("MISC");
  2616     print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
  2617     print_summary_sd(0, "Yields", _all_yield_times_ms);
  2618     for (int i = 0; i < _aux_num; ++i) {
  2619       if (_all_aux_times_ms[i].num() > 0) {
  2620         char buffer[96];
  2621         sprintf(buffer, "Aux%d", i);
  2622         print_summary_sd(0, buffer, &_all_aux_times_ms[i]);
  2626     size_t all_region_num = _region_num_young + _region_num_tenured;
  2627     gclog_or_tty->print_cr("   New Regions %8d, Young %8d (%6.2lf%%), "
  2628                "Tenured %8d (%6.2lf%%)",
  2629                all_region_num,
  2630                _region_num_young,
  2631                (double) _region_num_young / (double) all_region_num * 100.0,
  2632                _region_num_tenured,
  2633                (double) _region_num_tenured / (double) all_region_num * 100.0);
  2635     if (!G1RSBarrierUseQueue) {
  2636       gclog_or_tty->print_cr("Of %d times conc refinement was enabled, %d (%7.2f%%) "
  2637                     "did zero traversals.",
  2638                     _conc_refine_enabled, _conc_refine_zero_traversals,
  2639                     _conc_refine_enabled > 0 ?
  2640                     100.0 * (float)_conc_refine_zero_traversals/
  2641                     (float)_conc_refine_enabled : 0.0);
  2642       gclog_or_tty->print_cr("  Max # of traversals = %d.",
  2643                     _conc_refine_max_traversals);
  2644       gclog_or_tty->print_cr("");
  2647   if (TraceGen1Time) {
  2648     if (_all_full_gc_times_ms->num() > 0) {
  2649       gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
  2650                  _all_full_gc_times_ms->num(),
  2651                  _all_full_gc_times_ms->sum() / 1000.0);
  2652       gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times_ms->avg());
  2653       gclog_or_tty->print_cr("                     [std. dev = %8.2f ms, max = %8.2f ms]",
  2654                     _all_full_gc_times_ms->sd(),
  2655                     _all_full_gc_times_ms->maximum());
  2660 void G1CollectorPolicy::print_yg_surv_rate_info() const {
  2661 #ifndef PRODUCT
  2662   _short_lived_surv_rate_group->print_surv_rate_summary();
  2663   // add this call for any other surv rate groups
  2664 #endif // PRODUCT
  2667 void G1CollectorPolicy::update_conc_refine_data() {
  2668   unsigned traversals = _g1->concurrent_g1_refine()->disable();
  2669   if (traversals == 0) _conc_refine_zero_traversals++;
  2670   _conc_refine_max_traversals = MAX2(_conc_refine_max_traversals,
  2671                                      (size_t)traversals);
  2673   if (G1PolicyVerbose > 1)
  2674     gclog_or_tty->print_cr("Did a CR traversal series: %d traversals.", traversals);
  2675   double multiplier = 1.0;
  2676   if (traversals == 0) {
  2677     multiplier = 4.0;
  2678   } else if (traversals > (size_t)G1ConcRefineTargTraversals) {
  2679     multiplier = 1.0/1.5;
  2680   } else if (traversals < (size_t)G1ConcRefineTargTraversals) {
  2681     multiplier = 1.5;
  2683   if (G1PolicyVerbose > 1) {
  2684     gclog_or_tty->print_cr("  Multiplier = %7.2f.", multiplier);
  2685     gclog_or_tty->print("  Delta went from %d regions to ",
  2686                _conc_refine_current_delta);
  2688   _conc_refine_current_delta =
  2689     MIN2(_g1->n_regions(),
  2690          (size_t)(_conc_refine_current_delta * multiplier));
  2691   _conc_refine_current_delta =
  2692     MAX2(_conc_refine_current_delta, (size_t)1);
  2693   if (G1PolicyVerbose > 1) {
  2694     gclog_or_tty->print_cr("%d regions.", _conc_refine_current_delta);
  2696   _conc_refine_enabled++;
  2699 void G1CollectorPolicy::set_single_region_collection_set(HeapRegion* hr) {
  2700   assert(collection_set() == NULL, "Must be no current CS.");
  2701   _collection_set_size = 0;
  2702   _collection_set_bytes_used_before = 0;
  2703   add_to_collection_set(hr);
  2704   count_CS_bytes_used();
  2707 bool
  2708 G1CollectorPolicy::should_add_next_region_to_young_list() {
  2709   assert(in_young_gc_mode(), "should be in young GC mode");
  2710   bool ret;
  2711   size_t young_list_length = _g1->young_list_length();
  2712   size_t young_list_max_length = _young_list_target_length;
  2713   if (G1FixedEdenSize) {
  2714     young_list_max_length -= _max_survivor_regions;
  2716   if (young_list_length < young_list_max_length) {
  2717     ret = true;
  2718     ++_region_num_young;
  2719   } else {
  2720     ret = false;
  2721     ++_region_num_tenured;
  2724   return ret;
  2727 #ifndef PRODUCT
  2728 // for debugging, bit of a hack...
  2729 static char*
  2730 region_num_to_mbs(int length) {
  2731   static char buffer[64];
  2732   double bytes = (double) (length * HeapRegion::GrainBytes);
  2733   double mbs = bytes / (double) (1024 * 1024);
  2734   sprintf(buffer, "%7.2lfMB", mbs);
  2735   return buffer;
  2737 #endif // PRODUCT
  2739 void
  2740 G1CollectorPolicy::checkpoint_conc_overhead() {
  2741   double conc_overhead = 0.0;
  2742   if (G1AccountConcurrentOverhead)
  2743     conc_overhead = COTracker::totalPredConcOverhead();
  2744   _mmu_tracker->update_conc_overhead(conc_overhead);
  2745 #if 0
  2746   gclog_or_tty->print(" CO %1.4lf TARGET %1.4lf",
  2747              conc_overhead, _mmu_tracker->max_gc_time());
  2748 #endif
  2752 size_t G1CollectorPolicy::max_regions(int purpose) {
  2753   switch (purpose) {
  2754     case GCAllocForSurvived:
  2755       return _max_survivor_regions;
  2756     case GCAllocForTenured:
  2757       return REGIONS_UNLIMITED;
  2758     default:
  2759       ShouldNotReachHere();
  2760       return REGIONS_UNLIMITED;
  2761   };
  2764 // Calculates survivor space parameters.
  2765 void G1CollectorPolicy::calculate_survivors_policy()
  2767   if (!G1UseSurvivorSpace) {
  2768     return;
  2770   if (G1FixedSurvivorSpaceSize == 0) {
  2771     _max_survivor_regions = _young_list_target_length / SurvivorRatio;
  2772   } else {
  2773     _max_survivor_regions = G1FixedSurvivorSpaceSize;
  2776   if (G1FixedTenuringThreshold) {
  2777     _tenuring_threshold = MaxTenuringThreshold;
  2778   } else {
  2779     _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
  2780         HeapRegion::GrainWords * _max_survivor_regions);
  2785 void
  2786 G1CollectorPolicy_BestRegionsFirst::
  2787 set_single_region_collection_set(HeapRegion* hr) {
  2788   G1CollectorPolicy::set_single_region_collection_set(hr);
  2789   _collectionSetChooser->removeRegion(hr);
  2793 bool
  2794 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
  2795                                                                word_size) {
  2796   assert(_g1->regions_accounted_for(), "Region leakage!");
  2797   // Initiate a pause when we reach the steady-state "used" target.
  2798   size_t used_hard = (_g1->capacity() / 100) * G1SteadyStateUsed;
  2799   size_t used_soft =
  2800    MAX2((_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta),
  2801         used_hard/2);
  2802   size_t used = _g1->used();
  2804   double max_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
  2806   size_t young_list_length = _g1->young_list_length();
  2807   size_t young_list_max_length = _young_list_target_length;
  2808   if (G1FixedEdenSize) {
  2809     young_list_max_length -= _max_survivor_regions;
  2811   bool reached_target_length = young_list_length >= young_list_max_length;
  2813   if (in_young_gc_mode()) {
  2814     if (reached_target_length) {
  2815       assert( young_list_length > 0 && _g1->young_list_length() > 0,
  2816               "invariant" );
  2817       _target_pause_time_ms = max_pause_time_ms;
  2818       return true;
  2820   } else {
  2821     guarantee( false, "should not reach here" );
  2824   return false;
  2827 #ifndef PRODUCT
  2828 class HRSortIndexIsOKClosure: public HeapRegionClosure {
  2829   CollectionSetChooser* _chooser;
  2830 public:
  2831   HRSortIndexIsOKClosure(CollectionSetChooser* chooser) :
  2832     _chooser(chooser) {}
  2834   bool doHeapRegion(HeapRegion* r) {
  2835     if (!r->continuesHumongous()) {
  2836       assert(_chooser->regionProperlyOrdered(r), "Ought to be.");
  2838     return false;
  2840 };
  2842 bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() {
  2843   HRSortIndexIsOKClosure cl(_collectionSetChooser);
  2844   _g1->heap_region_iterate(&cl);
  2845   return true;
  2847 #endif
  2849 void
  2850 G1CollectorPolicy_BestRegionsFirst::
  2851 record_collection_pause_start(double start_time_sec, size_t start_used) {
  2852   G1CollectorPolicy::record_collection_pause_start(start_time_sec, start_used);
  2855 class NextNonCSElemFinder: public HeapRegionClosure {
  2856   HeapRegion* _res;
  2857 public:
  2858   NextNonCSElemFinder(): _res(NULL) {}
  2859   bool doHeapRegion(HeapRegion* r) {
  2860     if (!r->in_collection_set()) {
  2861       _res = r;
  2862       return true;
  2863     } else {
  2864       return false;
  2867   HeapRegion* res() { return _res; }
  2868 };
  2870 class KnownGarbageClosure: public HeapRegionClosure {
  2871   CollectionSetChooser* _hrSorted;
  2873 public:
  2874   KnownGarbageClosure(CollectionSetChooser* hrSorted) :
  2875     _hrSorted(hrSorted)
  2876   {}
  2878   bool doHeapRegion(HeapRegion* r) {
  2879     // We only include humongous regions in collection
  2880     // sets when concurrent mark shows that their contained object is
  2881     // unreachable.
  2883     // Do we have any marking information for this region?
  2884     if (r->is_marked()) {
  2885       // We don't include humongous regions in collection
  2886       // sets because we collect them immediately at the end of a marking
  2887       // cycle.  We also don't include young regions because we *must*
  2888       // include them in the next collection pause.
  2889       if (!r->isHumongous() && !r->is_young()) {
  2890         _hrSorted->addMarkedHeapRegion(r);
  2893     return false;
  2895 };
  2897 class ParKnownGarbageHRClosure: public HeapRegionClosure {
  2898   CollectionSetChooser* _hrSorted;
  2899   jint _marked_regions_added;
  2900   jint _chunk_size;
  2901   jint _cur_chunk_idx;
  2902   jint _cur_chunk_end; // Cur chunk [_cur_chunk_idx, _cur_chunk_end)
  2903   int _worker;
  2904   int _invokes;
  2906   void get_new_chunk() {
  2907     _cur_chunk_idx = _hrSorted->getParMarkedHeapRegionChunk(_chunk_size);
  2908     _cur_chunk_end = _cur_chunk_idx + _chunk_size;
  2910   void add_region(HeapRegion* r) {
  2911     if (_cur_chunk_idx == _cur_chunk_end) {
  2912       get_new_chunk();
  2914     assert(_cur_chunk_idx < _cur_chunk_end, "postcondition");
  2915     _hrSorted->setMarkedHeapRegion(_cur_chunk_idx, r);
  2916     _marked_regions_added++;
  2917     _cur_chunk_idx++;
  2920 public:
  2921   ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
  2922                            jint chunk_size,
  2923                            int worker) :
  2924     _hrSorted(hrSorted), _chunk_size(chunk_size), _worker(worker),
  2925     _marked_regions_added(0), _cur_chunk_idx(0), _cur_chunk_end(0),
  2926     _invokes(0)
  2927   {}
  2929   bool doHeapRegion(HeapRegion* r) {
  2930     // We only include humongous regions in collection
  2931     // sets when concurrent mark shows that their contained object is
  2932     // unreachable.
  2933     _invokes++;
  2935     // Do we have any marking information for this region?
  2936     if (r->is_marked()) {
  2937       // We don't include humongous regions in collection
  2938       // sets because we collect them immediately at the end of a marking
  2939       // cycle.
  2940       // We also do not include young regions in collection sets
  2941       if (!r->isHumongous() && !r->is_young()) {
  2942         add_region(r);
  2945     return false;
  2947   jint marked_regions_added() { return _marked_regions_added; }
  2948   int invokes() { return _invokes; }
  2949 };
  2951 class ParKnownGarbageTask: public AbstractGangTask {
  2952   CollectionSetChooser* _hrSorted;
  2953   jint _chunk_size;
  2954   G1CollectedHeap* _g1;
  2955 public:
  2956   ParKnownGarbageTask(CollectionSetChooser* hrSorted, jint chunk_size) :
  2957     AbstractGangTask("ParKnownGarbageTask"),
  2958     _hrSorted(hrSorted), _chunk_size(chunk_size),
  2959     _g1(G1CollectedHeap::heap())
  2960   {}
  2962   void work(int i) {
  2963     ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size, i);
  2964     // Back to zero for the claim value.
  2965     _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, i,
  2966                                          HeapRegion::InitialClaimValue);
  2967     jint regions_added = parKnownGarbageCl.marked_regions_added();
  2968     _hrSorted->incNumMarkedHeapRegions(regions_added);
  2969     if (G1PrintParCleanupStats) {
  2970       gclog_or_tty->print("     Thread %d called %d times, added %d regions to list.\n",
  2971                  i, parKnownGarbageCl.invokes(), regions_added);
  2974 };
  2976 void
  2977 G1CollectorPolicy_BestRegionsFirst::
  2978 record_concurrent_mark_cleanup_end(size_t freed_bytes,
  2979                                    size_t max_live_bytes) {
  2980   double start;
  2981   if (G1PrintParCleanupStats) start = os::elapsedTime();
  2982   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  2984   _collectionSetChooser->clearMarkedHeapRegions();
  2985   double clear_marked_end;
  2986   if (G1PrintParCleanupStats) {
  2987     clear_marked_end = os::elapsedTime();
  2988     gclog_or_tty->print_cr("  clear marked regions + work1: %8.3f ms.",
  2989                   (clear_marked_end - start)*1000.0);
  2991   if (ParallelGCThreads > 0) {
  2992     const size_t OverpartitionFactor = 4;
  2993     const size_t MinChunkSize = 8;
  2994     const size_t ChunkSize =
  2995       MAX2(_g1->n_regions() / (ParallelGCThreads * OverpartitionFactor),
  2996            MinChunkSize);
  2997     _collectionSetChooser->prepareForAddMarkedHeapRegionsPar(_g1->n_regions(),
  2998                                                              ChunkSize);
  2999     ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
  3000                                             (int) ChunkSize);
  3001     _g1->workers()->run_task(&parKnownGarbageTask);
  3003     assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  3004            "sanity check");
  3005   } else {
  3006     KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
  3007     _g1->heap_region_iterate(&knownGarbagecl);
  3009   double known_garbage_end;
  3010   if (G1PrintParCleanupStats) {
  3011     known_garbage_end = os::elapsedTime();
  3012     gclog_or_tty->print_cr("  compute known garbage: %8.3f ms.",
  3013                   (known_garbage_end - clear_marked_end)*1000.0);
  3015   _collectionSetChooser->sortMarkedHeapRegions();
  3016   double sort_end;
  3017   if (G1PrintParCleanupStats) {
  3018     sort_end = os::elapsedTime();
  3019     gclog_or_tty->print_cr("  sorting: %8.3f ms.",
  3020                   (sort_end - known_garbage_end)*1000.0);
  3023   record_concurrent_mark_cleanup_end_work2();
  3024   double work2_end;
  3025   if (G1PrintParCleanupStats) {
  3026     work2_end = os::elapsedTime();
  3027     gclog_or_tty->print_cr("  work2: %8.3f ms.",
  3028                   (work2_end - sort_end)*1000.0);
  3032 // Add the heap region to the collection set and return the conservative
  3033 // estimate of the number of live bytes.
  3034 void G1CollectorPolicy::
  3035 add_to_collection_set(HeapRegion* hr) {
  3036   if (G1TraceRegions) {
  3037     gclog_or_tty->print_cr("added region to cset %d:["PTR_FORMAT", "PTR_FORMAT"], "
  3038                   "top "PTR_FORMAT", young %s",
  3039                   hr->hrs_index(), hr->bottom(), hr->end(),
  3040                   hr->top(), (hr->is_young()) ? "YES" : "NO");
  3043   if (_g1->mark_in_progress())
  3044     _g1->concurrent_mark()->registerCSetRegion(hr);
  3046   assert(!hr->in_collection_set(),
  3047               "should not already be in the CSet");
  3048   hr->set_in_collection_set(true);
  3049   hr->set_next_in_collection_set(_collection_set);
  3050   _collection_set = hr;
  3051   _collection_set_size++;
  3052   _collection_set_bytes_used_before += hr->used();
  3053   _g1->register_region_with_in_cset_fast_test(hr);
  3056 void
  3057 G1CollectorPolicy_BestRegionsFirst::
  3058 choose_collection_set(HeapRegion* pop_region) {
  3059   double non_young_start_time_sec;
  3060   start_recording_regions();
  3062   if (pop_region != NULL) {
  3063     _target_pause_time_ms = (double) G1MaxPauseTimeMS;
  3064   } else {
  3065     guarantee(_target_pause_time_ms > -1.0,
  3066               "_target_pause_time_ms should have been set!");
  3069   // pop region is either null (and so is CS), or else it *is* the CS.
  3070   assert(_collection_set == pop_region, "Precondition");
  3072   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
  3073   double predicted_pause_time_ms = base_time_ms;
  3075   double target_time_ms = _target_pause_time_ms;
  3076   double time_remaining_ms = target_time_ms - base_time_ms;
  3078   // the 10% and 50% values are arbitrary...
  3079   if (time_remaining_ms < 0.10*target_time_ms) {
  3080     time_remaining_ms = 0.50 * target_time_ms;
  3081     _within_target = false;
  3082   } else {
  3083     _within_target = true;
  3086   // We figure out the number of bytes available for future to-space.
  3087   // For new regions without marking information, we must assume the
  3088   // worst-case of complete survival.  If we have marking information for a
  3089   // region, we can bound the amount of live data.  We can add a number of
  3090   // such regions, as long as the sum of the live data bounds does not
  3091   // exceed the available evacuation space.
  3092   size_t max_live_bytes = _g1->free_regions() * HeapRegion::GrainBytes;
  3094   size_t expansion_bytes =
  3095     _g1->expansion_regions() * HeapRegion::GrainBytes;
  3097   if (pop_region == NULL) {
  3098     _collection_set_bytes_used_before = 0;
  3099     _collection_set_size = 0;
  3102   // Adjust for expansion and slop.
  3103   max_live_bytes = max_live_bytes + expansion_bytes;
  3105   assert(pop_region != NULL || _g1->regions_accounted_for(), "Region leakage!");
  3107   HeapRegion* hr;
  3108   if (in_young_gc_mode()) {
  3109     double young_start_time_sec = os::elapsedTime();
  3111     if (G1PolicyVerbose > 0) {
  3112       gclog_or_tty->print_cr("Adding %d young regions to the CSet",
  3113                     _g1->young_list_length());
  3115     _young_cset_length  = 0;
  3116     _last_young_gc_full = full_young_gcs() ? true : false;
  3117     if (_last_young_gc_full)
  3118       ++_full_young_pause_num;
  3119     else
  3120       ++_partial_young_pause_num;
  3121     hr = _g1->pop_region_from_young_list();
  3122     while (hr != NULL) {
  3124       assert( hr->young_index_in_cset() == -1, "invariant" );
  3125       assert( hr->age_in_surv_rate_group() != -1, "invariant" );
  3126       hr->set_young_index_in_cset((int) _young_cset_length);
  3128       ++_young_cset_length;
  3129       double predicted_time_ms = predict_region_elapsed_time_ms(hr, true);
  3130       time_remaining_ms -= predicted_time_ms;
  3131       predicted_pause_time_ms += predicted_time_ms;
  3132       if (hr == pop_region) {
  3133         // The popular region was young.  Skip over it.
  3134         assert(hr->in_collection_set(), "It's the pop region.");
  3135       } else {
  3136         assert(!hr->in_collection_set(), "It's not the pop region.");
  3137         add_to_collection_set(hr);
  3138         record_cset_region(hr, true);
  3140       max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  3141       if (G1PolicyVerbose > 0) {
  3142         gclog_or_tty->print_cr("  Added [" PTR_FORMAT ", " PTR_FORMAT") to CS.",
  3143                       hr->bottom(), hr->end());
  3144         gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  3145                       max_live_bytes/K);
  3147       hr = _g1->pop_region_from_young_list();
  3150     record_scan_only_regions(_g1->young_list_scan_only_length());
  3152     double young_end_time_sec = os::elapsedTime();
  3153     _recorded_young_cset_choice_time_ms =
  3154       (young_end_time_sec - young_start_time_sec) * 1000.0;
  3156     non_young_start_time_sec = os::elapsedTime();
  3158     if (_young_cset_length > 0 && _last_young_gc_full) {
  3159       // don't bother adding more regions...
  3160       goto choose_collection_set_end;
  3162   } else if (pop_region != NULL) {
  3163     // We're not in young mode, and we chose a popular region; don't choose
  3164     // any more.
  3165     return;
  3168   if (!in_young_gc_mode() || !full_young_gcs()) {
  3169     bool should_continue = true;
  3170     NumberSeq seq;
  3171     double avg_prediction = 100000000000000000.0; // something very large
  3172     do {
  3173       hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
  3174                                                       avg_prediction);
  3175       if (hr != NULL && !hr->popular()) {
  3176         double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
  3177         time_remaining_ms -= predicted_time_ms;
  3178         predicted_pause_time_ms += predicted_time_ms;
  3179         add_to_collection_set(hr);
  3180         record_cset_region(hr, false);
  3181         max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  3182         if (G1PolicyVerbose > 0) {
  3183           gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  3184                         max_live_bytes/K);
  3186         seq.add(predicted_time_ms);
  3187         avg_prediction = seq.avg() + seq.sd();
  3189       should_continue =
  3190         ( hr != NULL) &&
  3191         ( (adaptive_young_list_length()) ? time_remaining_ms > 0.0
  3192           : _collection_set_size < _young_list_fixed_length );
  3193     } while (should_continue);
  3195     if (!adaptive_young_list_length() &&
  3196         _collection_set_size < _young_list_fixed_length)
  3197       _should_revert_to_full_young_gcs  = true;
  3200 choose_collection_set_end:
  3201   count_CS_bytes_used();
  3203   end_recording_regions();
  3205   double non_young_end_time_sec = os::elapsedTime();
  3206   _recorded_non_young_cset_choice_time_ms =
  3207     (non_young_end_time_sec - non_young_start_time_sec) * 1000.0;
  3210 void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() {
  3211   G1CollectorPolicy::record_full_collection_end();
  3212   _collectionSetChooser->updateAfterFullCollection();
  3215 void G1CollectorPolicy_BestRegionsFirst::
  3216 expand_if_possible(size_t numRegions) {
  3217   size_t expansion_bytes = numRegions * HeapRegion::GrainBytes;
  3218   _g1->expand(expansion_bytes);
  3221 void G1CollectorPolicy_BestRegionsFirst::
  3222 record_collection_pause_end(bool popular, bool abandoned) {
  3223   G1CollectorPolicy::record_collection_pause_end(popular, abandoned);
  3224   assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
  3227 // Local Variables: ***
  3228 // c-indentation-style: gnu ***
  3229 // End: ***

mercurial