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

Tue, 24 Feb 2009 15:50:23 -0500

author
tonyp
date
Tue, 24 Feb 2009 15:50:23 -0500
changeset 1030
3698e8f47799
parent 982
1e458753107d
child 1063
7bb995fbd3c0
child 1071
6c4cea9bfa11
permissions
-rw-r--r--

6804746: G1: guarantee(variance() > -1.0,"variance should be >= 0") (due to evacuation failure)
Summary: Under certain circumstances (evacuation failure) the pause time is not communicated to the policy and, as a result, the pause time field is not initialized properly.
Reviewed-by: jmasa

     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 during 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   if (SurvivorRatio < 1) {
   301     vm_exit_during_initialization("Invalid survivor ratio specified");
   302   }
   303   CollectorPolicy::initialize_flags();
   304 }
   306 void G1CollectorPolicy::init() {
   307   // Set aside an initial future to_space.
   308   _g1 = G1CollectedHeap::heap();
   309   size_t regions = Universe::heap()->capacity() / HeapRegion::GrainBytes;
   311   assert(Heap_lock->owned_by_self(), "Locking discipline.");
   313   if (G1SteadyStateUsed < 50) {
   314     vm_exit_during_initialization("G1SteadyStateUsed must be at least 50%.");
   315   }
   316   if (UseConcMarkSweepGC) {
   317     vm_exit_during_initialization("-XX:+UseG1GC is incompatible with "
   318                                   "-XX:+UseConcMarkSweepGC.");
   319   }
   321   initialize_gc_policy_counters();
   323   if (G1Gen) {
   324     _in_young_gc_mode = true;
   326     if (G1YoungGenSize == 0) {
   327       set_adaptive_young_list_length(true);
   328       _young_list_fixed_length = 0;
   329     } else {
   330       set_adaptive_young_list_length(false);
   331       _young_list_fixed_length = (G1YoungGenSize / HeapRegion::GrainBytes);
   332     }
   333      _free_regions_at_end_of_collection = _g1->free_regions();
   334      _scan_only_regions_at_end_of_collection = 0;
   335      calculate_young_list_min_length();
   336      guarantee( _young_list_min_length == 0, "invariant, not enough info" );
   337      calculate_young_list_target_config();
   338    } else {
   339      _young_list_fixed_length = 0;
   340     _in_young_gc_mode = false;
   341   }
   342 }
   344 // Create the jstat counters for the policy.
   345 void G1CollectorPolicy::initialize_gc_policy_counters()
   346 {
   347   _gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 2 + G1Gen);
   348 }
   350 void G1CollectorPolicy::calculate_young_list_min_length() {
   351   _young_list_min_length = 0;
   353   if (!adaptive_young_list_length())
   354     return;
   356   if (_alloc_rate_ms_seq->num() > 3) {
   357     double now_sec = os::elapsedTime();
   358     double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;
   359     double alloc_rate_ms = predict_alloc_rate_ms();
   360     int min_regions = (int) ceil(alloc_rate_ms * when_ms);
   361     int current_region_num = (int) _g1->young_list_length();
   362     _young_list_min_length = min_regions + current_region_num;
   363   }
   364 }
   366 void G1CollectorPolicy::calculate_young_list_target_config() {
   367   if (adaptive_young_list_length()) {
   368     size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
   369     calculate_young_list_target_config(rs_lengths);
   370   } else {
   371     if (full_young_gcs())
   372       _young_list_target_length = _young_list_fixed_length;
   373     else
   374       _young_list_target_length = _young_list_fixed_length / 2;
   375     _young_list_target_length = MAX2(_young_list_target_length, (size_t)1);
   376     size_t so_length = calculate_optimal_so_length(_young_list_target_length);
   377     guarantee( so_length < _young_list_target_length, "invariant" );
   378     _young_list_so_prefix_length = so_length;
   379   }
   380   calculate_survivors_policy();
   381 }
   383 // This method calculate the optimal scan-only set for a fixed young
   384 // gen size. I couldn't work out how to reuse the more elaborate one,
   385 // i.e. calculate_young_list_target_config(rs_length), as the loops are
   386 // fundamentally different (the other one finds a config for different
   387 // S-O lengths, whereas here we need to do the opposite).
   388 size_t G1CollectorPolicy::calculate_optimal_so_length(
   389                                                     size_t young_list_length) {
   390   if (!G1UseScanOnlyPrefix)
   391     return 0;
   393   if (_all_pause_times_ms->num() < 3) {
   394     // we won't use a scan-only set at the beginning to allow the rest
   395     // of the predictors to warm up
   396     return 0;
   397   }
   399   if (_cost_per_scan_only_region_ms_seq->num() < 3) {
   400     // then, we'll only set the S-O set to 1 for a little bit of time,
   401     // to get enough information on the scanning cost
   402     return 1;
   403   }
   405   size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
   406   size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
   407   size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
   408   size_t scanned_cards;
   409   if (full_young_gcs())
   410     scanned_cards = predict_young_card_num(adj_rs_lengths);
   411   else
   412     scanned_cards = predict_non_young_card_num(adj_rs_lengths);
   413   double base_time_ms = predict_base_elapsed_time_ms(pending_cards,
   414                                                      scanned_cards);
   416   size_t so_length = 0;
   417   double max_gc_eff = 0.0;
   418   for (size_t i = 0; i < young_list_length; ++i) {
   419     double gc_eff = 0.0;
   420     double pause_time_ms = 0.0;
   421     predict_gc_eff(young_list_length, i, base_time_ms,
   422                    &gc_eff, &pause_time_ms);
   423     if (gc_eff > max_gc_eff) {
   424       max_gc_eff = gc_eff;
   425       so_length = i;
   426     }
   427   }
   429   // set it to 95% of the optimal to make sure we sample the "area"
   430   // around the optimal length to get up-to-date survival rate data
   431   return so_length * 950 / 1000;
   432 }
   434 // This is a really cool piece of code! It finds the best
   435 // target configuration (young length / scan-only prefix length) so
   436 // that GC efficiency is maximized and that we also meet a pause
   437 // time. It's a triple nested loop. These loops are explained below
   438 // from the inside-out :-)
   439 //
   440 // (a) The innermost loop will try to find the optimal young length
   441 // for a fixed S-O length. It uses a binary search to speed up the
   442 // process. We assume that, for a fixed S-O length, as we add more
   443 // young regions to the CSet, the GC efficiency will only go up (I'll
   444 // skip the proof). So, using a binary search to optimize this process
   445 // makes perfect sense.
   446 //
   447 // (b) The middle loop will fix the S-O length before calling the
   448 // innermost one. It will vary it between two parameters, increasing
   449 // it by a given increment.
   450 //
   451 // (c) The outermost loop will call the middle loop three times.
   452 //   (1) The first time it will explore all possible S-O length values
   453 //   from 0 to as large as it can get, using a coarse increment (to
   454 //   quickly "home in" to where the optimal seems to be).
   455 //   (2) The second time it will explore the values around the optimal
   456 //   that was found by the first iteration using a fine increment.
   457 //   (3) Once the optimal config has been determined by the second
   458 //   iteration, we'll redo the calculation, but setting the S-O length
   459 //   to 95% of the optimal to make sure we sample the "area"
   460 //   around the optimal length to get up-to-date survival rate data
   461 //
   462 // Termination conditions for the iterations are several: the pause
   463 // time is over the limit, we do not have enough to-space, etc.
   465 void G1CollectorPolicy::calculate_young_list_target_config(size_t rs_lengths) {
   466   guarantee( adaptive_young_list_length(), "pre-condition" );
   468   double start_time_sec = os::elapsedTime();
   469   size_t min_reserve_perc = MAX2((size_t)2, (size_t)G1MinReservePerc);
   470   min_reserve_perc = MIN2((size_t) 50, min_reserve_perc);
   471   size_t reserve_regions =
   472     (size_t) ((double) min_reserve_perc * (double) _g1->n_regions() / 100.0);
   474   if (full_young_gcs() && _free_regions_at_end_of_collection > 0) {
   475     // we are in fully-young mode and there are free regions in the heap
   477     double survivor_regions_evac_time =
   478         predict_survivor_regions_evac_time();
   480     size_t min_so_length = 0;
   481     size_t max_so_length = 0;
   483     if (G1UseScanOnlyPrefix) {
   484       if (_all_pause_times_ms->num() < 3) {
   485         // we won't use a scan-only set at the beginning to allow the rest
   486         // of the predictors to warm up
   487         min_so_length = 0;
   488         max_so_length = 0;
   489       } else if (_cost_per_scan_only_region_ms_seq->num() < 3) {
   490         // then, we'll only set the S-O set to 1 for a little bit of time,
   491         // to get enough information on the scanning cost
   492         min_so_length = 1;
   493         max_so_length = 1;
   494       } else if (_in_marking_window || _last_full_young_gc) {
   495         // no S-O prefix during a marking phase either, as at the end
   496         // of the marking phase we'll have to use a very small young
   497         // length target to fill up the rest of the CSet with
   498         // non-young regions and, if we have lots of scan-only regions
   499         // left-over, we will not be able to add any more non-young
   500         // regions.
   501         min_so_length = 0;
   502         max_so_length = 0;
   503       } else {
   504         // this is the common case; we'll never reach the maximum, we
   505         // one of the end conditions will fire well before that
   506         // (hopefully!)
   507         min_so_length = 0;
   508         max_so_length = _free_regions_at_end_of_collection - 1;
   509       }
   510     } else {
   511       // no S-O prefix, as the switch is not set, but we still need to
   512       // do one iteration to calculate the best young target that
   513       // meets the pause time; this way we reuse the same code instead
   514       // of replicating it
   515       min_so_length = 0;
   516       max_so_length = 0;
   517     }
   519     double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
   520     size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
   521     size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
   522     size_t scanned_cards;
   523     if (full_young_gcs())
   524       scanned_cards = predict_young_card_num(adj_rs_lengths);
   525     else
   526       scanned_cards = predict_non_young_card_num(adj_rs_lengths);
   527     // calculate this once, so that we don't have to recalculate it in
   528     // the innermost loop
   529     double base_time_ms = predict_base_elapsed_time_ms(pending_cards, scanned_cards)
   530                           + survivor_regions_evac_time;
   531     // the result
   532     size_t final_young_length = 0;
   533     size_t final_so_length = 0;
   534     double final_gc_eff = 0.0;
   535     // we'll also keep track of how many times we go into the inner loop
   536     // this is for profiling reasons
   537     size_t calculations = 0;
   539     // this determines which of the three iterations the outer loop is in
   540     typedef enum {
   541       pass_type_coarse,
   542       pass_type_fine,
   543       pass_type_final
   544     } pass_type_t;
   546     // range of the outer loop's iteration
   547     size_t from_so_length   = min_so_length;
   548     size_t to_so_length     = max_so_length;
   549     guarantee( from_so_length <= to_so_length, "invariant" );
   551     // this will keep the S-O length that's found by the second
   552     // iteration of the outer loop; we'll keep it just in case the third
   553     // iteration fails to find something
   554     size_t fine_so_length   = 0;
   556     // the increment step for the coarse (first) iteration
   557     size_t so_coarse_increments = 5;
   559     // the common case, we'll start with the coarse iteration
   560     pass_type_t pass = pass_type_coarse;
   561     size_t so_length_incr = so_coarse_increments;
   563     if (from_so_length == to_so_length) {
   564       // not point in doing the coarse iteration, we'll go directly into
   565       // the fine one (we essentially trying to find the optimal young
   566       // length for a fixed S-O length).
   567       so_length_incr = 1;
   568       pass = pass_type_final;
   569     } else if (to_so_length - from_so_length < 3 * so_coarse_increments) {
   570       // again, the range is too short so no point in foind the coarse
   571       // iteration either
   572       so_length_incr = 1;
   573       pass = pass_type_fine;
   574     }
   576     bool done = false;
   577     // this is the outermost loop
   578     while (!done) {
   579 #ifdef TRACE_CALC_YOUNG_CONFIG
   580       // leave this in for debugging, just in case
   581       gclog_or_tty->print_cr("searching between " SIZE_FORMAT " and " SIZE_FORMAT
   582                              ", incr " SIZE_FORMAT ", pass %s",
   583                              from_so_length, to_so_length, so_length_incr,
   584                              (pass == pass_type_coarse) ? "coarse" :
   585                              (pass == pass_type_fine) ? "fine" : "final");
   586 #endif // TRACE_CALC_YOUNG_CONFIG
   588       size_t so_length = from_so_length;
   589       size_t init_free_regions =
   590         MAX2((size_t)0,
   591              _free_regions_at_end_of_collection +
   592              _scan_only_regions_at_end_of_collection - reserve_regions);
   594       // this determines whether a configuration was found
   595       bool gc_eff_set = false;
   596       // this is the middle loop
   597       while (so_length <= to_so_length) {
   598         // base time, which excludes region-related time; again we
   599         // calculate it once to avoid recalculating it in the
   600         // innermost loop
   601         double base_time_with_so_ms =
   602                            base_time_ms + predict_scan_only_time_ms(so_length);
   603         // it's already over the pause target, go around
   604         if (base_time_with_so_ms > target_pause_time_ms)
   605           break;
   607         size_t starting_young_length = so_length+1;
   609         // we make sure that the short young length that makes sense
   610         // (one more than the S-O length) is feasible
   611         size_t min_young_length = starting_young_length;
   612         double min_gc_eff;
   613         bool min_ok;
   614         ++calculations;
   615         min_ok = predict_gc_eff(min_young_length, so_length,
   616                                 base_time_with_so_ms,
   617                                 init_free_regions, target_pause_time_ms,
   618                                 &min_gc_eff);
   620         if (min_ok) {
   621           // the shortest young length is indeed feasible; we'll know
   622           // set up the max young length and we'll do a binary search
   623           // between min_young_length and max_young_length
   624           size_t max_young_length = _free_regions_at_end_of_collection - 1;
   625           double max_gc_eff = 0.0;
   626           bool max_ok = false;
   628           // the innermost loop! (finally!)
   629           while (max_young_length > min_young_length) {
   630             // we'll make sure that min_young_length is always at a
   631             // feasible config
   632             guarantee( min_ok, "invariant" );
   634             ++calculations;
   635             max_ok = predict_gc_eff(max_young_length, so_length,
   636                                     base_time_with_so_ms,
   637                                     init_free_regions, target_pause_time_ms,
   638                                     &max_gc_eff);
   640             size_t diff = (max_young_length - min_young_length) / 2;
   641             if (max_ok) {
   642               min_young_length = max_young_length;
   643               min_gc_eff = max_gc_eff;
   644               min_ok = true;
   645             }
   646             max_young_length = min_young_length + diff;
   647           }
   649           // the innermost loop found a config
   650           guarantee( min_ok, "invariant" );
   651           if (min_gc_eff > final_gc_eff) {
   652             // it's the best config so far, so we'll keep it
   653             final_gc_eff = min_gc_eff;
   654             final_young_length = min_young_length;
   655             final_so_length = so_length;
   656             gc_eff_set = true;
   657           }
   658         }
   660         // incremental the fixed S-O length and go around
   661         so_length += so_length_incr;
   662       }
   664       // this is the end of the outermost loop and we need to decide
   665       // what to do during the next iteration
   666       if (pass == pass_type_coarse) {
   667         // we just did the coarse pass (first iteration)
   669         if (!gc_eff_set)
   670           // we didn't find a feasible config so we'll just bail out; of
   671           // course, it might be the case that we missed it; but I'd say
   672           // it's a bit unlikely
   673           done = true;
   674         else {
   675           // We did find a feasible config with optimal GC eff during
   676           // the first pass. So the second pass we'll only consider the
   677           // S-O lengths around that config with a fine increment.
   679           guarantee( so_length_incr == so_coarse_increments, "invariant" );
   680           guarantee( final_so_length >= min_so_length, "invariant" );
   682 #ifdef TRACE_CALC_YOUNG_CONFIG
   683           // leave this in for debugging, just in case
   684           gclog_or_tty->print_cr("  coarse pass: SO length " SIZE_FORMAT,
   685                                  final_so_length);
   686 #endif // TRACE_CALC_YOUNG_CONFIG
   688           from_so_length =
   689             (final_so_length - min_so_length > so_coarse_increments) ?
   690             final_so_length - so_coarse_increments + 1 : min_so_length;
   691           to_so_length =
   692             (max_so_length - final_so_length > so_coarse_increments) ?
   693             final_so_length + so_coarse_increments - 1 : max_so_length;
   695           pass = pass_type_fine;
   696           so_length_incr = 1;
   697         }
   698       } else if (pass == pass_type_fine) {
   699         // we just finished the second pass
   701         if (!gc_eff_set) {
   702           // we didn't find a feasible config (yes, it's possible;
   703           // notice that, sometimes, we go directly into the fine
   704           // iteration and skip the coarse one) so we bail out
   705           done = true;
   706         } else {
   707           // We did find a feasible config with optimal GC eff
   708           guarantee( so_length_incr == 1, "invariant" );
   710           if (final_so_length == 0) {
   711             // The config is of an empty S-O set, so we'll just bail out
   712             done = true;
   713           } else {
   714             // we'll go around once more, setting the S-O length to 95%
   715             // of the optimal
   716             size_t new_so_length = 950 * final_so_length / 1000;
   718 #ifdef TRACE_CALC_YOUNG_CONFIG
   719             // leave this in for debugging, just in case
   720             gclog_or_tty->print_cr("  fine pass: SO length " SIZE_FORMAT
   721                                    ", setting it to " SIZE_FORMAT,
   722                                     final_so_length, new_so_length);
   723 #endif // TRACE_CALC_YOUNG_CONFIG
   725             from_so_length = new_so_length;
   726             to_so_length = new_so_length;
   727             fine_so_length = final_so_length;
   729             pass = pass_type_final;
   730           }
   731         }
   732       } else if (pass == pass_type_final) {
   733         // we just finished the final (third) pass
   735         if (!gc_eff_set)
   736           // we didn't find a feasible config, so we'll just use the one
   737           // we found during the second pass, which we saved
   738           final_so_length = fine_so_length;
   740         // and we're done!
   741         done = true;
   742       } else {
   743         guarantee( false, "should never reach here" );
   744       }
   746       // we now go around the outermost loop
   747     }
   749     // we should have at least one region in the target young length
   750     _young_list_target_length =
   751         MAX2((size_t) 1, final_young_length + _recorded_survivor_regions);
   752     if (final_so_length >= final_young_length)
   753       // and we need to ensure that the S-O length is not greater than
   754       // the target young length (this is being a bit careful)
   755       final_so_length = 0;
   756     _young_list_so_prefix_length = final_so_length;
   757     guarantee( !_in_marking_window || !_last_full_young_gc ||
   758                _young_list_so_prefix_length == 0, "invariant" );
   760     // let's keep an eye of how long we spend on this calculation
   761     // right now, I assume that we'll print it when we need it; we
   762     // should really adde it to the breakdown of a pause
   763     double end_time_sec = os::elapsedTime();
   764     double elapsed_time_ms = (end_time_sec - start_time_sec) * 1000.0;
   766 #ifdef TRACE_CALC_YOUNG_CONFIG
   767     // leave this in for debugging, just in case
   768     gclog_or_tty->print_cr("target = %1.1lf ms, young = " SIZE_FORMAT
   769                            ", SO = " SIZE_FORMAT ", "
   770                            "elapsed %1.2lf ms, calcs: " SIZE_FORMAT " (%s%s) "
   771                            SIZE_FORMAT SIZE_FORMAT,
   772                            target_pause_time_ms,
   773                            _young_list_target_length - _young_list_so_prefix_length,
   774                            _young_list_so_prefix_length,
   775                            elapsed_time_ms,
   776                            calculations,
   777                            full_young_gcs() ? "full" : "partial",
   778                            should_initiate_conc_mark() ? " i-m" : "",
   779                            _in_marking_window,
   780                            _in_marking_window_im);
   781 #endif // TRACE_CALC_YOUNG_CONFIG
   783     if (_young_list_target_length < _young_list_min_length) {
   784       // bummer; this means that, if we do a pause when the optimal
   785       // config dictates, we'll violate the pause spacing target (the
   786       // min length was calculate based on the application's current
   787       // alloc rate);
   789       // so, we have to bite the bullet, and allocate the minimum
   790       // number. We'll violate our target, but we just can't meet it.
   792       size_t so_length = 0;
   793       // a note further up explains why we do not want an S-O length
   794       // during marking
   795       if (!_in_marking_window && !_last_full_young_gc)
   796         // but we can still try to see whether we can find an optimal
   797         // S-O length
   798         so_length = calculate_optimal_so_length(_young_list_min_length);
   800 #ifdef TRACE_CALC_YOUNG_CONFIG
   801       // leave this in for debugging, just in case
   802       gclog_or_tty->print_cr("adjusted target length from "
   803                              SIZE_FORMAT " to " SIZE_FORMAT
   804                              ", SO " SIZE_FORMAT,
   805                              _young_list_target_length, _young_list_min_length,
   806                              so_length);
   807 #endif // TRACE_CALC_YOUNG_CONFIG
   809       _young_list_target_length =
   810         MAX2(_young_list_min_length, (size_t)1);
   811       _young_list_so_prefix_length = so_length;
   812     }
   813   } else {
   814     // we are in a partially-young mode or we've run out of regions (due
   815     // to evacuation failure)
   817 #ifdef TRACE_CALC_YOUNG_CONFIG
   818     // leave this in for debugging, just in case
   819     gclog_or_tty->print_cr("(partial) setting target to " SIZE_FORMAT
   820                            ", SO " SIZE_FORMAT,
   821                            _young_list_min_length, 0);
   822 #endif // TRACE_CALC_YOUNG_CONFIG
   824     // we'll do the pause as soon as possible and with no S-O prefix
   825     // (see above for the reasons behind the latter)
   826     _young_list_target_length =
   827       MAX2(_young_list_min_length, (size_t) 1);
   828     _young_list_so_prefix_length = 0;
   829   }
   831   _rs_lengths_prediction = rs_lengths;
   832 }
   834 // This is used by: calculate_optimal_so_length(length). It returns
   835 // the GC eff and predicted pause time for a particular config
   836 void
   837 G1CollectorPolicy::predict_gc_eff(size_t young_length,
   838                                   size_t so_length,
   839                                   double base_time_ms,
   840                                   double* ret_gc_eff,
   841                                   double* ret_pause_time_ms) {
   842   double so_time_ms = predict_scan_only_time_ms(so_length);
   843   double accum_surv_rate_adj = 0.0;
   844   if (so_length > 0)
   845     accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
   846   double accum_surv_rate =
   847     accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
   848   size_t bytes_to_copy =
   849     (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
   850   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
   851   double young_other_time_ms =
   852                        predict_young_other_time_ms(young_length - so_length);
   853   double pause_time_ms =
   854                 base_time_ms + so_time_ms + copy_time_ms + young_other_time_ms;
   855   size_t reclaimed_bytes =
   856     (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
   857   double gc_eff = (double) reclaimed_bytes / pause_time_ms;
   859   *ret_gc_eff = gc_eff;
   860   *ret_pause_time_ms = pause_time_ms;
   861 }
   863 // This is used by: calculate_young_list_target_config(rs_length). It
   864 // returns the GC eff of a particular config. It returns false if that
   865 // config violates any of the end conditions of the search in the
   866 // calling method, or true upon success. The end conditions were put
   867 // here since it's called twice and it was best not to replicate them
   868 // in the caller. Also, passing the parameteres avoids having to
   869 // recalculate them in the innermost loop.
   870 bool
   871 G1CollectorPolicy::predict_gc_eff(size_t young_length,
   872                                   size_t so_length,
   873                                   double base_time_with_so_ms,
   874                                   size_t init_free_regions,
   875                                   double target_pause_time_ms,
   876                                   double* ret_gc_eff) {
   877   *ret_gc_eff = 0.0;
   879   if (young_length >= init_free_regions)
   880     // end condition 1: not enough space for the young regions
   881     return false;
   883   double accum_surv_rate_adj = 0.0;
   884   if (so_length > 0)
   885     accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
   886   double accum_surv_rate =
   887     accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
   888   size_t bytes_to_copy =
   889     (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
   890   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
   891   double young_other_time_ms =
   892                        predict_young_other_time_ms(young_length - so_length);
   893   double pause_time_ms =
   894                    base_time_with_so_ms + copy_time_ms + young_other_time_ms;
   896   if (pause_time_ms > target_pause_time_ms)
   897     // end condition 2: over the target pause time
   898     return false;
   900   size_t reclaimed_bytes =
   901     (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
   902   size_t free_bytes =
   903                  (init_free_regions - young_length) * HeapRegion::GrainBytes;
   905   if ((2.0 + sigma()) * (double) bytes_to_copy > (double) free_bytes)
   906     // end condition 3: out of to-space (conservatively)
   907     return false;
   909   // success!
   910   double gc_eff = (double) reclaimed_bytes / pause_time_ms;
   911   *ret_gc_eff = gc_eff;
   913   return true;
   914 }
   916 double G1CollectorPolicy::predict_survivor_regions_evac_time() {
   917   double survivor_regions_evac_time = 0.0;
   918   for (HeapRegion * r = _recorded_survivor_head;
   919        r != NULL && r != _recorded_survivor_tail->get_next_young_region();
   920        r = r->get_next_young_region()) {
   921     survivor_regions_evac_time += predict_region_elapsed_time_ms(r, true);
   922   }
   923   return survivor_regions_evac_time;
   924 }
   926 void G1CollectorPolicy::check_prediction_validity() {
   927   guarantee( adaptive_young_list_length(), "should not call this otherwise" );
   929   size_t rs_lengths = _g1->young_list_sampled_rs_lengths();
   930   if (rs_lengths > _rs_lengths_prediction) {
   931     // add 10% to avoid having to recalculate often
   932     size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;
   933     calculate_young_list_target_config(rs_lengths_prediction);
   934   }
   935 }
   937 HeapWord* G1CollectorPolicy::mem_allocate_work(size_t size,
   938                                                bool is_tlab,
   939                                                bool* gc_overhead_limit_was_exceeded) {
   940   guarantee(false, "Not using this policy feature yet.");
   941   return NULL;
   942 }
   944 // This method controls how a collector handles one or more
   945 // of its generations being fully allocated.
   946 HeapWord* G1CollectorPolicy::satisfy_failed_allocation(size_t size,
   947                                                        bool is_tlab) {
   948   guarantee(false, "Not using this policy feature yet.");
   949   return NULL;
   950 }
   953 #ifndef PRODUCT
   954 bool G1CollectorPolicy::verify_young_ages() {
   955   HeapRegion* head = _g1->young_list_first_region();
   956   return
   957     verify_young_ages(head, _short_lived_surv_rate_group);
   958   // also call verify_young_ages on any additional surv rate groups
   959 }
   961 bool
   962 G1CollectorPolicy::verify_young_ages(HeapRegion* head,
   963                                      SurvRateGroup *surv_rate_group) {
   964   guarantee( surv_rate_group != NULL, "pre-condition" );
   966   const char* name = surv_rate_group->name();
   967   bool ret = true;
   968   int prev_age = -1;
   970   for (HeapRegion* curr = head;
   971        curr != NULL;
   972        curr = curr->get_next_young_region()) {
   973     SurvRateGroup* group = curr->surv_rate_group();
   974     if (group == NULL && !curr->is_survivor()) {
   975       gclog_or_tty->print_cr("## %s: encountered NULL surv_rate_group", name);
   976       ret = false;
   977     }
   979     if (surv_rate_group == group) {
   980       int age = curr->age_in_surv_rate_group();
   982       if (age < 0) {
   983         gclog_or_tty->print_cr("## %s: encountered negative age", name);
   984         ret = false;
   985       }
   987       if (age <= prev_age) {
   988         gclog_or_tty->print_cr("## %s: region ages are not strictly increasing "
   989                                "(%d, %d)", name, age, prev_age);
   990         ret = false;
   991       }
   992       prev_age = age;
   993     }
   994   }
   996   return ret;
   997 }
   998 #endif // PRODUCT
  1000 void G1CollectorPolicy::record_full_collection_start() {
  1001   _cur_collection_start_sec = os::elapsedTime();
  1002   // Release the future to-space so that it is available for compaction into.
  1003   _g1->set_full_collection();
  1006 void G1CollectorPolicy::record_full_collection_end() {
  1007   // Consider this like a collection pause for the purposes of allocation
  1008   // since last pause.
  1009   double end_sec = os::elapsedTime();
  1010   double full_gc_time_sec = end_sec - _cur_collection_start_sec;
  1011   double full_gc_time_ms = full_gc_time_sec * 1000.0;
  1013   checkpoint_conc_overhead();
  1015   _all_full_gc_times_ms->add(full_gc_time_ms);
  1017   update_recent_gc_times(end_sec, full_gc_time_ms);
  1019   _g1->clear_full_collection();
  1021   // "Nuke" the heuristics that control the fully/partially young GC
  1022   // transitions and make sure we start with fully young GCs after the
  1023   // Full GC.
  1024   set_full_young_gcs(true);
  1025   _last_full_young_gc = false;
  1026   _should_revert_to_full_young_gcs = false;
  1027   _should_initiate_conc_mark = false;
  1028   _known_garbage_bytes = 0;
  1029   _known_garbage_ratio = 0.0;
  1030   _in_marking_window = false;
  1031   _in_marking_window_im = false;
  1033   _short_lived_surv_rate_group->record_scan_only_prefix(0);
  1034   _short_lived_surv_rate_group->start_adding_regions();
  1035   // also call this on any additional surv rate groups
  1037   record_survivor_regions(0, NULL, NULL);
  1039   _prev_region_num_young   = _region_num_young;
  1040   _prev_region_num_tenured = _region_num_tenured;
  1042   _free_regions_at_end_of_collection = _g1->free_regions();
  1043   _scan_only_regions_at_end_of_collection = 0;
  1044   // Reset survivors SurvRateGroup.
  1045   _survivor_surv_rate_group->reset();
  1046   calculate_young_list_min_length();
  1047   calculate_young_list_target_config();
  1050 void G1CollectorPolicy::record_pop_compute_rc_start() {
  1051   _pop_compute_rc_start = os::elapsedTime();
  1053 void G1CollectorPolicy::record_pop_compute_rc_end() {
  1054   double ms = (os::elapsedTime() - _pop_compute_rc_start)*1000.0;
  1055   _cur_popular_compute_rc_time_ms = ms;
  1056   _pop_compute_rc_start = 0.0;
  1058 void G1CollectorPolicy::record_pop_evac_start() {
  1059   _pop_evac_start = os::elapsedTime();
  1061 void G1CollectorPolicy::record_pop_evac_end() {
  1062   double ms = (os::elapsedTime() - _pop_evac_start)*1000.0;
  1063   _cur_popular_evac_time_ms = ms;
  1064   _pop_evac_start = 0.0;
  1067 void G1CollectorPolicy::record_before_bytes(size_t bytes) {
  1068   _bytes_in_to_space_before_gc += bytes;
  1071 void G1CollectorPolicy::record_after_bytes(size_t bytes) {
  1072   _bytes_in_to_space_after_gc += bytes;
  1075 void G1CollectorPolicy::record_stop_world_start() {
  1076   _stop_world_start = os::elapsedTime();
  1079 void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
  1080                                                       size_t start_used) {
  1081   if (PrintGCDetails) {
  1082     gclog_or_tty->stamp(PrintGCTimeStamps);
  1083     gclog_or_tty->print("[GC pause");
  1084     if (in_young_gc_mode())
  1085       gclog_or_tty->print(" (%s)", full_young_gcs() ? "young" : "partial");
  1088   assert(_g1->used_regions() == _g1->recalculate_used_regions(),
  1089          "sanity");
  1091   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
  1092   _all_stop_world_times_ms->add(s_w_t_ms);
  1093   _stop_world_start = 0.0;
  1095   _cur_collection_start_sec = start_time_sec;
  1096   _cur_collection_pause_used_at_start_bytes = start_used;
  1097   _cur_collection_pause_used_regions_at_start = _g1->used_regions();
  1098   _pending_cards = _g1->pending_card_num();
  1099   _max_pending_cards = _g1->max_pending_card_num();
  1101   _bytes_in_to_space_before_gc = 0;
  1102   _bytes_in_to_space_after_gc = 0;
  1103   _bytes_in_collection_set_before_gc = 0;
  1105 #ifdef DEBUG
  1106   // initialise these to something well known so that we can spot
  1107   // if they are not set properly
  1109   for (int i = 0; i < _parallel_gc_threads; ++i) {
  1110     _par_last_ext_root_scan_times_ms[i] = -666.0;
  1111     _par_last_mark_stack_scan_times_ms[i] = -666.0;
  1112     _par_last_scan_only_times_ms[i] = -666.0;
  1113     _par_last_scan_only_regions_scanned[i] = -666.0;
  1114     _par_last_update_rs_start_times_ms[i] = -666.0;
  1115     _par_last_update_rs_times_ms[i] = -666.0;
  1116     _par_last_update_rs_processed_buffers[i] = -666.0;
  1117     _par_last_scan_rs_start_times_ms[i] = -666.0;
  1118     _par_last_scan_rs_times_ms[i] = -666.0;
  1119     _par_last_scan_new_refs_times_ms[i] = -666.0;
  1120     _par_last_obj_copy_times_ms[i] = -666.0;
  1121     _par_last_termination_times_ms[i] = -666.0;
  1123     _pop_par_last_update_rs_start_times_ms[i] = -666.0;
  1124     _pop_par_last_update_rs_times_ms[i] = -666.0;
  1125     _pop_par_last_update_rs_processed_buffers[i] = -666.0;
  1126     _pop_par_last_scan_rs_start_times_ms[i] = -666.0;
  1127     _pop_par_last_scan_rs_times_ms[i] = -666.0;
  1128     _pop_par_last_closure_app_times_ms[i] = -666.0;
  1130 #endif
  1132   for (int i = 0; i < _aux_num; ++i) {
  1133     _cur_aux_times_ms[i] = 0.0;
  1134     _cur_aux_times_set[i] = false;
  1137   _satb_drain_time_set = false;
  1138   _last_satb_drain_processed_buffers = -1;
  1140   if (in_young_gc_mode())
  1141     _last_young_gc_full = false;
  1144   // do that for any other surv rate groups
  1145   _short_lived_surv_rate_group->stop_adding_regions();
  1146   size_t short_lived_so_length = _young_list_so_prefix_length;
  1147   _short_lived_surv_rate_group->record_scan_only_prefix(short_lived_so_length);
  1148   tag_scan_only(short_lived_so_length);
  1150   if (G1UseSurvivorSpace) {
  1151     _survivors_age_table.clear();
  1154   assert( verify_young_ages(), "region age verification" );
  1157 void G1CollectorPolicy::tag_scan_only(size_t short_lived_scan_only_length) {
  1158   // done in a way that it can be extended for other surv rate groups too...
  1160   HeapRegion* head = _g1->young_list_first_region();
  1161   bool finished_short_lived = (short_lived_scan_only_length == 0);
  1163   if (finished_short_lived)
  1164     return;
  1166   for (HeapRegion* curr = head;
  1167        curr != NULL;
  1168        curr = curr->get_next_young_region()) {
  1169     SurvRateGroup* surv_rate_group = curr->surv_rate_group();
  1170     int age = curr->age_in_surv_rate_group();
  1172     if (surv_rate_group == _short_lived_surv_rate_group) {
  1173       if ((size_t)age < short_lived_scan_only_length)
  1174         curr->set_scan_only();
  1175       else
  1176         finished_short_lived = true;
  1180     if (finished_short_lived)
  1181       return;
  1184   guarantee( false, "we should never reach here" );
  1187 void G1CollectorPolicy::record_popular_pause_preamble_start() {
  1188   _cur_popular_preamble_start_ms = os::elapsedTime() * 1000.0;
  1191 void G1CollectorPolicy::record_popular_pause_preamble_end() {
  1192   _cur_popular_preamble_time_ms =
  1193     (os::elapsedTime() * 1000.0) - _cur_popular_preamble_start_ms;
  1195   // copy the recorded statistics of the first pass to temporary arrays
  1196   for (int i = 0; i < _parallel_gc_threads; ++i) {
  1197     _pop_par_last_update_rs_start_times_ms[i] = _par_last_update_rs_start_times_ms[i];
  1198     _pop_par_last_update_rs_times_ms[i] = _par_last_update_rs_times_ms[i];
  1199     _pop_par_last_update_rs_processed_buffers[i] = _par_last_update_rs_processed_buffers[i];
  1200     _pop_par_last_scan_rs_start_times_ms[i] = _par_last_scan_rs_start_times_ms[i];
  1201     _pop_par_last_scan_rs_times_ms[i] = _par_last_scan_rs_times_ms[i];
  1202     _pop_par_last_closure_app_times_ms[i] = _par_last_obj_copy_times_ms[i];
  1206 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
  1207   _mark_closure_time_ms = mark_closure_time_ms;
  1210 void G1CollectorPolicy::record_concurrent_mark_init_start() {
  1211   _mark_init_start_sec = os::elapsedTime();
  1212   guarantee(!in_young_gc_mode(), "should not do be here in young GC mode");
  1215 void G1CollectorPolicy::record_concurrent_mark_init_end_pre(double
  1216                                                    mark_init_elapsed_time_ms) {
  1217   _during_marking = true;
  1218   _should_initiate_conc_mark = false;
  1219   _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
  1222 void G1CollectorPolicy::record_concurrent_mark_init_end() {
  1223   double end_time_sec = os::elapsedTime();
  1224   double elapsed_time_ms = (end_time_sec - _mark_init_start_sec) * 1000.0;
  1225   _concurrent_mark_init_times_ms->add(elapsed_time_ms);
  1226   checkpoint_conc_overhead();
  1227   record_concurrent_mark_init_end_pre(elapsed_time_ms);
  1229   _mmu_tracker->add_pause(_mark_init_start_sec, end_time_sec, true);
  1232 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
  1233   _mark_remark_start_sec = os::elapsedTime();
  1234   _during_marking = false;
  1237 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
  1238   double end_time_sec = os::elapsedTime();
  1239   double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
  1240   checkpoint_conc_overhead();
  1241   _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
  1242   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1243   _prev_collection_pause_end_ms += elapsed_time_ms;
  1245   _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
  1248 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
  1249   _mark_cleanup_start_sec = os::elapsedTime();
  1252 void
  1253 G1CollectorPolicy::record_concurrent_mark_cleanup_end(size_t freed_bytes,
  1254                                                       size_t max_live_bytes) {
  1255   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  1256   record_concurrent_mark_cleanup_end_work2();
  1259 void
  1260 G1CollectorPolicy::
  1261 record_concurrent_mark_cleanup_end_work1(size_t freed_bytes,
  1262                                          size_t max_live_bytes) {
  1263   if (_n_marks < 2) _n_marks++;
  1264   if (G1PolicyVerbose > 0)
  1265     gclog_or_tty->print_cr("At end of marking, max_live is " SIZE_FORMAT " MB "
  1266                            " (of " SIZE_FORMAT " MB heap).",
  1267                            max_live_bytes/M, _g1->capacity()/M);
  1270 // The important thing about this is that it includes "os::elapsedTime".
  1271 void G1CollectorPolicy::record_concurrent_mark_cleanup_end_work2() {
  1272   checkpoint_conc_overhead();
  1273   double end_time_sec = os::elapsedTime();
  1274   double elapsed_time_ms = (end_time_sec - _mark_cleanup_start_sec)*1000.0;
  1275   _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
  1276   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1277   _prev_collection_pause_end_ms += elapsed_time_ms;
  1279   _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_time_sec, true);
  1281   _num_markings++;
  1283   // We did a marking, so reset the "since_last_mark" variables.
  1284   double considerConcMarkCost = 1.0;
  1285   // If there are available processors, concurrent activity is free...
  1286   if (Threads::number_of_non_daemon_threads() * 2 <
  1287       os::active_processor_count()) {
  1288     considerConcMarkCost = 0.0;
  1290   _n_pauses_at_mark_end = _n_pauses;
  1291   _n_marks_since_last_pause++;
  1292   _conc_mark_initiated = false;
  1295 void
  1296 G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
  1297   if (in_young_gc_mode()) {
  1298     _should_revert_to_full_young_gcs = false;
  1299     _last_full_young_gc = true;
  1300     _in_marking_window = false;
  1301     if (adaptive_young_list_length())
  1302       calculate_young_list_target_config();
  1306 void G1CollectorPolicy::record_concurrent_pause() {
  1307   if (_stop_world_start > 0.0) {
  1308     double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
  1309     _all_yield_times_ms->add(yield_ms);
  1313 void G1CollectorPolicy::record_concurrent_pause_end() {
  1316 void G1CollectorPolicy::record_collection_pause_end_CH_strong_roots() {
  1317   _cur_CH_strong_roots_end_sec = os::elapsedTime();
  1318   _cur_CH_strong_roots_dur_ms =
  1319     (_cur_CH_strong_roots_end_sec - _cur_collection_start_sec) * 1000.0;
  1322 void G1CollectorPolicy::record_collection_pause_end_G1_strong_roots() {
  1323   _cur_G1_strong_roots_end_sec = os::elapsedTime();
  1324   _cur_G1_strong_roots_dur_ms =
  1325     (_cur_G1_strong_roots_end_sec - _cur_CH_strong_roots_end_sec) * 1000.0;
  1328 template<class T>
  1329 T sum_of(T* sum_arr, int start, int n, int N) {
  1330   T sum = (T)0;
  1331   for (int i = 0; i < n; i++) {
  1332     int j = (start + i) % N;
  1333     sum += sum_arr[j];
  1335   return sum;
  1338 void G1CollectorPolicy::print_par_stats (int level,
  1339                                          const char* str,
  1340                                          double* data,
  1341                                          bool summary) {
  1342   double min = data[0], max = data[0];
  1343   double total = 0.0;
  1344   int j;
  1345   for (j = 0; j < level; ++j)
  1346     gclog_or_tty->print("   ");
  1347   gclog_or_tty->print("[%s (ms):", str);
  1348   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1349     double val = data[i];
  1350     if (val < min)
  1351       min = val;
  1352     if (val > max)
  1353       max = val;
  1354     total += val;
  1355     gclog_or_tty->print("  %3.1lf", val);
  1357   if (summary) {
  1358     gclog_or_tty->print_cr("");
  1359     double avg = total / (double) ParallelGCThreads;
  1360     gclog_or_tty->print(" ");
  1361     for (j = 0; j < level; ++j)
  1362       gclog_or_tty->print("   ");
  1363     gclog_or_tty->print("Avg: %5.1lf, Min: %5.1lf, Max: %5.1lf",
  1364                         avg, min, max);
  1366   gclog_or_tty->print_cr("]");
  1369 void G1CollectorPolicy::print_par_buffers (int level,
  1370                                          const char* str,
  1371                                          double* data,
  1372                                          bool summary) {
  1373   double min = data[0], max = data[0];
  1374   double total = 0.0;
  1375   int j;
  1376   for (j = 0; j < level; ++j)
  1377     gclog_or_tty->print("   ");
  1378   gclog_or_tty->print("[%s :", str);
  1379   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1380     double val = data[i];
  1381     if (val < min)
  1382       min = val;
  1383     if (val > max)
  1384       max = val;
  1385     total += val;
  1386     gclog_or_tty->print(" %d", (int) val);
  1388   if (summary) {
  1389     gclog_or_tty->print_cr("");
  1390     double avg = total / (double) ParallelGCThreads;
  1391     gclog_or_tty->print(" ");
  1392     for (j = 0; j < level; ++j)
  1393       gclog_or_tty->print("   ");
  1394     gclog_or_tty->print("Sum: %d, Avg: %d, Min: %d, Max: %d",
  1395                (int)total, (int)avg, (int)min, (int)max);
  1397   gclog_or_tty->print_cr("]");
  1400 void G1CollectorPolicy::print_stats (int level,
  1401                                      const char* str,
  1402                                      double value) {
  1403   for (int j = 0; j < level; ++j)
  1404     gclog_or_tty->print("   ");
  1405   gclog_or_tty->print_cr("[%s: %5.1lf ms]", str, value);
  1408 void G1CollectorPolicy::print_stats (int level,
  1409                                      const char* str,
  1410                                      int value) {
  1411   for (int j = 0; j < level; ++j)
  1412     gclog_or_tty->print("   ");
  1413   gclog_or_tty->print_cr("[%s: %d]", str, value);
  1416 double G1CollectorPolicy::avg_value (double* data) {
  1417   if (ParallelGCThreads > 0) {
  1418     double ret = 0.0;
  1419     for (uint i = 0; i < ParallelGCThreads; ++i)
  1420       ret += data[i];
  1421     return ret / (double) ParallelGCThreads;
  1422   } else {
  1423     return data[0];
  1427 double G1CollectorPolicy::max_value (double* data) {
  1428   if (ParallelGCThreads > 0) {
  1429     double ret = data[0];
  1430     for (uint i = 1; i < ParallelGCThreads; ++i)
  1431       if (data[i] > ret)
  1432         ret = data[i];
  1433     return ret;
  1434   } else {
  1435     return data[0];
  1439 double G1CollectorPolicy::sum_of_values (double* data) {
  1440   if (ParallelGCThreads > 0) {
  1441     double sum = 0.0;
  1442     for (uint i = 0; i < ParallelGCThreads; i++)
  1443       sum += data[i];
  1444     return sum;
  1445   } else {
  1446     return data[0];
  1450 double G1CollectorPolicy::max_sum (double* data1,
  1451                                    double* data2) {
  1452   double ret = data1[0] + data2[0];
  1454   if (ParallelGCThreads > 0) {
  1455     for (uint i = 1; i < ParallelGCThreads; ++i) {
  1456       double data = data1[i] + data2[i];
  1457       if (data > ret)
  1458         ret = data;
  1461   return ret;
  1464 // Anything below that is considered to be zero
  1465 #define MIN_TIMER_GRANULARITY 0.0000001
  1467 void G1CollectorPolicy::record_collection_pause_end(bool popular,
  1468                                                     bool abandoned) {
  1469   double end_time_sec = os::elapsedTime();
  1470   double elapsed_ms = _last_pause_time_ms;
  1471   bool parallel = ParallelGCThreads > 0;
  1472   double evac_ms = (end_time_sec - _cur_G1_strong_roots_end_sec) * 1000.0;
  1473   size_t rs_size =
  1474     _cur_collection_pause_used_regions_at_start - collection_set_size();
  1475   size_t cur_used_bytes = _g1->used();
  1476   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
  1477   bool last_pause_included_initial_mark = false;
  1478   bool update_stats = !abandoned && !_g1->evacuation_failed();
  1480 #ifndef PRODUCT
  1481   if (G1YoungSurvRateVerbose) {
  1482     gclog_or_tty->print_cr("");
  1483     _short_lived_surv_rate_group->print();
  1484     // do that for any other surv rate groups too
  1486 #endif // PRODUCT
  1488   checkpoint_conc_overhead();
  1490   if (in_young_gc_mode()) {
  1491     last_pause_included_initial_mark = _should_initiate_conc_mark;
  1492     if (last_pause_included_initial_mark)
  1493       record_concurrent_mark_init_end_pre(0.0);
  1495     size_t min_used_targ =
  1496       (_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta);
  1498     if (cur_used_bytes > min_used_targ) {
  1499       if (cur_used_bytes <= _prev_collection_pause_used_at_end_bytes) {
  1500       } else if (!_g1->mark_in_progress() && !_last_full_young_gc) {
  1501         _should_initiate_conc_mark = true;
  1505     _prev_collection_pause_used_at_end_bytes = cur_used_bytes;
  1508   _mmu_tracker->add_pause(end_time_sec - elapsed_ms/1000.0,
  1509                           end_time_sec, false);
  1511   guarantee(_cur_collection_pause_used_regions_at_start >=
  1512             collection_set_size(),
  1513             "Negative RS size?");
  1515   // This assert is exempted when we're doing parallel collection pauses,
  1516   // because the fragmentation caused by the parallel GC allocation buffers
  1517   // can lead to more memory being used during collection than was used
  1518   // before. Best leave this out until the fragmentation problem is fixed.
  1519   // Pauses in which evacuation failed can also lead to negative
  1520   // collections, since no space is reclaimed from a region containing an
  1521   // object whose evacuation failed.
  1522   // Further, we're now always doing parallel collection.  But I'm still
  1523   // leaving this here as a placeholder for a more precise assertion later.
  1524   // (DLD, 10/05.)
  1525   assert((true || parallel) // Always using GC LABs now.
  1526          || _g1->evacuation_failed()
  1527          || _cur_collection_pause_used_at_start_bytes >= cur_used_bytes,
  1528          "Negative collection");
  1530   size_t freed_bytes =
  1531     _cur_collection_pause_used_at_start_bytes - cur_used_bytes;
  1532   size_t surviving_bytes = _collection_set_bytes_used_before - freed_bytes;
  1533   double survival_fraction =
  1534     (double)surviving_bytes/
  1535     (double)_collection_set_bytes_used_before;
  1537   _n_pauses++;
  1539   if (update_stats) {
  1540     _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
  1541     _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
  1542     _recent_evac_times_ms->add(evac_ms);
  1543     _recent_pause_times_ms->add(elapsed_ms);
  1545     _recent_rs_sizes->add(rs_size);
  1547     // We exempt parallel collection from this check because Alloc Buffer
  1548     // fragmentation can produce negative collections.  Same with evac
  1549     // failure.
  1550     // Further, we're now always doing parallel collection.  But I'm still
  1551     // leaving this here as a placeholder for a more precise assertion later.
  1552     // (DLD, 10/05.
  1553     assert((true || parallel)
  1554            || _g1->evacuation_failed()
  1555            || surviving_bytes <= _collection_set_bytes_used_before,
  1556            "Or else negative collection!");
  1557     _recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
  1558     _recent_CS_bytes_surviving->add(surviving_bytes);
  1560     // this is where we update the allocation rate of the application
  1561     double app_time_ms =
  1562       (_cur_collection_start_sec * 1000.0 - _prev_collection_pause_end_ms);
  1563     if (app_time_ms < MIN_TIMER_GRANULARITY) {
  1564       // This usually happens due to the timer not having the required
  1565       // granularity. Some Linuxes are the usual culprits.
  1566       // We'll just set it to something (arbitrarily) small.
  1567       app_time_ms = 1.0;
  1569     size_t regions_allocated =
  1570       (_region_num_young - _prev_region_num_young) +
  1571       (_region_num_tenured - _prev_region_num_tenured);
  1572     double alloc_rate_ms = (double) regions_allocated / app_time_ms;
  1573     _alloc_rate_ms_seq->add(alloc_rate_ms);
  1574     _prev_region_num_young   = _region_num_young;
  1575     _prev_region_num_tenured = _region_num_tenured;
  1577     double interval_ms =
  1578       (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
  1579     update_recent_gc_times(end_time_sec, elapsed_ms);
  1580     _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
  1581     assert(recent_avg_pause_time_ratio() < 1.00, "All GC?");
  1584   if (G1PolicyVerbose > 1) {
  1585     gclog_or_tty->print_cr("   Recording collection pause(%d)", _n_pauses);
  1588   PauseSummary* summary;
  1589   if (!abandoned && !popular)
  1590     summary = _non_pop_summary;
  1591   else if (!abandoned && popular)
  1592     summary = _pop_summary;
  1593   else if (abandoned && !popular)
  1594     summary = _non_pop_abandoned_summary;
  1595   else if (abandoned && popular)
  1596     summary = _pop_abandoned_summary;
  1597   else
  1598     guarantee(false, "should not get here!");
  1600   double pop_update_rs_time;
  1601   double pop_update_rs_processed_buffers;
  1602   double pop_scan_rs_time;
  1603   double pop_closure_app_time;
  1604   double pop_other_time;
  1606   if (popular) {
  1607     PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
  1608     guarantee(preamble_summary != NULL, "should not be null!");
  1610     pop_update_rs_time = avg_value(_pop_par_last_update_rs_times_ms);
  1611     pop_update_rs_processed_buffers =
  1612       sum_of_values(_pop_par_last_update_rs_processed_buffers);
  1613     pop_scan_rs_time = avg_value(_pop_par_last_scan_rs_times_ms);
  1614     pop_closure_app_time = avg_value(_pop_par_last_closure_app_times_ms);
  1615     pop_other_time = _cur_popular_preamble_time_ms -
  1616       (pop_update_rs_time + pop_scan_rs_time + pop_closure_app_time +
  1617        _cur_popular_evac_time_ms);
  1619     preamble_summary->record_pop_preamble_time_ms(_cur_popular_preamble_time_ms);
  1620     preamble_summary->record_pop_update_rs_time_ms(pop_update_rs_time);
  1621     preamble_summary->record_pop_scan_rs_time_ms(pop_scan_rs_time);
  1622     preamble_summary->record_pop_closure_app_time_ms(pop_closure_app_time);
  1623     preamble_summary->record_pop_evacuation_time_ms(_cur_popular_evac_time_ms);
  1624     preamble_summary->record_pop_other_time_ms(pop_other_time);
  1627   double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
  1628   double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
  1629   double scan_only_time = avg_value(_par_last_scan_only_times_ms);
  1630   double scan_only_regions_scanned =
  1631     sum_of_values(_par_last_scan_only_regions_scanned);
  1632   double update_rs_time = avg_value(_par_last_update_rs_times_ms);
  1633   double update_rs_processed_buffers =
  1634     sum_of_values(_par_last_update_rs_processed_buffers);
  1635   double scan_rs_time = avg_value(_par_last_scan_rs_times_ms);
  1636   double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
  1637   double termination_time = avg_value(_par_last_termination_times_ms);
  1639   double parallel_other_time;
  1640   if (update_stats) {
  1641     MainBodySummary* body_summary = summary->main_body_summary();
  1642     guarantee(body_summary != NULL, "should not be null!");
  1644     if (_satb_drain_time_set)
  1645       body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
  1646     else
  1647       body_summary->record_satb_drain_time_ms(0.0);
  1648     body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
  1649     body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
  1650     body_summary->record_scan_only_time_ms(scan_only_time);
  1651     body_summary->record_update_rs_time_ms(update_rs_time);
  1652     body_summary->record_scan_rs_time_ms(scan_rs_time);
  1653     body_summary->record_obj_copy_time_ms(obj_copy_time);
  1654     if (parallel) {
  1655       body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
  1656       body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
  1657       body_summary->record_termination_time_ms(termination_time);
  1658       parallel_other_time = _cur_collection_par_time_ms -
  1659         (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
  1660          scan_only_time + scan_rs_time + obj_copy_time + termination_time);
  1661       body_summary->record_parallel_other_time_ms(parallel_other_time);
  1663     body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
  1666   if (G1PolicyVerbose > 1) {
  1667     gclog_or_tty->print_cr("      ET: %10.6f ms           (avg: %10.6f ms)\n"
  1668                            "        CH Strong: %10.6f ms    (avg: %10.6f ms)\n"
  1669                            "        G1 Strong: %10.6f ms    (avg: %10.6f ms)\n"
  1670                            "        Evac:      %10.6f ms    (avg: %10.6f ms)\n"
  1671                            "       ET-RS:  %10.6f ms      (avg: %10.6f ms)\n"
  1672                            "      |RS|: " SIZE_FORMAT,
  1673                            elapsed_ms, recent_avg_time_for_pauses_ms(),
  1674                            _cur_CH_strong_roots_dur_ms, recent_avg_time_for_CH_strong_ms(),
  1675                            _cur_G1_strong_roots_dur_ms, recent_avg_time_for_G1_strong_ms(),
  1676                            evac_ms, recent_avg_time_for_evac_ms(),
  1677                            scan_rs_time,
  1678                            recent_avg_time_for_pauses_ms() -
  1679                            recent_avg_time_for_G1_strong_ms(),
  1680                            rs_size);
  1682     gclog_or_tty->print_cr("       Used at start: " SIZE_FORMAT"K"
  1683                            "       At end " SIZE_FORMAT "K\n"
  1684                            "       garbage      : " SIZE_FORMAT "K"
  1685                            "       of     " SIZE_FORMAT "K\n"
  1686                            "       survival     : %6.2f%%  (%6.2f%% avg)",
  1687                            _cur_collection_pause_used_at_start_bytes/K,
  1688                            _g1->used()/K, freed_bytes/K,
  1689                            _collection_set_bytes_used_before/K,
  1690                            survival_fraction*100.0,
  1691                            recent_avg_survival_fraction()*100.0);
  1692     gclog_or_tty->print_cr("       Recent %% gc pause time: %6.2f",
  1693                            recent_avg_pause_time_ratio() * 100.0);
  1696   double other_time_ms = elapsed_ms;
  1697   if (popular)
  1698     other_time_ms -= _cur_popular_preamble_time_ms;
  1700   if (!abandoned) {
  1701     if (_satb_drain_time_set)
  1702       other_time_ms -= _cur_satb_drain_time_ms;
  1704     if (parallel)
  1705       other_time_ms -= _cur_collection_par_time_ms + _cur_clear_ct_time_ms;
  1706     else
  1707       other_time_ms -=
  1708         update_rs_time +
  1709         ext_root_scan_time + mark_stack_scan_time + scan_only_time +
  1710         scan_rs_time + obj_copy_time;
  1713   if (PrintGCDetails) {
  1714     gclog_or_tty->print_cr("%s%s, %1.8lf secs]",
  1715                            (popular && !abandoned) ? " (popular)" :
  1716                            (!popular && abandoned) ? " (abandoned)" :
  1717                            (popular && abandoned) ? " (popular/abandoned)" : "",
  1718                            (last_pause_included_initial_mark) ? " (initial-mark)" : "",
  1719                            elapsed_ms / 1000.0);
  1721     if (!abandoned) {
  1722       if (_satb_drain_time_set)
  1723         print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
  1724       if (_last_satb_drain_processed_buffers >= 0)
  1725         print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
  1727     if (popular)
  1728       print_stats(1, "Popularity Preamble", _cur_popular_preamble_time_ms);
  1729     if (parallel) {
  1730       if (popular) {
  1731         print_par_stats(2, "Update RS (Start)", _pop_par_last_update_rs_start_times_ms, false);
  1732         print_par_stats(2, "Update RS", _pop_par_last_update_rs_times_ms);
  1733         if (G1RSBarrierUseQueue)
  1734           print_par_buffers(3, "Processed Buffers",
  1735                             _pop_par_last_update_rs_processed_buffers, true);
  1736         print_par_stats(2, "Scan RS", _pop_par_last_scan_rs_times_ms);
  1737         print_par_stats(2, "Closure app", _pop_par_last_closure_app_times_ms);
  1738         print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
  1739         print_stats(2, "Other", pop_other_time);
  1741       if (!abandoned) {
  1742         print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
  1743         if (!popular) {
  1744           print_par_stats(2, "Update RS (Start)", _par_last_update_rs_start_times_ms, false);
  1745           print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
  1746           if (G1RSBarrierUseQueue)
  1747             print_par_buffers(3, "Processed Buffers",
  1748                               _par_last_update_rs_processed_buffers, true);
  1750         print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
  1751         print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
  1752         print_par_stats(2, "Scan-Only Scanning", _par_last_scan_only_times_ms);
  1753         print_par_buffers(3, "Scan-Only Regions",
  1754                           _par_last_scan_only_regions_scanned, true);
  1755         print_par_stats(2, "Scan RS", _par_last_scan_rs_times_ms);
  1756         print_par_stats(2, "Object Copy", _par_last_obj_copy_times_ms);
  1757         print_par_stats(2, "Termination", _par_last_termination_times_ms);
  1758         print_stats(2, "Other", parallel_other_time);
  1759         print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
  1761     } else {
  1762       if (popular) {
  1763         print_stats(2, "Update RS", pop_update_rs_time);
  1764         if (G1RSBarrierUseQueue)
  1765           print_stats(3, "Processed Buffers",
  1766                       (int)pop_update_rs_processed_buffers);
  1767         print_stats(2, "Scan RS", pop_scan_rs_time);
  1768         print_stats(2, "Closure App", pop_closure_app_time);
  1769         print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
  1770         print_stats(2, "Other", pop_other_time);
  1772       if (!abandoned) {
  1773         if (!popular) {
  1774           print_stats(1, "Update RS", update_rs_time);
  1775           if (G1RSBarrierUseQueue)
  1776             print_stats(2, "Processed Buffers",
  1777                         (int)update_rs_processed_buffers);
  1779         print_stats(1, "Ext Root Scanning", ext_root_scan_time);
  1780         print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
  1781         print_stats(1, "Scan-Only Scanning", scan_only_time);
  1782         print_stats(1, "Scan RS", scan_rs_time);
  1783         print_stats(1, "Object Copying", obj_copy_time);
  1786     print_stats(1, "Other", other_time_ms);
  1787     for (int i = 0; i < _aux_num; ++i) {
  1788       if (_cur_aux_times_set[i]) {
  1789         char buffer[96];
  1790         sprintf(buffer, "Aux%d", i);
  1791         print_stats(1, buffer, _cur_aux_times_ms[i]);
  1795   if (PrintGCDetails)
  1796     gclog_or_tty->print("   [");
  1797   if (PrintGC || PrintGCDetails)
  1798     _g1->print_size_transition(gclog_or_tty,
  1799                                _cur_collection_pause_used_at_start_bytes,
  1800                                _g1->used(), _g1->capacity());
  1801   if (PrintGCDetails)
  1802     gclog_or_tty->print_cr("]");
  1804   _all_pause_times_ms->add(elapsed_ms);
  1805   summary->record_total_time_ms(elapsed_ms);
  1806   summary->record_other_time_ms(other_time_ms);
  1807   for (int i = 0; i < _aux_num; ++i)
  1808     if (_cur_aux_times_set[i])
  1809       _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
  1811   // Reset marks-between-pauses counter.
  1812   _n_marks_since_last_pause = 0;
  1814   // Update the efficiency-since-mark vars.
  1815   double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
  1816   if (elapsed_ms < MIN_TIMER_GRANULARITY) {
  1817     // This usually happens due to the timer not having the required
  1818     // granularity. Some Linuxes are the usual culprits.
  1819     // We'll just set it to something (arbitrarily) small.
  1820     proc_ms = 1.0;
  1822   double cur_efficiency = (double) freed_bytes / proc_ms;
  1824   bool new_in_marking_window = _in_marking_window;
  1825   bool new_in_marking_window_im = false;
  1826   if (_should_initiate_conc_mark) {
  1827     new_in_marking_window = true;
  1828     new_in_marking_window_im = true;
  1831   if (in_young_gc_mode()) {
  1832     if (_last_full_young_gc) {
  1833       set_full_young_gcs(false);
  1834       _last_full_young_gc = false;
  1837     if ( !_last_young_gc_full ) {
  1838       if ( _should_revert_to_full_young_gcs ||
  1839            _known_garbage_ratio < 0.05 ||
  1840            (adaptive_young_list_length() &&
  1841            (get_gc_eff_factor() * cur_efficiency < predict_young_gc_eff())) ) {
  1842         set_full_young_gcs(true);
  1845     _should_revert_to_full_young_gcs = false;
  1847     if (_last_young_gc_full && !_during_marking)
  1848       _young_gc_eff_seq->add(cur_efficiency);
  1851   _short_lived_surv_rate_group->start_adding_regions();
  1852   // do that for any other surv rate groupsx
  1854   // <NEW PREDICTION>
  1856   if (!popular && update_stats) {
  1857     double pause_time_ms = elapsed_ms;
  1859     size_t diff = 0;
  1860     if (_max_pending_cards >= _pending_cards)
  1861       diff = _max_pending_cards - _pending_cards;
  1862     _pending_card_diff_seq->add((double) diff);
  1864     double cost_per_card_ms = 0.0;
  1865     if (_pending_cards > 0) {
  1866       cost_per_card_ms = update_rs_time / (double) _pending_cards;
  1867       _cost_per_card_ms_seq->add(cost_per_card_ms);
  1870     double cost_per_scan_only_region_ms = 0.0;
  1871     if (scan_only_regions_scanned > 0.0) {
  1872       cost_per_scan_only_region_ms =
  1873         scan_only_time / scan_only_regions_scanned;
  1874       if (_in_marking_window_im)
  1875         _cost_per_scan_only_region_ms_during_cm_seq->add(cost_per_scan_only_region_ms);
  1876       else
  1877         _cost_per_scan_only_region_ms_seq->add(cost_per_scan_only_region_ms);
  1880     size_t cards_scanned = _g1->cards_scanned();
  1882     double cost_per_entry_ms = 0.0;
  1883     if (cards_scanned > 10) {
  1884       cost_per_entry_ms = scan_rs_time / (double) cards_scanned;
  1885       if (_last_young_gc_full)
  1886         _cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1887       else
  1888         _partially_young_cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1891     if (_max_rs_lengths > 0) {
  1892       double cards_per_entry_ratio =
  1893         (double) cards_scanned / (double) _max_rs_lengths;
  1894       if (_last_young_gc_full)
  1895         _fully_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1896       else
  1897         _partially_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1900     size_t rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
  1901     if (rs_length_diff >= 0)
  1902       _rs_length_diff_seq->add((double) rs_length_diff);
  1904     size_t copied_bytes = surviving_bytes;
  1905     double cost_per_byte_ms = 0.0;
  1906     if (copied_bytes > 0) {
  1907       cost_per_byte_ms = obj_copy_time / (double) copied_bytes;
  1908       if (_in_marking_window)
  1909         _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
  1910       else
  1911         _cost_per_byte_ms_seq->add(cost_per_byte_ms);
  1914     double all_other_time_ms = pause_time_ms -
  1915       (update_rs_time + scan_only_time + scan_rs_time + obj_copy_time +
  1916        _mark_closure_time_ms + termination_time);
  1918     double young_other_time_ms = 0.0;
  1919     if (_recorded_young_regions > 0) {
  1920       young_other_time_ms =
  1921         _recorded_young_cset_choice_time_ms +
  1922         _recorded_young_free_cset_time_ms;
  1923       _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
  1924                                              (double) _recorded_young_regions);
  1926     double non_young_other_time_ms = 0.0;
  1927     if (_recorded_non_young_regions > 0) {
  1928       non_young_other_time_ms =
  1929         _recorded_non_young_cset_choice_time_ms +
  1930         _recorded_non_young_free_cset_time_ms;
  1932       _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
  1933                                          (double) _recorded_non_young_regions);
  1936     double constant_other_time_ms = all_other_time_ms -
  1937       (young_other_time_ms + non_young_other_time_ms);
  1938     _constant_other_time_ms_seq->add(constant_other_time_ms);
  1940     double survival_ratio = 0.0;
  1941     if (_bytes_in_collection_set_before_gc > 0) {
  1942       survival_ratio = (double) bytes_in_to_space_during_gc() /
  1943         (double) _bytes_in_collection_set_before_gc;
  1946     _pending_cards_seq->add((double) _pending_cards);
  1947     _scanned_cards_seq->add((double) cards_scanned);
  1948     _rs_lengths_seq->add((double) _max_rs_lengths);
  1950     double expensive_region_limit_ms =
  1951       (double) G1MaxPauseTimeMS - predict_constant_other_time_ms();
  1952     if (expensive_region_limit_ms < 0.0) {
  1953       // this means that the other time was predicted to be longer than
  1954       // than the max pause time
  1955       expensive_region_limit_ms = (double) G1MaxPauseTimeMS;
  1957     _expensive_region_limit_ms = expensive_region_limit_ms;
  1959     if (PREDICTIONS_VERBOSE) {
  1960       gclog_or_tty->print_cr("");
  1961       gclog_or_tty->print_cr("PREDICTIONS %1.4lf %d "
  1962                     "REGIONS %d %d %d %d "
  1963                     "PENDING_CARDS %d %d "
  1964                     "CARDS_SCANNED %d %d "
  1965                     "RS_LENGTHS %d %d "
  1966                     "SCAN_ONLY_SCAN %1.6lf %1.6lf "
  1967                     "RS_UPDATE %1.6lf %1.6lf RS_SCAN %1.6lf %1.6lf "
  1968                     "SURVIVAL_RATIO %1.6lf %1.6lf "
  1969                     "OBJECT_COPY %1.6lf %1.6lf OTHER_CONSTANT %1.6lf %1.6lf "
  1970                     "OTHER_YOUNG %1.6lf %1.6lf "
  1971                     "OTHER_NON_YOUNG %1.6lf %1.6lf "
  1972                     "VTIME_DIFF %1.6lf TERMINATION %1.6lf "
  1973                     "ELAPSED %1.6lf %1.6lf ",
  1974                     _cur_collection_start_sec,
  1975                     (!_last_young_gc_full) ? 2 :
  1976                     (last_pause_included_initial_mark) ? 1 : 0,
  1977                     _recorded_region_num,
  1978                     _recorded_young_regions,
  1979                     _recorded_scan_only_regions,
  1980                     _recorded_non_young_regions,
  1981                     _predicted_pending_cards, _pending_cards,
  1982                     _predicted_cards_scanned, cards_scanned,
  1983                     _predicted_rs_lengths, _max_rs_lengths,
  1984                     _predicted_scan_only_scan_time_ms, scan_only_time,
  1985                     _predicted_rs_update_time_ms, update_rs_time,
  1986                     _predicted_rs_scan_time_ms, scan_rs_time,
  1987                     _predicted_survival_ratio, survival_ratio,
  1988                     _predicted_object_copy_time_ms, obj_copy_time,
  1989                     _predicted_constant_other_time_ms, constant_other_time_ms,
  1990                     _predicted_young_other_time_ms, young_other_time_ms,
  1991                     _predicted_non_young_other_time_ms,
  1992                     non_young_other_time_ms,
  1993                     _vtime_diff_ms, termination_time,
  1994                     _predicted_pause_time_ms, elapsed_ms);
  1997     if (G1PolicyVerbose > 0) {
  1998       gclog_or_tty->print_cr("Pause Time, predicted: %1.4lfms (predicted %s), actual: %1.4lfms",
  1999                     _predicted_pause_time_ms,
  2000                     (_within_target) ? "within" : "outside",
  2001                     elapsed_ms);
  2006   _in_marking_window = new_in_marking_window;
  2007   _in_marking_window_im = new_in_marking_window_im;
  2008   _free_regions_at_end_of_collection = _g1->free_regions();
  2009   _scan_only_regions_at_end_of_collection = _g1->young_list_length();
  2010   calculate_young_list_min_length();
  2011   calculate_young_list_target_config();
  2013   // </NEW PREDICTION>
  2015   _target_pause_time_ms = -1.0;
  2018 // <NEW PREDICTION>
  2020 double
  2021 G1CollectorPolicy::
  2022 predict_young_collection_elapsed_time_ms(size_t adjustment) {
  2023   guarantee( adjustment == 0 || adjustment == 1, "invariant" );
  2025   G1CollectedHeap* g1h = G1CollectedHeap::heap();
  2026   size_t young_num = g1h->young_list_length();
  2027   if (young_num == 0)
  2028     return 0.0;
  2030   young_num += adjustment;
  2031   size_t pending_cards = predict_pending_cards();
  2032   size_t rs_lengths = g1h->young_list_sampled_rs_lengths() +
  2033                       predict_rs_length_diff();
  2034   size_t card_num;
  2035   if (full_young_gcs())
  2036     card_num = predict_young_card_num(rs_lengths);
  2037   else
  2038     card_num = predict_non_young_card_num(rs_lengths);
  2039   size_t young_byte_size = young_num * HeapRegion::GrainBytes;
  2040   double accum_yg_surv_rate =
  2041     _short_lived_surv_rate_group->accum_surv_rate(adjustment);
  2043   size_t bytes_to_copy =
  2044     (size_t) (accum_yg_surv_rate * (double) HeapRegion::GrainBytes);
  2046   return
  2047     predict_rs_update_time_ms(pending_cards) +
  2048     predict_rs_scan_time_ms(card_num) +
  2049     predict_object_copy_time_ms(bytes_to_copy) +
  2050     predict_young_other_time_ms(young_num) +
  2051     predict_constant_other_time_ms();
  2054 double
  2055 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
  2056   size_t rs_length = predict_rs_length_diff();
  2057   size_t card_num;
  2058   if (full_young_gcs())
  2059     card_num = predict_young_card_num(rs_length);
  2060   else
  2061     card_num = predict_non_young_card_num(rs_length);
  2062   return predict_base_elapsed_time_ms(pending_cards, card_num);
  2065 double
  2066 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
  2067                                                 size_t scanned_cards) {
  2068   return
  2069     predict_rs_update_time_ms(pending_cards) +
  2070     predict_rs_scan_time_ms(scanned_cards) +
  2071     predict_constant_other_time_ms();
  2074 double
  2075 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
  2076                                                   bool young) {
  2077   size_t rs_length = hr->rem_set()->occupied();
  2078   size_t card_num;
  2079   if (full_young_gcs())
  2080     card_num = predict_young_card_num(rs_length);
  2081   else
  2082     card_num = predict_non_young_card_num(rs_length);
  2083   size_t bytes_to_copy = predict_bytes_to_copy(hr);
  2085   double region_elapsed_time_ms =
  2086     predict_rs_scan_time_ms(card_num) +
  2087     predict_object_copy_time_ms(bytes_to_copy);
  2089   if (young)
  2090     region_elapsed_time_ms += predict_young_other_time_ms(1);
  2091   else
  2092     region_elapsed_time_ms += predict_non_young_other_time_ms(1);
  2094   return region_elapsed_time_ms;
  2097 size_t
  2098 G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
  2099   size_t bytes_to_copy;
  2100   if (hr->is_marked())
  2101     bytes_to_copy = hr->max_live_bytes();
  2102   else {
  2103     guarantee( hr->is_young() && hr->age_in_surv_rate_group() != -1,
  2104                "invariant" );
  2105     int age = hr->age_in_surv_rate_group();
  2106     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
  2107     bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
  2110   return bytes_to_copy;
  2113 void
  2114 G1CollectorPolicy::start_recording_regions() {
  2115   _recorded_rs_lengths            = 0;
  2116   _recorded_scan_only_regions     = 0;
  2117   _recorded_young_regions         = 0;
  2118   _recorded_non_young_regions     = 0;
  2120 #if PREDICTIONS_VERBOSE
  2121   _predicted_rs_lengths           = 0;
  2122   _predicted_cards_scanned        = 0;
  2124   _recorded_marked_bytes          = 0;
  2125   _recorded_young_bytes           = 0;
  2126   _predicted_bytes_to_copy        = 0;
  2127 #endif // PREDICTIONS_VERBOSE
  2130 void
  2131 G1CollectorPolicy::record_cset_region(HeapRegion* hr, bool young) {
  2132   if (young) {
  2133     ++_recorded_young_regions;
  2134   } else {
  2135     ++_recorded_non_young_regions;
  2137 #if PREDICTIONS_VERBOSE
  2138   if (young) {
  2139     _recorded_young_bytes += hr->used();
  2140   } else {
  2141     _recorded_marked_bytes += hr->max_live_bytes();
  2143   _predicted_bytes_to_copy += predict_bytes_to_copy(hr);
  2144 #endif // PREDICTIONS_VERBOSE
  2146   size_t rs_length = hr->rem_set()->occupied();
  2147   _recorded_rs_lengths += rs_length;
  2150 void
  2151 G1CollectorPolicy::record_scan_only_regions(size_t scan_only_length) {
  2152   _recorded_scan_only_regions = scan_only_length;
  2155 void
  2156 G1CollectorPolicy::end_recording_regions() {
  2157 #if PREDICTIONS_VERBOSE
  2158   _predicted_pending_cards = predict_pending_cards();
  2159   _predicted_rs_lengths = _recorded_rs_lengths + predict_rs_length_diff();
  2160   if (full_young_gcs())
  2161     _predicted_cards_scanned += predict_young_card_num(_predicted_rs_lengths);
  2162   else
  2163     _predicted_cards_scanned +=
  2164       predict_non_young_card_num(_predicted_rs_lengths);
  2165   _recorded_region_num = _recorded_young_regions + _recorded_non_young_regions;
  2167   _predicted_scan_only_scan_time_ms =
  2168     predict_scan_only_time_ms(_recorded_scan_only_regions);
  2169   _predicted_rs_update_time_ms =
  2170     predict_rs_update_time_ms(_g1->pending_card_num());
  2171   _predicted_rs_scan_time_ms =
  2172     predict_rs_scan_time_ms(_predicted_cards_scanned);
  2173   _predicted_object_copy_time_ms =
  2174     predict_object_copy_time_ms(_predicted_bytes_to_copy);
  2175   _predicted_constant_other_time_ms =
  2176     predict_constant_other_time_ms();
  2177   _predicted_young_other_time_ms =
  2178     predict_young_other_time_ms(_recorded_young_regions);
  2179   _predicted_non_young_other_time_ms =
  2180     predict_non_young_other_time_ms(_recorded_non_young_regions);
  2182   _predicted_pause_time_ms =
  2183     _predicted_scan_only_scan_time_ms +
  2184     _predicted_rs_update_time_ms +
  2185     _predicted_rs_scan_time_ms +
  2186     _predicted_object_copy_time_ms +
  2187     _predicted_constant_other_time_ms +
  2188     _predicted_young_other_time_ms +
  2189     _predicted_non_young_other_time_ms;
  2190 #endif // PREDICTIONS_VERBOSE
  2193 void G1CollectorPolicy::check_if_region_is_too_expensive(double
  2194                                                            predicted_time_ms) {
  2195   // I don't think we need to do this when in young GC mode since
  2196   // marking will be initiated next time we hit the soft limit anyway...
  2197   if (predicted_time_ms > _expensive_region_limit_ms) {
  2198     if (!in_young_gc_mode()) {
  2199         set_full_young_gcs(true);
  2200       _should_initiate_conc_mark = true;
  2201     } else
  2202       // no point in doing another partial one
  2203       _should_revert_to_full_young_gcs = true;
  2207 // </NEW PREDICTION>
  2210 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
  2211                                                double elapsed_ms) {
  2212   _recent_gc_times_ms->add(elapsed_ms);
  2213   _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
  2214   _prev_collection_pause_end_ms = end_time_sec * 1000.0;
  2217 double G1CollectorPolicy::recent_avg_time_for_pauses_ms() {
  2218   if (_recent_pause_times_ms->num() == 0) return (double) G1MaxPauseTimeMS;
  2219   else return _recent_pause_times_ms->avg();
  2222 double G1CollectorPolicy::recent_avg_time_for_CH_strong_ms() {
  2223   if (_recent_CH_strong_roots_times_ms->num() == 0)
  2224     return (double)G1MaxPauseTimeMS/3.0;
  2225   else return _recent_CH_strong_roots_times_ms->avg();
  2228 double G1CollectorPolicy::recent_avg_time_for_G1_strong_ms() {
  2229   if (_recent_G1_strong_roots_times_ms->num() == 0)
  2230     return (double)G1MaxPauseTimeMS/3.0;
  2231   else return _recent_G1_strong_roots_times_ms->avg();
  2234 double G1CollectorPolicy::recent_avg_time_for_evac_ms() {
  2235   if (_recent_evac_times_ms->num() == 0) return (double)G1MaxPauseTimeMS/3.0;
  2236   else return _recent_evac_times_ms->avg();
  2239 int G1CollectorPolicy::number_of_recent_gcs() {
  2240   assert(_recent_CH_strong_roots_times_ms->num() ==
  2241          _recent_G1_strong_roots_times_ms->num(), "Sequence out of sync");
  2242   assert(_recent_G1_strong_roots_times_ms->num() ==
  2243          _recent_evac_times_ms->num(), "Sequence out of sync");
  2244   assert(_recent_evac_times_ms->num() ==
  2245          _recent_pause_times_ms->num(), "Sequence out of sync");
  2246   assert(_recent_pause_times_ms->num() ==
  2247          _recent_CS_bytes_used_before->num(), "Sequence out of sync");
  2248   assert(_recent_CS_bytes_used_before->num() ==
  2249          _recent_CS_bytes_surviving->num(), "Sequence out of sync");
  2250   return _recent_pause_times_ms->num();
  2253 double G1CollectorPolicy::recent_avg_survival_fraction() {
  2254   return recent_avg_survival_fraction_work(_recent_CS_bytes_surviving,
  2255                                            _recent_CS_bytes_used_before);
  2258 double G1CollectorPolicy::last_survival_fraction() {
  2259   return last_survival_fraction_work(_recent_CS_bytes_surviving,
  2260                                      _recent_CS_bytes_used_before);
  2263 double
  2264 G1CollectorPolicy::recent_avg_survival_fraction_work(TruncatedSeq* surviving,
  2265                                                      TruncatedSeq* before) {
  2266   assert(surviving->num() == before->num(), "Sequence out of sync");
  2267   if (before->sum() > 0.0) {
  2268       double recent_survival_rate = surviving->sum() / before->sum();
  2269       // We exempt parallel collection from this check because Alloc Buffer
  2270       // fragmentation can produce negative collections.
  2271       // Further, we're now always doing parallel collection.  But I'm still
  2272       // leaving this here as a placeholder for a more precise assertion later.
  2273       // (DLD, 10/05.)
  2274       assert((true || ParallelGCThreads > 0) ||
  2275              _g1->evacuation_failed() ||
  2276              recent_survival_rate <= 1.0, "Or bad frac");
  2277       return recent_survival_rate;
  2278   } else {
  2279     return 1.0; // Be conservative.
  2283 double
  2284 G1CollectorPolicy::last_survival_fraction_work(TruncatedSeq* surviving,
  2285                                                TruncatedSeq* before) {
  2286   assert(surviving->num() == before->num(), "Sequence out of sync");
  2287   if (surviving->num() > 0 && before->last() > 0.0) {
  2288     double last_survival_rate = surviving->last() / before->last();
  2289     // We exempt parallel collection from this check because Alloc Buffer
  2290     // fragmentation can produce negative collections.
  2291     // Further, we're now always doing parallel collection.  But I'm still
  2292     // leaving this here as a placeholder for a more precise assertion later.
  2293     // (DLD, 10/05.)
  2294     assert((true || ParallelGCThreads > 0) ||
  2295            last_survival_rate <= 1.0, "Or bad frac");
  2296     return last_survival_rate;
  2297   } else {
  2298     return 1.0;
  2302 static const int survival_min_obs = 5;
  2303 static double survival_min_obs_limits[] = { 0.9, 0.7, 0.5, 0.3, 0.1 };
  2304 static const double min_survival_rate = 0.1;
  2306 double
  2307 G1CollectorPolicy::conservative_avg_survival_fraction_work(double avg,
  2308                                                            double latest) {
  2309   double res = avg;
  2310   if (number_of_recent_gcs() < survival_min_obs) {
  2311     res = MAX2(res, survival_min_obs_limits[number_of_recent_gcs()]);
  2313   res = MAX2(res, latest);
  2314   res = MAX2(res, min_survival_rate);
  2315   // In the parallel case, LAB fragmentation can produce "negative
  2316   // collections"; so can evac failure.  Cap at 1.0
  2317   res = MIN2(res, 1.0);
  2318   return res;
  2321 size_t G1CollectorPolicy::expansion_amount() {
  2322   if ((int)(recent_avg_pause_time_ratio() * 100.0) > G1GCPct) {
  2323     // We will double the existing space, or take G1ExpandByPctOfAvail % of
  2324     // the available expansion space, whichever is smaller, bounded below
  2325     // by a minimum expansion (unless that's all that's left.)
  2326     const size_t min_expand_bytes = 1*M;
  2327     size_t reserved_bytes = _g1->g1_reserved_obj_bytes();
  2328     size_t committed_bytes = _g1->capacity();
  2329     size_t uncommitted_bytes = reserved_bytes - committed_bytes;
  2330     size_t expand_bytes;
  2331     size_t expand_bytes_via_pct =
  2332       uncommitted_bytes * G1ExpandByPctOfAvail / 100;
  2333     expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
  2334     expand_bytes = MAX2(expand_bytes, min_expand_bytes);
  2335     expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
  2336     if (G1PolicyVerbose > 1) {
  2337       gclog_or_tty->print("Decided to expand: ratio = %5.2f, "
  2338                  "committed = %d%s, uncommited = %d%s, via pct = %d%s.\n"
  2339                  "                   Answer = %d.\n",
  2340                  recent_avg_pause_time_ratio(),
  2341                  byte_size_in_proper_unit(committed_bytes),
  2342                  proper_unit_for_byte_size(committed_bytes),
  2343                  byte_size_in_proper_unit(uncommitted_bytes),
  2344                  proper_unit_for_byte_size(uncommitted_bytes),
  2345                  byte_size_in_proper_unit(expand_bytes_via_pct),
  2346                  proper_unit_for_byte_size(expand_bytes_via_pct),
  2347                  byte_size_in_proper_unit(expand_bytes),
  2348                  proper_unit_for_byte_size(expand_bytes));
  2350     return expand_bytes;
  2351   } else {
  2352     return 0;
  2356 void G1CollectorPolicy::note_start_of_mark_thread() {
  2357   _mark_thread_startup_sec = os::elapsedTime();
  2360 class CountCSClosure: public HeapRegionClosure {
  2361   G1CollectorPolicy* _g1_policy;
  2362 public:
  2363   CountCSClosure(G1CollectorPolicy* g1_policy) :
  2364     _g1_policy(g1_policy) {}
  2365   bool doHeapRegion(HeapRegion* r) {
  2366     _g1_policy->_bytes_in_collection_set_before_gc += r->used();
  2367     return false;
  2369 };
  2371 void G1CollectorPolicy::count_CS_bytes_used() {
  2372   CountCSClosure cs_closure(this);
  2373   _g1->collection_set_iterate(&cs_closure);
  2376 static void print_indent(int level) {
  2377   for (int j = 0; j < level+1; ++j)
  2378     gclog_or_tty->print("   ");
  2381 void G1CollectorPolicy::print_summary (int level,
  2382                                        const char* str,
  2383                                        NumberSeq* seq) const {
  2384   double sum = seq->sum();
  2385   print_indent(level);
  2386   gclog_or_tty->print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
  2387                 str, sum / 1000.0, seq->avg());
  2390 void G1CollectorPolicy::print_summary_sd (int level,
  2391                                           const char* str,
  2392                                           NumberSeq* seq) const {
  2393   print_summary(level, str, seq);
  2394   print_indent(level + 5);
  2395   gclog_or_tty->print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
  2396                 seq->num(), seq->sd(), seq->maximum());
  2399 void G1CollectorPolicy::check_other_times(int level,
  2400                                         NumberSeq* other_times_ms,
  2401                                         NumberSeq* calc_other_times_ms) const {
  2402   bool should_print = false;
  2404   double max_sum = MAX2(fabs(other_times_ms->sum()),
  2405                         fabs(calc_other_times_ms->sum()));
  2406   double min_sum = MIN2(fabs(other_times_ms->sum()),
  2407                         fabs(calc_other_times_ms->sum()));
  2408   double sum_ratio = max_sum / min_sum;
  2409   if (sum_ratio > 1.1) {
  2410     should_print = true;
  2411     print_indent(level + 1);
  2412     gclog_or_tty->print_cr("## CALCULATED OTHER SUM DOESN'T MATCH RECORDED ###");
  2415   double max_avg = MAX2(fabs(other_times_ms->avg()),
  2416                         fabs(calc_other_times_ms->avg()));
  2417   double min_avg = MIN2(fabs(other_times_ms->avg()),
  2418                         fabs(calc_other_times_ms->avg()));
  2419   double avg_ratio = max_avg / min_avg;
  2420   if (avg_ratio > 1.1) {
  2421     should_print = true;
  2422     print_indent(level + 1);
  2423     gclog_or_tty->print_cr("## CALCULATED OTHER AVG DOESN'T MATCH RECORDED ###");
  2426   if (other_times_ms->sum() < -0.01) {
  2427     print_indent(level + 1);
  2428     gclog_or_tty->print_cr("## RECORDED OTHER SUM IS NEGATIVE ###");
  2431   if (other_times_ms->avg() < -0.01) {
  2432     print_indent(level + 1);
  2433     gclog_or_tty->print_cr("## RECORDED OTHER AVG IS NEGATIVE ###");
  2436   if (calc_other_times_ms->sum() < -0.01) {
  2437     should_print = true;
  2438     print_indent(level + 1);
  2439     gclog_or_tty->print_cr("## CALCULATED OTHER SUM IS NEGATIVE ###");
  2442   if (calc_other_times_ms->avg() < -0.01) {
  2443     should_print = true;
  2444     print_indent(level + 1);
  2445     gclog_or_tty->print_cr("## CALCULATED OTHER AVG IS NEGATIVE ###");
  2448   if (should_print)
  2449     print_summary(level, "Other(Calc)", calc_other_times_ms);
  2452 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
  2453   bool parallel = ParallelGCThreads > 0;
  2454   MainBodySummary*    body_summary = summary->main_body_summary();
  2455   PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
  2457   if (summary->get_total_seq()->num() > 0) {
  2458     print_summary_sd(0,
  2459                      (preamble_summary == NULL) ? "Non-Popular Pauses" :
  2460                      "Popular Pauses",
  2461                      summary->get_total_seq());
  2462     if (preamble_summary != NULL) {
  2463       print_summary(1, "Popularity Preamble",
  2464                     preamble_summary->get_pop_preamble_seq());
  2465       print_summary(2, "Update RS", preamble_summary->get_pop_update_rs_seq());
  2466       print_summary(2, "Scan RS", preamble_summary->get_pop_scan_rs_seq());
  2467       print_summary(2, "Closure App",
  2468                     preamble_summary->get_pop_closure_app_seq());
  2469       print_summary(2, "Evacuation",
  2470                     preamble_summary->get_pop_evacuation_seq());
  2471       print_summary(2, "Other", preamble_summary->get_pop_other_seq());
  2473         NumberSeq* other_parts[] = {
  2474           preamble_summary->get_pop_update_rs_seq(),
  2475           preamble_summary->get_pop_scan_rs_seq(),
  2476           preamble_summary->get_pop_closure_app_seq(),
  2477           preamble_summary->get_pop_evacuation_seq()
  2478         };
  2479         NumberSeq calc_other_times_ms(preamble_summary->get_pop_preamble_seq(),
  2480                                       4, other_parts);
  2481         check_other_times(2, preamble_summary->get_pop_other_seq(),
  2482                           &calc_other_times_ms);
  2485     if (body_summary != NULL) {
  2486       print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
  2487       if (parallel) {
  2488         print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
  2489         print_summary(2, "Update RS", body_summary->get_update_rs_seq());
  2490         print_summary(2, "Ext Root Scanning",
  2491                       body_summary->get_ext_root_scan_seq());
  2492         print_summary(2, "Mark Stack Scanning",
  2493                       body_summary->get_mark_stack_scan_seq());
  2494         print_summary(2, "Scan-Only Scanning",
  2495                       body_summary->get_scan_only_seq());
  2496         print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
  2497         print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
  2498         print_summary(2, "Termination", body_summary->get_termination_seq());
  2499         print_summary(2, "Other", body_summary->get_parallel_other_seq());
  2501           NumberSeq* other_parts[] = {
  2502             body_summary->get_update_rs_seq(),
  2503             body_summary->get_ext_root_scan_seq(),
  2504             body_summary->get_mark_stack_scan_seq(),
  2505             body_summary->get_scan_only_seq(),
  2506             body_summary->get_scan_rs_seq(),
  2507             body_summary->get_obj_copy_seq(),
  2508             body_summary->get_termination_seq()
  2509           };
  2510           NumberSeq calc_other_times_ms(body_summary->get_parallel_seq(),
  2511                                         7, other_parts);
  2512           check_other_times(2, body_summary->get_parallel_other_seq(),
  2513                             &calc_other_times_ms);
  2515         print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
  2516         print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
  2517       } else {
  2518         print_summary(1, "Update RS", body_summary->get_update_rs_seq());
  2519         print_summary(1, "Ext Root Scanning",
  2520                       body_summary->get_ext_root_scan_seq());
  2521         print_summary(1, "Mark Stack Scanning",
  2522                       body_summary->get_mark_stack_scan_seq());
  2523         print_summary(1, "Scan-Only Scanning",
  2524                       body_summary->get_scan_only_seq());
  2525         print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
  2526         print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
  2529     print_summary(1, "Other", summary->get_other_seq());
  2531       NumberSeq calc_other_times_ms;
  2532       if (body_summary != NULL) {
  2533         // not abandoned
  2534         if (parallel) {
  2535           // parallel
  2536           NumberSeq* other_parts[] = {
  2537             body_summary->get_satb_drain_seq(),
  2538             (preamble_summary == NULL) ? NULL :
  2539               preamble_summary->get_pop_preamble_seq(),
  2540             body_summary->get_parallel_seq(),
  2541             body_summary->get_clear_ct_seq()
  2542           };
  2543           calc_other_times_ms = NumberSeq (summary->get_total_seq(),
  2544                                           4, other_parts);
  2545         } else {
  2546           // serial
  2547           NumberSeq* other_parts[] = {
  2548             body_summary->get_satb_drain_seq(),
  2549             (preamble_summary == NULL) ? NULL :
  2550               preamble_summary->get_pop_preamble_seq(),
  2551             body_summary->get_update_rs_seq(),
  2552             body_summary->get_ext_root_scan_seq(),
  2553             body_summary->get_mark_stack_scan_seq(),
  2554             body_summary->get_scan_only_seq(),
  2555             body_summary->get_scan_rs_seq(),
  2556             body_summary->get_obj_copy_seq()
  2557           };
  2558           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2559                                           8, other_parts);
  2561       } else {
  2562         // abandoned
  2563         NumberSeq* other_parts[] = {
  2564           (preamble_summary == NULL) ? NULL :
  2565             preamble_summary->get_pop_preamble_seq()
  2566         };
  2567         calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2568                                         1, other_parts);
  2570       check_other_times(1,  summary->get_other_seq(), &calc_other_times_ms);
  2572   } else {
  2573     print_indent(0);
  2574     gclog_or_tty->print_cr("none");
  2576   gclog_or_tty->print_cr("");
  2579 void
  2580 G1CollectorPolicy::print_abandoned_summary(PauseSummary* non_pop_summary,
  2581                                            PauseSummary* pop_summary) const {
  2582   bool printed = false;
  2583   if (non_pop_summary->get_total_seq()->num() > 0) {
  2584     printed = true;
  2585     print_summary(non_pop_summary);
  2587   if (pop_summary->get_total_seq()->num() > 0) {
  2588     printed = true;
  2589     print_summary(pop_summary);
  2592   if (!printed) {
  2593     print_indent(0);
  2594     gclog_or_tty->print_cr("none");
  2595     gclog_or_tty->print_cr("");
  2599 void G1CollectorPolicy::print_tracing_info() const {
  2600   if (TraceGen0Time) {
  2601     gclog_or_tty->print_cr("ALL PAUSES");
  2602     print_summary_sd(0, "Total", _all_pause_times_ms);
  2603     gclog_or_tty->print_cr("");
  2604     gclog_or_tty->print_cr("");
  2605     gclog_or_tty->print_cr("   Full Young GC Pauses:    %8d", _full_young_pause_num);
  2606     gclog_or_tty->print_cr("   Partial Young GC Pauses: %8d", _partial_young_pause_num);
  2607     gclog_or_tty->print_cr("");
  2609     gclog_or_tty->print_cr("NON-POPULAR PAUSES");
  2610     print_summary(_non_pop_summary);
  2612     gclog_or_tty->print_cr("POPULAR PAUSES");
  2613     print_summary(_pop_summary);
  2615     gclog_or_tty->print_cr("ABANDONED PAUSES");
  2616     print_abandoned_summary(_non_pop_abandoned_summary,
  2617                             _pop_abandoned_summary);
  2619     gclog_or_tty->print_cr("MISC");
  2620     print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
  2621     print_summary_sd(0, "Yields", _all_yield_times_ms);
  2622     for (int i = 0; i < _aux_num; ++i) {
  2623       if (_all_aux_times_ms[i].num() > 0) {
  2624         char buffer[96];
  2625         sprintf(buffer, "Aux%d", i);
  2626         print_summary_sd(0, buffer, &_all_aux_times_ms[i]);
  2630     size_t all_region_num = _region_num_young + _region_num_tenured;
  2631     gclog_or_tty->print_cr("   New Regions %8d, Young %8d (%6.2lf%%), "
  2632                "Tenured %8d (%6.2lf%%)",
  2633                all_region_num,
  2634                _region_num_young,
  2635                (double) _region_num_young / (double) all_region_num * 100.0,
  2636                _region_num_tenured,
  2637                (double) _region_num_tenured / (double) all_region_num * 100.0);
  2639     if (!G1RSBarrierUseQueue) {
  2640       gclog_or_tty->print_cr("Of %d times conc refinement was enabled, %d (%7.2f%%) "
  2641                     "did zero traversals.",
  2642                     _conc_refine_enabled, _conc_refine_zero_traversals,
  2643                     _conc_refine_enabled > 0 ?
  2644                     100.0 * (float)_conc_refine_zero_traversals/
  2645                     (float)_conc_refine_enabled : 0.0);
  2646       gclog_or_tty->print_cr("  Max # of traversals = %d.",
  2647                     _conc_refine_max_traversals);
  2648       gclog_or_tty->print_cr("");
  2651   if (TraceGen1Time) {
  2652     if (_all_full_gc_times_ms->num() > 0) {
  2653       gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
  2654                  _all_full_gc_times_ms->num(),
  2655                  _all_full_gc_times_ms->sum() / 1000.0);
  2656       gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times_ms->avg());
  2657       gclog_or_tty->print_cr("                     [std. dev = %8.2f ms, max = %8.2f ms]",
  2658                     _all_full_gc_times_ms->sd(),
  2659                     _all_full_gc_times_ms->maximum());
  2664 void G1CollectorPolicy::print_yg_surv_rate_info() const {
  2665 #ifndef PRODUCT
  2666   _short_lived_surv_rate_group->print_surv_rate_summary();
  2667   // add this call for any other surv rate groups
  2668 #endif // PRODUCT
  2671 void G1CollectorPolicy::update_conc_refine_data() {
  2672   unsigned traversals = _g1->concurrent_g1_refine()->disable();
  2673   if (traversals == 0) _conc_refine_zero_traversals++;
  2674   _conc_refine_max_traversals = MAX2(_conc_refine_max_traversals,
  2675                                      (size_t)traversals);
  2677   if (G1PolicyVerbose > 1)
  2678     gclog_or_tty->print_cr("Did a CR traversal series: %d traversals.", traversals);
  2679   double multiplier = 1.0;
  2680   if (traversals == 0) {
  2681     multiplier = 4.0;
  2682   } else if (traversals > (size_t)G1ConcRefineTargTraversals) {
  2683     multiplier = 1.0/1.5;
  2684   } else if (traversals < (size_t)G1ConcRefineTargTraversals) {
  2685     multiplier = 1.5;
  2687   if (G1PolicyVerbose > 1) {
  2688     gclog_or_tty->print_cr("  Multiplier = %7.2f.", multiplier);
  2689     gclog_or_tty->print("  Delta went from %d regions to ",
  2690                _conc_refine_current_delta);
  2692   _conc_refine_current_delta =
  2693     MIN2(_g1->n_regions(),
  2694          (size_t)(_conc_refine_current_delta * multiplier));
  2695   _conc_refine_current_delta =
  2696     MAX2(_conc_refine_current_delta, (size_t)1);
  2697   if (G1PolicyVerbose > 1) {
  2698     gclog_or_tty->print_cr("%d regions.", _conc_refine_current_delta);
  2700   _conc_refine_enabled++;
  2703 void G1CollectorPolicy::set_single_region_collection_set(HeapRegion* hr) {
  2704   assert(collection_set() == NULL, "Must be no current CS.");
  2705   _collection_set_size = 0;
  2706   _collection_set_bytes_used_before = 0;
  2707   add_to_collection_set(hr);
  2708   count_CS_bytes_used();
  2711 bool
  2712 G1CollectorPolicy::should_add_next_region_to_young_list() {
  2713   assert(in_young_gc_mode(), "should be in young GC mode");
  2714   bool ret;
  2715   size_t young_list_length = _g1->young_list_length();
  2716   size_t young_list_max_length = _young_list_target_length;
  2717   if (G1FixedEdenSize) {
  2718     young_list_max_length -= _max_survivor_regions;
  2720   if (young_list_length < young_list_max_length) {
  2721     ret = true;
  2722     ++_region_num_young;
  2723   } else {
  2724     ret = false;
  2725     ++_region_num_tenured;
  2728   return ret;
  2731 #ifndef PRODUCT
  2732 // for debugging, bit of a hack...
  2733 static char*
  2734 region_num_to_mbs(int length) {
  2735   static char buffer[64];
  2736   double bytes = (double) (length * HeapRegion::GrainBytes);
  2737   double mbs = bytes / (double) (1024 * 1024);
  2738   sprintf(buffer, "%7.2lfMB", mbs);
  2739   return buffer;
  2741 #endif // PRODUCT
  2743 void
  2744 G1CollectorPolicy::checkpoint_conc_overhead() {
  2745   double conc_overhead = 0.0;
  2746   if (G1AccountConcurrentOverhead)
  2747     conc_overhead = COTracker::totalPredConcOverhead();
  2748   _mmu_tracker->update_conc_overhead(conc_overhead);
  2749 #if 0
  2750   gclog_or_tty->print(" CO %1.4lf TARGET %1.4lf",
  2751              conc_overhead, _mmu_tracker->max_gc_time());
  2752 #endif
  2756 size_t G1CollectorPolicy::max_regions(int purpose) {
  2757   switch (purpose) {
  2758     case GCAllocForSurvived:
  2759       return _max_survivor_regions;
  2760     case GCAllocForTenured:
  2761       return REGIONS_UNLIMITED;
  2762     default:
  2763       ShouldNotReachHere();
  2764       return REGIONS_UNLIMITED;
  2765   };
  2768 // Calculates survivor space parameters.
  2769 void G1CollectorPolicy::calculate_survivors_policy()
  2771   if (!G1UseSurvivorSpace) {
  2772     return;
  2774   if (G1FixedSurvivorSpaceSize == 0) {
  2775     _max_survivor_regions = _young_list_target_length / SurvivorRatio;
  2776   } else {
  2777     _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
  2780   if (G1FixedTenuringThreshold) {
  2781     _tenuring_threshold = MaxTenuringThreshold;
  2782   } else {
  2783     _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
  2784         HeapRegion::GrainWords * _max_survivor_regions);
  2789 void
  2790 G1CollectorPolicy_BestRegionsFirst::
  2791 set_single_region_collection_set(HeapRegion* hr) {
  2792   G1CollectorPolicy::set_single_region_collection_set(hr);
  2793   _collectionSetChooser->removeRegion(hr);
  2797 bool
  2798 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
  2799                                                                word_size) {
  2800   assert(_g1->regions_accounted_for(), "Region leakage!");
  2801   // Initiate a pause when we reach the steady-state "used" target.
  2802   size_t used_hard = (_g1->capacity() / 100) * G1SteadyStateUsed;
  2803   size_t used_soft =
  2804    MAX2((_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta),
  2805         used_hard/2);
  2806   size_t used = _g1->used();
  2808   double max_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
  2810   size_t young_list_length = _g1->young_list_length();
  2811   size_t young_list_max_length = _young_list_target_length;
  2812   if (G1FixedEdenSize) {
  2813     young_list_max_length -= _max_survivor_regions;
  2815   bool reached_target_length = young_list_length >= young_list_max_length;
  2817   if (in_young_gc_mode()) {
  2818     if (reached_target_length) {
  2819       assert( young_list_length > 0 && _g1->young_list_length() > 0,
  2820               "invariant" );
  2821       _target_pause_time_ms = max_pause_time_ms;
  2822       return true;
  2824   } else {
  2825     guarantee( false, "should not reach here" );
  2828   return false;
  2831 #ifndef PRODUCT
  2832 class HRSortIndexIsOKClosure: public HeapRegionClosure {
  2833   CollectionSetChooser* _chooser;
  2834 public:
  2835   HRSortIndexIsOKClosure(CollectionSetChooser* chooser) :
  2836     _chooser(chooser) {}
  2838   bool doHeapRegion(HeapRegion* r) {
  2839     if (!r->continuesHumongous()) {
  2840       assert(_chooser->regionProperlyOrdered(r), "Ought to be.");
  2842     return false;
  2844 };
  2846 bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() {
  2847   HRSortIndexIsOKClosure cl(_collectionSetChooser);
  2848   _g1->heap_region_iterate(&cl);
  2849   return true;
  2851 #endif
  2853 void
  2854 G1CollectorPolicy_BestRegionsFirst::
  2855 record_collection_pause_start(double start_time_sec, size_t start_used) {
  2856   G1CollectorPolicy::record_collection_pause_start(start_time_sec, start_used);
  2859 class NextNonCSElemFinder: public HeapRegionClosure {
  2860   HeapRegion* _res;
  2861 public:
  2862   NextNonCSElemFinder(): _res(NULL) {}
  2863   bool doHeapRegion(HeapRegion* r) {
  2864     if (!r->in_collection_set()) {
  2865       _res = r;
  2866       return true;
  2867     } else {
  2868       return false;
  2871   HeapRegion* res() { return _res; }
  2872 };
  2874 class KnownGarbageClosure: public HeapRegionClosure {
  2875   CollectionSetChooser* _hrSorted;
  2877 public:
  2878   KnownGarbageClosure(CollectionSetChooser* hrSorted) :
  2879     _hrSorted(hrSorted)
  2880   {}
  2882   bool doHeapRegion(HeapRegion* r) {
  2883     // We only include humongous regions in collection
  2884     // sets when concurrent mark shows that their contained object is
  2885     // unreachable.
  2887     // Do we have any marking information for this region?
  2888     if (r->is_marked()) {
  2889       // We don't include humongous regions in collection
  2890       // sets because we collect them immediately at the end of a marking
  2891       // cycle.  We also don't include young regions because we *must*
  2892       // include them in the next collection pause.
  2893       if (!r->isHumongous() && !r->is_young()) {
  2894         _hrSorted->addMarkedHeapRegion(r);
  2897     return false;
  2899 };
  2901 class ParKnownGarbageHRClosure: public HeapRegionClosure {
  2902   CollectionSetChooser* _hrSorted;
  2903   jint _marked_regions_added;
  2904   jint _chunk_size;
  2905   jint _cur_chunk_idx;
  2906   jint _cur_chunk_end; // Cur chunk [_cur_chunk_idx, _cur_chunk_end)
  2907   int _worker;
  2908   int _invokes;
  2910   void get_new_chunk() {
  2911     _cur_chunk_idx = _hrSorted->getParMarkedHeapRegionChunk(_chunk_size);
  2912     _cur_chunk_end = _cur_chunk_idx + _chunk_size;
  2914   void add_region(HeapRegion* r) {
  2915     if (_cur_chunk_idx == _cur_chunk_end) {
  2916       get_new_chunk();
  2918     assert(_cur_chunk_idx < _cur_chunk_end, "postcondition");
  2919     _hrSorted->setMarkedHeapRegion(_cur_chunk_idx, r);
  2920     _marked_regions_added++;
  2921     _cur_chunk_idx++;
  2924 public:
  2925   ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
  2926                            jint chunk_size,
  2927                            int worker) :
  2928     _hrSorted(hrSorted), _chunk_size(chunk_size), _worker(worker),
  2929     _marked_regions_added(0), _cur_chunk_idx(0), _cur_chunk_end(0),
  2930     _invokes(0)
  2931   {}
  2933   bool doHeapRegion(HeapRegion* r) {
  2934     // We only include humongous regions in collection
  2935     // sets when concurrent mark shows that their contained object is
  2936     // unreachable.
  2937     _invokes++;
  2939     // Do we have any marking information for this region?
  2940     if (r->is_marked()) {
  2941       // We don't include humongous regions in collection
  2942       // sets because we collect them immediately at the end of a marking
  2943       // cycle.
  2944       // We also do not include young regions in collection sets
  2945       if (!r->isHumongous() && !r->is_young()) {
  2946         add_region(r);
  2949     return false;
  2951   jint marked_regions_added() { return _marked_regions_added; }
  2952   int invokes() { return _invokes; }
  2953 };
  2955 class ParKnownGarbageTask: public AbstractGangTask {
  2956   CollectionSetChooser* _hrSorted;
  2957   jint _chunk_size;
  2958   G1CollectedHeap* _g1;
  2959 public:
  2960   ParKnownGarbageTask(CollectionSetChooser* hrSorted, jint chunk_size) :
  2961     AbstractGangTask("ParKnownGarbageTask"),
  2962     _hrSorted(hrSorted), _chunk_size(chunk_size),
  2963     _g1(G1CollectedHeap::heap())
  2964   {}
  2966   void work(int i) {
  2967     ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size, i);
  2968     // Back to zero for the claim value.
  2969     _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, i,
  2970                                          HeapRegion::InitialClaimValue);
  2971     jint regions_added = parKnownGarbageCl.marked_regions_added();
  2972     _hrSorted->incNumMarkedHeapRegions(regions_added);
  2973     if (G1PrintParCleanupStats) {
  2974       gclog_or_tty->print("     Thread %d called %d times, added %d regions to list.\n",
  2975                  i, parKnownGarbageCl.invokes(), regions_added);
  2978 };
  2980 void
  2981 G1CollectorPolicy_BestRegionsFirst::
  2982 record_concurrent_mark_cleanup_end(size_t freed_bytes,
  2983                                    size_t max_live_bytes) {
  2984   double start;
  2985   if (G1PrintParCleanupStats) start = os::elapsedTime();
  2986   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  2988   _collectionSetChooser->clearMarkedHeapRegions();
  2989   double clear_marked_end;
  2990   if (G1PrintParCleanupStats) {
  2991     clear_marked_end = os::elapsedTime();
  2992     gclog_or_tty->print_cr("  clear marked regions + work1: %8.3f ms.",
  2993                   (clear_marked_end - start)*1000.0);
  2995   if (ParallelGCThreads > 0) {
  2996     const size_t OverpartitionFactor = 4;
  2997     const size_t MinChunkSize = 8;
  2998     const size_t ChunkSize =
  2999       MAX2(_g1->n_regions() / (ParallelGCThreads * OverpartitionFactor),
  3000            MinChunkSize);
  3001     _collectionSetChooser->prepareForAddMarkedHeapRegionsPar(_g1->n_regions(),
  3002                                                              ChunkSize);
  3003     ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
  3004                                             (int) ChunkSize);
  3005     _g1->workers()->run_task(&parKnownGarbageTask);
  3007     assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  3008            "sanity check");
  3009   } else {
  3010     KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
  3011     _g1->heap_region_iterate(&knownGarbagecl);
  3013   double known_garbage_end;
  3014   if (G1PrintParCleanupStats) {
  3015     known_garbage_end = os::elapsedTime();
  3016     gclog_or_tty->print_cr("  compute known garbage: %8.3f ms.",
  3017                   (known_garbage_end - clear_marked_end)*1000.0);
  3019   _collectionSetChooser->sortMarkedHeapRegions();
  3020   double sort_end;
  3021   if (G1PrintParCleanupStats) {
  3022     sort_end = os::elapsedTime();
  3023     gclog_or_tty->print_cr("  sorting: %8.3f ms.",
  3024                   (sort_end - known_garbage_end)*1000.0);
  3027   record_concurrent_mark_cleanup_end_work2();
  3028   double work2_end;
  3029   if (G1PrintParCleanupStats) {
  3030     work2_end = os::elapsedTime();
  3031     gclog_or_tty->print_cr("  work2: %8.3f ms.",
  3032                   (work2_end - sort_end)*1000.0);
  3036 // Add the heap region to the collection set and return the conservative
  3037 // estimate of the number of live bytes.
  3038 void G1CollectorPolicy::
  3039 add_to_collection_set(HeapRegion* hr) {
  3040   if (G1TraceRegions) {
  3041     gclog_or_tty->print_cr("added region to cset %d:["PTR_FORMAT", "PTR_FORMAT"], "
  3042                   "top "PTR_FORMAT", young %s",
  3043                   hr->hrs_index(), hr->bottom(), hr->end(),
  3044                   hr->top(), (hr->is_young()) ? "YES" : "NO");
  3047   if (_g1->mark_in_progress())
  3048     _g1->concurrent_mark()->registerCSetRegion(hr);
  3050   assert(!hr->in_collection_set(),
  3051               "should not already be in the CSet");
  3052   hr->set_in_collection_set(true);
  3053   hr->set_next_in_collection_set(_collection_set);
  3054   _collection_set = hr;
  3055   _collection_set_size++;
  3056   _collection_set_bytes_used_before += hr->used();
  3057   _g1->register_region_with_in_cset_fast_test(hr);
  3060 void
  3061 G1CollectorPolicy_BestRegionsFirst::
  3062 choose_collection_set(HeapRegion* pop_region) {
  3063   double non_young_start_time_sec;
  3064   start_recording_regions();
  3066   if (pop_region != NULL) {
  3067     _target_pause_time_ms = (double) G1MaxPauseTimeMS;
  3068   } else {
  3069     guarantee(_target_pause_time_ms > -1.0,
  3070               "_target_pause_time_ms should have been set!");
  3073   // pop region is either null (and so is CS), or else it *is* the CS.
  3074   assert(_collection_set == pop_region, "Precondition");
  3076   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
  3077   double predicted_pause_time_ms = base_time_ms;
  3079   double target_time_ms = _target_pause_time_ms;
  3080   double time_remaining_ms = target_time_ms - base_time_ms;
  3082   // the 10% and 50% values are arbitrary...
  3083   if (time_remaining_ms < 0.10*target_time_ms) {
  3084     time_remaining_ms = 0.50 * target_time_ms;
  3085     _within_target = false;
  3086   } else {
  3087     _within_target = true;
  3090   // We figure out the number of bytes available for future to-space.
  3091   // For new regions without marking information, we must assume the
  3092   // worst-case of complete survival.  If we have marking information for a
  3093   // region, we can bound the amount of live data.  We can add a number of
  3094   // such regions, as long as the sum of the live data bounds does not
  3095   // exceed the available evacuation space.
  3096   size_t max_live_bytes = _g1->free_regions() * HeapRegion::GrainBytes;
  3098   size_t expansion_bytes =
  3099     _g1->expansion_regions() * HeapRegion::GrainBytes;
  3101   if (pop_region == NULL) {
  3102     _collection_set_bytes_used_before = 0;
  3103     _collection_set_size = 0;
  3106   // Adjust for expansion and slop.
  3107   max_live_bytes = max_live_bytes + expansion_bytes;
  3109   assert(pop_region != NULL || _g1->regions_accounted_for(), "Region leakage!");
  3111   HeapRegion* hr;
  3112   if (in_young_gc_mode()) {
  3113     double young_start_time_sec = os::elapsedTime();
  3115     if (G1PolicyVerbose > 0) {
  3116       gclog_or_tty->print_cr("Adding %d young regions to the CSet",
  3117                     _g1->young_list_length());
  3119     _young_cset_length  = 0;
  3120     _last_young_gc_full = full_young_gcs() ? true : false;
  3121     if (_last_young_gc_full)
  3122       ++_full_young_pause_num;
  3123     else
  3124       ++_partial_young_pause_num;
  3125     hr = _g1->pop_region_from_young_list();
  3126     while (hr != NULL) {
  3128       assert( hr->young_index_in_cset() == -1, "invariant" );
  3129       assert( hr->age_in_surv_rate_group() != -1, "invariant" );
  3130       hr->set_young_index_in_cset((int) _young_cset_length);
  3132       ++_young_cset_length;
  3133       double predicted_time_ms = predict_region_elapsed_time_ms(hr, true);
  3134       time_remaining_ms -= predicted_time_ms;
  3135       predicted_pause_time_ms += predicted_time_ms;
  3136       if (hr == pop_region) {
  3137         // The popular region was young.  Skip over it.
  3138         assert(hr->in_collection_set(), "It's the pop region.");
  3139       } else {
  3140         assert(!hr->in_collection_set(), "It's not the pop region.");
  3141         add_to_collection_set(hr);
  3142         record_cset_region(hr, true);
  3144       max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  3145       if (G1PolicyVerbose > 0) {
  3146         gclog_or_tty->print_cr("  Added [" PTR_FORMAT ", " PTR_FORMAT") to CS.",
  3147                       hr->bottom(), hr->end());
  3148         gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  3149                       max_live_bytes/K);
  3151       hr = _g1->pop_region_from_young_list();
  3154     record_scan_only_regions(_g1->young_list_scan_only_length());
  3156     double young_end_time_sec = os::elapsedTime();
  3157     _recorded_young_cset_choice_time_ms =
  3158       (young_end_time_sec - young_start_time_sec) * 1000.0;
  3160     non_young_start_time_sec = os::elapsedTime();
  3162     if (_young_cset_length > 0 && _last_young_gc_full) {
  3163       // don't bother adding more regions...
  3164       goto choose_collection_set_end;
  3166   } else if (pop_region != NULL) {
  3167     // We're not in young mode, and we chose a popular region; don't choose
  3168     // any more.
  3169     return;
  3172   if (!in_young_gc_mode() || !full_young_gcs()) {
  3173     bool should_continue = true;
  3174     NumberSeq seq;
  3175     double avg_prediction = 100000000000000000.0; // something very large
  3176     do {
  3177       hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
  3178                                                       avg_prediction);
  3179       if (hr != NULL && !hr->popular()) {
  3180         double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
  3181         time_remaining_ms -= predicted_time_ms;
  3182         predicted_pause_time_ms += predicted_time_ms;
  3183         add_to_collection_set(hr);
  3184         record_cset_region(hr, false);
  3185         max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  3186         if (G1PolicyVerbose > 0) {
  3187           gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  3188                         max_live_bytes/K);
  3190         seq.add(predicted_time_ms);
  3191         avg_prediction = seq.avg() + seq.sd();
  3193       should_continue =
  3194         ( hr != NULL) &&
  3195         ( (adaptive_young_list_length()) ? time_remaining_ms > 0.0
  3196           : _collection_set_size < _young_list_fixed_length );
  3197     } while (should_continue);
  3199     if (!adaptive_young_list_length() &&
  3200         _collection_set_size < _young_list_fixed_length)
  3201       _should_revert_to_full_young_gcs  = true;
  3204 choose_collection_set_end:
  3205   count_CS_bytes_used();
  3207   end_recording_regions();
  3209   double non_young_end_time_sec = os::elapsedTime();
  3210   _recorded_non_young_cset_choice_time_ms =
  3211     (non_young_end_time_sec - non_young_start_time_sec) * 1000.0;
  3214 void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() {
  3215   G1CollectorPolicy::record_full_collection_end();
  3216   _collectionSetChooser->updateAfterFullCollection();
  3219 void G1CollectorPolicy_BestRegionsFirst::
  3220 expand_if_possible(size_t numRegions) {
  3221   size_t expansion_bytes = numRegions * HeapRegion::GrainBytes;
  3222   _g1->expand(expansion_bytes);
  3225 void G1CollectorPolicy_BestRegionsFirst::
  3226 record_collection_pause_end(bool popular, bool abandoned) {
  3227   G1CollectorPolicy::record_collection_pause_end(popular, abandoned);
  3228   assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
  3231 // Local Variables: ***
  3232 // c-indentation-style: gnu ***
  3233 // End: ***

mercurial