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

Sat, 21 Mar 2009 22:53:04 -0400

author
tonyp
date
Sat, 21 Mar 2009 22:53:04 -0400
changeset 1083
2314b7336582
parent 1075
ba50942c8138
child 1112
96b229c54d1e
permissions
-rw-r--r--

6820321: G1: Error: guarantee(check_nums(total, n, parts), "all seq lengths should match")
Summary: Small fixes to sort out some verbosegc-related incorrectness and a failure
Reviewed-by: apetrusenko

     1 /*
     2  * Copyright 2001-2009 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 #include "incls/_precompiled.incl"
    26 #include "incls/_g1CollectorPolicy.cpp.incl"
    28 #define PREDICTIONS_VERBOSE 0
    30 // <NEW PREDICTION>
    32 // Different defaults for different number of GC threads
    33 // They were chosen by running GCOld and SPECjbb on debris with different
    34 //   numbers of GC threads and choosing them based on the results
    36 // all the same
    37 static double rs_length_diff_defaults[] = {
    38   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
    39 };
    41 static double cost_per_card_ms_defaults[] = {
    42   0.01, 0.005, 0.005, 0.003, 0.003, 0.002, 0.002, 0.0015
    43 };
    45 static double cost_per_scan_only_region_ms_defaults[] = {
    46   1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
    47 };
    49 // all the same
    50 static double fully_young_cards_per_entry_ratio_defaults[] = {
    51   1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
    52 };
    54 static double cost_per_entry_ms_defaults[] = {
    55   0.015, 0.01, 0.01, 0.008, 0.008, 0.0055, 0.0055, 0.005
    56 };
    58 static double cost_per_byte_ms_defaults[] = {
    59   0.00006, 0.00003, 0.00003, 0.000015, 0.000015, 0.00001, 0.00001, 0.000009
    60 };
    62 // these should be pretty consistent
    63 static double constant_other_time_ms_defaults[] = {
    64   5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0
    65 };
    68 static double young_other_cost_per_region_ms_defaults[] = {
    69   0.3, 0.2, 0.2, 0.15, 0.15, 0.12, 0.12, 0.1
    70 };
    72 static double non_young_other_cost_per_region_ms_defaults[] = {
    73   1.0, 0.7, 0.7, 0.5, 0.5, 0.42, 0.42, 0.30
    74 };
    76 // </NEW PREDICTION>
    78 G1CollectorPolicy::G1CollectorPolicy() :
    79   _parallel_gc_threads((ParallelGCThreads > 0) ? ParallelGCThreads : 1),
    80   _n_pauses(0),
    81   _recent_CH_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    82   _recent_G1_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    83   _recent_evac_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    84   _recent_pause_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    85   _recent_rs_sizes(new TruncatedSeq(NumPrevPausesForHeuristics)),
    86   _recent_gc_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
    87   _all_pause_times_ms(new NumberSeq()),
    88   _stop_world_start(0.0),
    89   _all_stop_world_times_ms(new NumberSeq()),
    90   _all_yield_times_ms(new NumberSeq()),
    92   _all_mod_union_times_ms(new NumberSeq()),
    94   _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");
  1090   assert(_g1->used() == _g1->recalculate_used(), "sanity");
  1092   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
  1093   _all_stop_world_times_ms->add(s_w_t_ms);
  1094   _stop_world_start = 0.0;
  1096   _cur_collection_start_sec = start_time_sec;
  1097   _cur_collection_pause_used_at_start_bytes = start_used;
  1098   _cur_collection_pause_used_regions_at_start = _g1->used_regions();
  1099   _pending_cards = _g1->pending_card_num();
  1100   _max_pending_cards = _g1->max_pending_card_num();
  1102   _bytes_in_to_space_before_gc = 0;
  1103   _bytes_in_to_space_after_gc = 0;
  1104   _bytes_in_collection_set_before_gc = 0;
  1106 #ifdef DEBUG
  1107   // initialise these to something well known so that we can spot
  1108   // if they are not set properly
  1110   for (int i = 0; i < _parallel_gc_threads; ++i) {
  1111     _par_last_ext_root_scan_times_ms[i] = -666.0;
  1112     _par_last_mark_stack_scan_times_ms[i] = -666.0;
  1113     _par_last_scan_only_times_ms[i] = -666.0;
  1114     _par_last_scan_only_regions_scanned[i] = -666.0;
  1115     _par_last_update_rs_start_times_ms[i] = -666.0;
  1116     _par_last_update_rs_times_ms[i] = -666.0;
  1117     _par_last_update_rs_processed_buffers[i] = -666.0;
  1118     _par_last_scan_rs_start_times_ms[i] = -666.0;
  1119     _par_last_scan_rs_times_ms[i] = -666.0;
  1120     _par_last_scan_new_refs_times_ms[i] = -666.0;
  1121     _par_last_obj_copy_times_ms[i] = -666.0;
  1122     _par_last_termination_times_ms[i] = -666.0;
  1124     _pop_par_last_update_rs_start_times_ms[i] = -666.0;
  1125     _pop_par_last_update_rs_times_ms[i] = -666.0;
  1126     _pop_par_last_update_rs_processed_buffers[i] = -666.0;
  1127     _pop_par_last_scan_rs_start_times_ms[i] = -666.0;
  1128     _pop_par_last_scan_rs_times_ms[i] = -666.0;
  1129     _pop_par_last_closure_app_times_ms[i] = -666.0;
  1131 #endif
  1133   for (int i = 0; i < _aux_num; ++i) {
  1134     _cur_aux_times_ms[i] = 0.0;
  1135     _cur_aux_times_set[i] = false;
  1138   _satb_drain_time_set = false;
  1139   _last_satb_drain_processed_buffers = -1;
  1141   if (in_young_gc_mode())
  1142     _last_young_gc_full = false;
  1145   // do that for any other surv rate groups
  1146   _short_lived_surv_rate_group->stop_adding_regions();
  1147   size_t short_lived_so_length = _young_list_so_prefix_length;
  1148   _short_lived_surv_rate_group->record_scan_only_prefix(short_lived_so_length);
  1149   tag_scan_only(short_lived_so_length);
  1151   if (G1UseSurvivorSpace) {
  1152     _survivors_age_table.clear();
  1155   assert( verify_young_ages(), "region age verification" );
  1158 void G1CollectorPolicy::tag_scan_only(size_t short_lived_scan_only_length) {
  1159   // done in a way that it can be extended for other surv rate groups too...
  1161   HeapRegion* head = _g1->young_list_first_region();
  1162   bool finished_short_lived = (short_lived_scan_only_length == 0);
  1164   if (finished_short_lived)
  1165     return;
  1167   for (HeapRegion* curr = head;
  1168        curr != NULL;
  1169        curr = curr->get_next_young_region()) {
  1170     SurvRateGroup* surv_rate_group = curr->surv_rate_group();
  1171     int age = curr->age_in_surv_rate_group();
  1173     if (surv_rate_group == _short_lived_surv_rate_group) {
  1174       if ((size_t)age < short_lived_scan_only_length)
  1175         curr->set_scan_only();
  1176       else
  1177         finished_short_lived = true;
  1181     if (finished_short_lived)
  1182       return;
  1185   guarantee( false, "we should never reach here" );
  1188 void G1CollectorPolicy::record_popular_pause_preamble_start() {
  1189   _cur_popular_preamble_start_ms = os::elapsedTime() * 1000.0;
  1192 void G1CollectorPolicy::record_popular_pause_preamble_end() {
  1193   _cur_popular_preamble_time_ms =
  1194     (os::elapsedTime() * 1000.0) - _cur_popular_preamble_start_ms;
  1196   // copy the recorded statistics of the first pass to temporary arrays
  1197   for (int i = 0; i < _parallel_gc_threads; ++i) {
  1198     _pop_par_last_update_rs_start_times_ms[i] = _par_last_update_rs_start_times_ms[i];
  1199     _pop_par_last_update_rs_times_ms[i] = _par_last_update_rs_times_ms[i];
  1200     _pop_par_last_update_rs_processed_buffers[i] = _par_last_update_rs_processed_buffers[i];
  1201     _pop_par_last_scan_rs_start_times_ms[i] = _par_last_scan_rs_start_times_ms[i];
  1202     _pop_par_last_scan_rs_times_ms[i] = _par_last_scan_rs_times_ms[i];
  1203     _pop_par_last_closure_app_times_ms[i] = _par_last_obj_copy_times_ms[i];
  1207 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
  1208   _mark_closure_time_ms = mark_closure_time_ms;
  1211 void G1CollectorPolicy::record_concurrent_mark_init_start() {
  1212   _mark_init_start_sec = os::elapsedTime();
  1213   guarantee(!in_young_gc_mode(), "should not do be here in young GC mode");
  1216 void G1CollectorPolicy::record_concurrent_mark_init_end_pre(double
  1217                                                    mark_init_elapsed_time_ms) {
  1218   _during_marking = true;
  1219   _should_initiate_conc_mark = false;
  1220   _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
  1223 void G1CollectorPolicy::record_concurrent_mark_init_end() {
  1224   double end_time_sec = os::elapsedTime();
  1225   double elapsed_time_ms = (end_time_sec - _mark_init_start_sec) * 1000.0;
  1226   _concurrent_mark_init_times_ms->add(elapsed_time_ms);
  1227   checkpoint_conc_overhead();
  1228   record_concurrent_mark_init_end_pre(elapsed_time_ms);
  1230   _mmu_tracker->add_pause(_mark_init_start_sec, end_time_sec, true);
  1233 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
  1234   _mark_remark_start_sec = os::elapsedTime();
  1235   _during_marking = false;
  1238 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
  1239   double end_time_sec = os::elapsedTime();
  1240   double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
  1241   checkpoint_conc_overhead();
  1242   _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
  1243   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1244   _prev_collection_pause_end_ms += elapsed_time_ms;
  1246   _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
  1249 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
  1250   _mark_cleanup_start_sec = os::elapsedTime();
  1253 void
  1254 G1CollectorPolicy::record_concurrent_mark_cleanup_end(size_t freed_bytes,
  1255                                                       size_t max_live_bytes) {
  1256   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  1257   record_concurrent_mark_cleanup_end_work2();
  1260 void
  1261 G1CollectorPolicy::
  1262 record_concurrent_mark_cleanup_end_work1(size_t freed_bytes,
  1263                                          size_t max_live_bytes) {
  1264   if (_n_marks < 2) _n_marks++;
  1265   if (G1PolicyVerbose > 0)
  1266     gclog_or_tty->print_cr("At end of marking, max_live is " SIZE_FORMAT " MB "
  1267                            " (of " SIZE_FORMAT " MB heap).",
  1268                            max_live_bytes/M, _g1->capacity()/M);
  1271 // The important thing about this is that it includes "os::elapsedTime".
  1272 void G1CollectorPolicy::record_concurrent_mark_cleanup_end_work2() {
  1273   checkpoint_conc_overhead();
  1274   double end_time_sec = os::elapsedTime();
  1275   double elapsed_time_ms = (end_time_sec - _mark_cleanup_start_sec)*1000.0;
  1276   _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
  1277   _cur_mark_stop_world_time_ms += elapsed_time_ms;
  1278   _prev_collection_pause_end_ms += elapsed_time_ms;
  1280   _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_time_sec, true);
  1282   _num_markings++;
  1284   // We did a marking, so reset the "since_last_mark" variables.
  1285   double considerConcMarkCost = 1.0;
  1286   // If there are available processors, concurrent activity is free...
  1287   if (Threads::number_of_non_daemon_threads() * 2 <
  1288       os::active_processor_count()) {
  1289     considerConcMarkCost = 0.0;
  1291   _n_pauses_at_mark_end = _n_pauses;
  1292   _n_marks_since_last_pause++;
  1293   _conc_mark_initiated = false;
  1296 void
  1297 G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
  1298   if (in_young_gc_mode()) {
  1299     _should_revert_to_full_young_gcs = false;
  1300     _last_full_young_gc = true;
  1301     _in_marking_window = false;
  1302     if (adaptive_young_list_length())
  1303       calculate_young_list_target_config();
  1307 void G1CollectorPolicy::record_concurrent_pause() {
  1308   if (_stop_world_start > 0.0) {
  1309     double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
  1310     _all_yield_times_ms->add(yield_ms);
  1314 void G1CollectorPolicy::record_concurrent_pause_end() {
  1317 void G1CollectorPolicy::record_collection_pause_end_CH_strong_roots() {
  1318   _cur_CH_strong_roots_end_sec = os::elapsedTime();
  1319   _cur_CH_strong_roots_dur_ms =
  1320     (_cur_CH_strong_roots_end_sec - _cur_collection_start_sec) * 1000.0;
  1323 void G1CollectorPolicy::record_collection_pause_end_G1_strong_roots() {
  1324   _cur_G1_strong_roots_end_sec = os::elapsedTime();
  1325   _cur_G1_strong_roots_dur_ms =
  1326     (_cur_G1_strong_roots_end_sec - _cur_CH_strong_roots_end_sec) * 1000.0;
  1329 template<class T>
  1330 T sum_of(T* sum_arr, int start, int n, int N) {
  1331   T sum = (T)0;
  1332   for (int i = 0; i < n; i++) {
  1333     int j = (start + i) % N;
  1334     sum += sum_arr[j];
  1336   return sum;
  1339 void G1CollectorPolicy::print_par_stats (int level,
  1340                                          const char* str,
  1341                                          double* data,
  1342                                          bool summary) {
  1343   double min = data[0], max = data[0];
  1344   double total = 0.0;
  1345   int j;
  1346   for (j = 0; j < level; ++j)
  1347     gclog_or_tty->print("   ");
  1348   gclog_or_tty->print("[%s (ms):", str);
  1349   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1350     double val = data[i];
  1351     if (val < min)
  1352       min = val;
  1353     if (val > max)
  1354       max = val;
  1355     total += val;
  1356     gclog_or_tty->print("  %3.1lf", val);
  1358   if (summary) {
  1359     gclog_or_tty->print_cr("");
  1360     double avg = total / (double) ParallelGCThreads;
  1361     gclog_or_tty->print(" ");
  1362     for (j = 0; j < level; ++j)
  1363       gclog_or_tty->print("   ");
  1364     gclog_or_tty->print("Avg: %5.1lf, Min: %5.1lf, Max: %5.1lf",
  1365                         avg, min, max);
  1367   gclog_or_tty->print_cr("]");
  1370 void G1CollectorPolicy::print_par_buffers (int level,
  1371                                          const char* str,
  1372                                          double* data,
  1373                                          bool summary) {
  1374   double min = data[0], max = data[0];
  1375   double total = 0.0;
  1376   int j;
  1377   for (j = 0; j < level; ++j)
  1378     gclog_or_tty->print("   ");
  1379   gclog_or_tty->print("[%s :", str);
  1380   for (uint i = 0; i < ParallelGCThreads; ++i) {
  1381     double val = data[i];
  1382     if (val < min)
  1383       min = val;
  1384     if (val > max)
  1385       max = val;
  1386     total += val;
  1387     gclog_or_tty->print(" %d", (int) val);
  1389   if (summary) {
  1390     gclog_or_tty->print_cr("");
  1391     double avg = total / (double) ParallelGCThreads;
  1392     gclog_or_tty->print(" ");
  1393     for (j = 0; j < level; ++j)
  1394       gclog_or_tty->print("   ");
  1395     gclog_or_tty->print("Sum: %d, Avg: %d, Min: %d, Max: %d",
  1396                (int)total, (int)avg, (int)min, (int)max);
  1398   gclog_or_tty->print_cr("]");
  1401 void G1CollectorPolicy::print_stats (int level,
  1402                                      const char* str,
  1403                                      double value) {
  1404   for (int j = 0; j < level; ++j)
  1405     gclog_or_tty->print("   ");
  1406   gclog_or_tty->print_cr("[%s: %5.1lf ms]", str, value);
  1409 void G1CollectorPolicy::print_stats (int level,
  1410                                      const char* str,
  1411                                      int value) {
  1412   for (int j = 0; j < level; ++j)
  1413     gclog_or_tty->print("   ");
  1414   gclog_or_tty->print_cr("[%s: %d]", str, value);
  1417 double G1CollectorPolicy::avg_value (double* data) {
  1418   if (ParallelGCThreads > 0) {
  1419     double ret = 0.0;
  1420     for (uint i = 0; i < ParallelGCThreads; ++i)
  1421       ret += data[i];
  1422     return ret / (double) ParallelGCThreads;
  1423   } else {
  1424     return data[0];
  1428 double G1CollectorPolicy::max_value (double* data) {
  1429   if (ParallelGCThreads > 0) {
  1430     double ret = data[0];
  1431     for (uint i = 1; i < ParallelGCThreads; ++i)
  1432       if (data[i] > ret)
  1433         ret = data[i];
  1434     return ret;
  1435   } else {
  1436     return data[0];
  1440 double G1CollectorPolicy::sum_of_values (double* data) {
  1441   if (ParallelGCThreads > 0) {
  1442     double sum = 0.0;
  1443     for (uint i = 0; i < ParallelGCThreads; i++)
  1444       sum += data[i];
  1445     return sum;
  1446   } else {
  1447     return data[0];
  1451 double G1CollectorPolicy::max_sum (double* data1,
  1452                                    double* data2) {
  1453   double ret = data1[0] + data2[0];
  1455   if (ParallelGCThreads > 0) {
  1456     for (uint i = 1; i < ParallelGCThreads; ++i) {
  1457       double data = data1[i] + data2[i];
  1458       if (data > ret)
  1459         ret = data;
  1462   return ret;
  1465 // Anything below that is considered to be zero
  1466 #define MIN_TIMER_GRANULARITY 0.0000001
  1468 void G1CollectorPolicy::record_collection_pause_end(bool popular,
  1469                                                     bool abandoned) {
  1470   double end_time_sec = os::elapsedTime();
  1471   double elapsed_ms = _last_pause_time_ms;
  1472   bool parallel = ParallelGCThreads > 0;
  1473   double evac_ms = (end_time_sec - _cur_G1_strong_roots_end_sec) * 1000.0;
  1474   size_t rs_size =
  1475     _cur_collection_pause_used_regions_at_start - collection_set_size();
  1476   size_t cur_used_bytes = _g1->used();
  1477   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
  1478   bool last_pause_included_initial_mark = false;
  1479   bool update_stats = !abandoned && !_g1->evacuation_failed();
  1481 #ifndef PRODUCT
  1482   if (G1YoungSurvRateVerbose) {
  1483     gclog_or_tty->print_cr("");
  1484     _short_lived_surv_rate_group->print();
  1485     // do that for any other surv rate groups too
  1487 #endif // PRODUCT
  1489   checkpoint_conc_overhead();
  1491   if (in_young_gc_mode()) {
  1492     last_pause_included_initial_mark = _should_initiate_conc_mark;
  1493     if (last_pause_included_initial_mark)
  1494       record_concurrent_mark_init_end_pre(0.0);
  1496     size_t min_used_targ =
  1497       (_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta);
  1499     if (cur_used_bytes > min_used_targ) {
  1500       if (cur_used_bytes <= _prev_collection_pause_used_at_end_bytes) {
  1501       } else if (!_g1->mark_in_progress() && !_last_full_young_gc) {
  1502         _should_initiate_conc_mark = true;
  1506     _prev_collection_pause_used_at_end_bytes = cur_used_bytes;
  1509   _mmu_tracker->add_pause(end_time_sec - elapsed_ms/1000.0,
  1510                           end_time_sec, false);
  1512   guarantee(_cur_collection_pause_used_regions_at_start >=
  1513             collection_set_size(),
  1514             "Negative RS size?");
  1516   // This assert is exempted when we're doing parallel collection pauses,
  1517   // because the fragmentation caused by the parallel GC allocation buffers
  1518   // can lead to more memory being used during collection than was used
  1519   // before. Best leave this out until the fragmentation problem is fixed.
  1520   // Pauses in which evacuation failed can also lead to negative
  1521   // collections, since no space is reclaimed from a region containing an
  1522   // object whose evacuation failed.
  1523   // Further, we're now always doing parallel collection.  But I'm still
  1524   // leaving this here as a placeholder for a more precise assertion later.
  1525   // (DLD, 10/05.)
  1526   assert((true || parallel) // Always using GC LABs now.
  1527          || _g1->evacuation_failed()
  1528          || _cur_collection_pause_used_at_start_bytes >= cur_used_bytes,
  1529          "Negative collection");
  1531   size_t freed_bytes =
  1532     _cur_collection_pause_used_at_start_bytes - cur_used_bytes;
  1533   size_t surviving_bytes = _collection_set_bytes_used_before - freed_bytes;
  1534   double survival_fraction =
  1535     (double)surviving_bytes/
  1536     (double)_collection_set_bytes_used_before;
  1538   _n_pauses++;
  1540   if (update_stats) {
  1541     _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
  1542     _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
  1543     _recent_evac_times_ms->add(evac_ms);
  1544     _recent_pause_times_ms->add(elapsed_ms);
  1546     _recent_rs_sizes->add(rs_size);
  1548     // We exempt parallel collection from this check because Alloc Buffer
  1549     // fragmentation can produce negative collections.  Same with evac
  1550     // failure.
  1551     // Further, we're now always doing parallel collection.  But I'm still
  1552     // leaving this here as a placeholder for a more precise assertion later.
  1553     // (DLD, 10/05.
  1554     assert((true || parallel)
  1555            || _g1->evacuation_failed()
  1556            || surviving_bytes <= _collection_set_bytes_used_before,
  1557            "Or else negative collection!");
  1558     _recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
  1559     _recent_CS_bytes_surviving->add(surviving_bytes);
  1561     // this is where we update the allocation rate of the application
  1562     double app_time_ms =
  1563       (_cur_collection_start_sec * 1000.0 - _prev_collection_pause_end_ms);
  1564     if (app_time_ms < MIN_TIMER_GRANULARITY) {
  1565       // This usually happens due to the timer not having the required
  1566       // granularity. Some Linuxes are the usual culprits.
  1567       // We'll just set it to something (arbitrarily) small.
  1568       app_time_ms = 1.0;
  1570     size_t regions_allocated =
  1571       (_region_num_young - _prev_region_num_young) +
  1572       (_region_num_tenured - _prev_region_num_tenured);
  1573     double alloc_rate_ms = (double) regions_allocated / app_time_ms;
  1574     _alloc_rate_ms_seq->add(alloc_rate_ms);
  1575     _prev_region_num_young   = _region_num_young;
  1576     _prev_region_num_tenured = _region_num_tenured;
  1578     double interval_ms =
  1579       (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
  1580     update_recent_gc_times(end_time_sec, elapsed_ms);
  1581     _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
  1582     assert(recent_avg_pause_time_ratio() < 1.00, "All GC?");
  1585   if (G1PolicyVerbose > 1) {
  1586     gclog_or_tty->print_cr("   Recording collection pause(%d)", _n_pauses);
  1589   PauseSummary* summary;
  1590   if (!abandoned && !popular)
  1591     summary = _non_pop_summary;
  1592   else if (!abandoned && popular)
  1593     summary = _pop_summary;
  1594   else if (abandoned && !popular)
  1595     summary = _non_pop_abandoned_summary;
  1596   else if (abandoned && popular)
  1597     summary = _pop_abandoned_summary;
  1598   else
  1599     guarantee(false, "should not get here!");
  1601   double pop_update_rs_time;
  1602   double pop_update_rs_processed_buffers;
  1603   double pop_scan_rs_time;
  1604   double pop_closure_app_time;
  1605   double pop_other_time;
  1607   if (popular) {
  1608     PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
  1609     guarantee(preamble_summary != NULL, "should not be null!");
  1611     pop_update_rs_time = avg_value(_pop_par_last_update_rs_times_ms);
  1612     pop_update_rs_processed_buffers =
  1613       sum_of_values(_pop_par_last_update_rs_processed_buffers);
  1614     pop_scan_rs_time = avg_value(_pop_par_last_scan_rs_times_ms);
  1615     pop_closure_app_time = avg_value(_pop_par_last_closure_app_times_ms);
  1616     pop_other_time = _cur_popular_preamble_time_ms -
  1617       (pop_update_rs_time + pop_scan_rs_time + pop_closure_app_time +
  1618        _cur_popular_evac_time_ms);
  1620     preamble_summary->record_pop_preamble_time_ms(_cur_popular_preamble_time_ms);
  1621     preamble_summary->record_pop_update_rs_time_ms(pop_update_rs_time);
  1622     preamble_summary->record_pop_scan_rs_time_ms(pop_scan_rs_time);
  1623     preamble_summary->record_pop_closure_app_time_ms(pop_closure_app_time);
  1624     preamble_summary->record_pop_evacuation_time_ms(_cur_popular_evac_time_ms);
  1625     preamble_summary->record_pop_other_time_ms(pop_other_time);
  1628   double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
  1629   double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
  1630   double scan_only_time = avg_value(_par_last_scan_only_times_ms);
  1631   double scan_only_regions_scanned =
  1632     sum_of_values(_par_last_scan_only_regions_scanned);
  1633   double update_rs_time = avg_value(_par_last_update_rs_times_ms);
  1634   double update_rs_processed_buffers =
  1635     sum_of_values(_par_last_update_rs_processed_buffers);
  1636   double scan_rs_time = avg_value(_par_last_scan_rs_times_ms);
  1637   double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
  1638   double termination_time = avg_value(_par_last_termination_times_ms);
  1640   double parallel_other_time = _cur_collection_par_time_ms -
  1641     (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
  1642      scan_only_time + scan_rs_time + obj_copy_time + termination_time);
  1643   if (update_stats) {
  1644     MainBodySummary* body_summary = summary->main_body_summary();
  1645     guarantee(body_summary != NULL, "should not be null!");
  1647     if (_satb_drain_time_set)
  1648       body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
  1649     else
  1650       body_summary->record_satb_drain_time_ms(0.0);
  1651     body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
  1652     body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
  1653     body_summary->record_scan_only_time_ms(scan_only_time);
  1654     body_summary->record_update_rs_time_ms(update_rs_time);
  1655     body_summary->record_scan_rs_time_ms(scan_rs_time);
  1656     body_summary->record_obj_copy_time_ms(obj_copy_time);
  1657     if (parallel) {
  1658       body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
  1659       body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
  1660       body_summary->record_termination_time_ms(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   if (update_stats) {
  1806     summary->record_total_time_ms(elapsed_ms);
  1807     summary->record_other_time_ms(other_time_ms);
  1809   for (int i = 0; i < _aux_num; ++i)
  1810     if (_cur_aux_times_set[i])
  1811       _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
  1813   // Reset marks-between-pauses counter.
  1814   _n_marks_since_last_pause = 0;
  1816   // Update the efficiency-since-mark vars.
  1817   double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
  1818   if (elapsed_ms < MIN_TIMER_GRANULARITY) {
  1819     // This usually happens due to the timer not having the required
  1820     // granularity. Some Linuxes are the usual culprits.
  1821     // We'll just set it to something (arbitrarily) small.
  1822     proc_ms = 1.0;
  1824   double cur_efficiency = (double) freed_bytes / proc_ms;
  1826   bool new_in_marking_window = _in_marking_window;
  1827   bool new_in_marking_window_im = false;
  1828   if (_should_initiate_conc_mark) {
  1829     new_in_marking_window = true;
  1830     new_in_marking_window_im = true;
  1833   if (in_young_gc_mode()) {
  1834     if (_last_full_young_gc) {
  1835       set_full_young_gcs(false);
  1836       _last_full_young_gc = false;
  1839     if ( !_last_young_gc_full ) {
  1840       if ( _should_revert_to_full_young_gcs ||
  1841            _known_garbage_ratio < 0.05 ||
  1842            (adaptive_young_list_length() &&
  1843            (get_gc_eff_factor() * cur_efficiency < predict_young_gc_eff())) ) {
  1844         set_full_young_gcs(true);
  1847     _should_revert_to_full_young_gcs = false;
  1849     if (_last_young_gc_full && !_during_marking)
  1850       _young_gc_eff_seq->add(cur_efficiency);
  1853   _short_lived_surv_rate_group->start_adding_regions();
  1854   // do that for any other surv rate groupsx
  1856   // <NEW PREDICTION>
  1858   if (!popular && update_stats) {
  1859     double pause_time_ms = elapsed_ms;
  1861     size_t diff = 0;
  1862     if (_max_pending_cards >= _pending_cards)
  1863       diff = _max_pending_cards - _pending_cards;
  1864     _pending_card_diff_seq->add((double) diff);
  1866     double cost_per_card_ms = 0.0;
  1867     if (_pending_cards > 0) {
  1868       cost_per_card_ms = update_rs_time / (double) _pending_cards;
  1869       _cost_per_card_ms_seq->add(cost_per_card_ms);
  1872     double cost_per_scan_only_region_ms = 0.0;
  1873     if (scan_only_regions_scanned > 0.0) {
  1874       cost_per_scan_only_region_ms =
  1875         scan_only_time / scan_only_regions_scanned;
  1876       if (_in_marking_window_im)
  1877         _cost_per_scan_only_region_ms_during_cm_seq->add(cost_per_scan_only_region_ms);
  1878       else
  1879         _cost_per_scan_only_region_ms_seq->add(cost_per_scan_only_region_ms);
  1882     size_t cards_scanned = _g1->cards_scanned();
  1884     double cost_per_entry_ms = 0.0;
  1885     if (cards_scanned > 10) {
  1886       cost_per_entry_ms = scan_rs_time / (double) cards_scanned;
  1887       if (_last_young_gc_full)
  1888         _cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1889       else
  1890         _partially_young_cost_per_entry_ms_seq->add(cost_per_entry_ms);
  1893     if (_max_rs_lengths > 0) {
  1894       double cards_per_entry_ratio =
  1895         (double) cards_scanned / (double) _max_rs_lengths;
  1896       if (_last_young_gc_full)
  1897         _fully_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1898       else
  1899         _partially_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
  1902     size_t rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
  1903     if (rs_length_diff >= 0)
  1904       _rs_length_diff_seq->add((double) rs_length_diff);
  1906     size_t copied_bytes = surviving_bytes;
  1907     double cost_per_byte_ms = 0.0;
  1908     if (copied_bytes > 0) {
  1909       cost_per_byte_ms = obj_copy_time / (double) copied_bytes;
  1910       if (_in_marking_window)
  1911         _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
  1912       else
  1913         _cost_per_byte_ms_seq->add(cost_per_byte_ms);
  1916     double all_other_time_ms = pause_time_ms -
  1917       (update_rs_time + scan_only_time + scan_rs_time + obj_copy_time +
  1918        _mark_closure_time_ms + termination_time);
  1920     double young_other_time_ms = 0.0;
  1921     if (_recorded_young_regions > 0) {
  1922       young_other_time_ms =
  1923         _recorded_young_cset_choice_time_ms +
  1924         _recorded_young_free_cset_time_ms;
  1925       _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
  1926                                              (double) _recorded_young_regions);
  1928     double non_young_other_time_ms = 0.0;
  1929     if (_recorded_non_young_regions > 0) {
  1930       non_young_other_time_ms =
  1931         _recorded_non_young_cset_choice_time_ms +
  1932         _recorded_non_young_free_cset_time_ms;
  1934       _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
  1935                                          (double) _recorded_non_young_regions);
  1938     double constant_other_time_ms = all_other_time_ms -
  1939       (young_other_time_ms + non_young_other_time_ms);
  1940     _constant_other_time_ms_seq->add(constant_other_time_ms);
  1942     double survival_ratio = 0.0;
  1943     if (_bytes_in_collection_set_before_gc > 0) {
  1944       survival_ratio = (double) bytes_in_to_space_during_gc() /
  1945         (double) _bytes_in_collection_set_before_gc;
  1948     _pending_cards_seq->add((double) _pending_cards);
  1949     _scanned_cards_seq->add((double) cards_scanned);
  1950     _rs_lengths_seq->add((double) _max_rs_lengths);
  1952     double expensive_region_limit_ms =
  1953       (double) G1MaxPauseTimeMS - predict_constant_other_time_ms();
  1954     if (expensive_region_limit_ms < 0.0) {
  1955       // this means that the other time was predicted to be longer than
  1956       // than the max pause time
  1957       expensive_region_limit_ms = (double) G1MaxPauseTimeMS;
  1959     _expensive_region_limit_ms = expensive_region_limit_ms;
  1961     if (PREDICTIONS_VERBOSE) {
  1962       gclog_or_tty->print_cr("");
  1963       gclog_or_tty->print_cr("PREDICTIONS %1.4lf %d "
  1964                     "REGIONS %d %d %d %d "
  1965                     "PENDING_CARDS %d %d "
  1966                     "CARDS_SCANNED %d %d "
  1967                     "RS_LENGTHS %d %d "
  1968                     "SCAN_ONLY_SCAN %1.6lf %1.6lf "
  1969                     "RS_UPDATE %1.6lf %1.6lf RS_SCAN %1.6lf %1.6lf "
  1970                     "SURVIVAL_RATIO %1.6lf %1.6lf "
  1971                     "OBJECT_COPY %1.6lf %1.6lf OTHER_CONSTANT %1.6lf %1.6lf "
  1972                     "OTHER_YOUNG %1.6lf %1.6lf "
  1973                     "OTHER_NON_YOUNG %1.6lf %1.6lf "
  1974                     "VTIME_DIFF %1.6lf TERMINATION %1.6lf "
  1975                     "ELAPSED %1.6lf %1.6lf ",
  1976                     _cur_collection_start_sec,
  1977                     (!_last_young_gc_full) ? 2 :
  1978                     (last_pause_included_initial_mark) ? 1 : 0,
  1979                     _recorded_region_num,
  1980                     _recorded_young_regions,
  1981                     _recorded_scan_only_regions,
  1982                     _recorded_non_young_regions,
  1983                     _predicted_pending_cards, _pending_cards,
  1984                     _predicted_cards_scanned, cards_scanned,
  1985                     _predicted_rs_lengths, _max_rs_lengths,
  1986                     _predicted_scan_only_scan_time_ms, scan_only_time,
  1987                     _predicted_rs_update_time_ms, update_rs_time,
  1988                     _predicted_rs_scan_time_ms, scan_rs_time,
  1989                     _predicted_survival_ratio, survival_ratio,
  1990                     _predicted_object_copy_time_ms, obj_copy_time,
  1991                     _predicted_constant_other_time_ms, constant_other_time_ms,
  1992                     _predicted_young_other_time_ms, young_other_time_ms,
  1993                     _predicted_non_young_other_time_ms,
  1994                     non_young_other_time_ms,
  1995                     _vtime_diff_ms, termination_time,
  1996                     _predicted_pause_time_ms, elapsed_ms);
  1999     if (G1PolicyVerbose > 0) {
  2000       gclog_or_tty->print_cr("Pause Time, predicted: %1.4lfms (predicted %s), actual: %1.4lfms",
  2001                     _predicted_pause_time_ms,
  2002                     (_within_target) ? "within" : "outside",
  2003                     elapsed_ms);
  2008   _in_marking_window = new_in_marking_window;
  2009   _in_marking_window_im = new_in_marking_window_im;
  2010   _free_regions_at_end_of_collection = _g1->free_regions();
  2011   _scan_only_regions_at_end_of_collection = _g1->young_list_length();
  2012   calculate_young_list_min_length();
  2013   calculate_young_list_target_config();
  2015   // </NEW PREDICTION>
  2017   _target_pause_time_ms = -1.0;
  2020 // <NEW PREDICTION>
  2022 double
  2023 G1CollectorPolicy::
  2024 predict_young_collection_elapsed_time_ms(size_t adjustment) {
  2025   guarantee( adjustment == 0 || adjustment == 1, "invariant" );
  2027   G1CollectedHeap* g1h = G1CollectedHeap::heap();
  2028   size_t young_num = g1h->young_list_length();
  2029   if (young_num == 0)
  2030     return 0.0;
  2032   young_num += adjustment;
  2033   size_t pending_cards = predict_pending_cards();
  2034   size_t rs_lengths = g1h->young_list_sampled_rs_lengths() +
  2035                       predict_rs_length_diff();
  2036   size_t card_num;
  2037   if (full_young_gcs())
  2038     card_num = predict_young_card_num(rs_lengths);
  2039   else
  2040     card_num = predict_non_young_card_num(rs_lengths);
  2041   size_t young_byte_size = young_num * HeapRegion::GrainBytes;
  2042   double accum_yg_surv_rate =
  2043     _short_lived_surv_rate_group->accum_surv_rate(adjustment);
  2045   size_t bytes_to_copy =
  2046     (size_t) (accum_yg_surv_rate * (double) HeapRegion::GrainBytes);
  2048   return
  2049     predict_rs_update_time_ms(pending_cards) +
  2050     predict_rs_scan_time_ms(card_num) +
  2051     predict_object_copy_time_ms(bytes_to_copy) +
  2052     predict_young_other_time_ms(young_num) +
  2053     predict_constant_other_time_ms();
  2056 double
  2057 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
  2058   size_t rs_length = predict_rs_length_diff();
  2059   size_t card_num;
  2060   if (full_young_gcs())
  2061     card_num = predict_young_card_num(rs_length);
  2062   else
  2063     card_num = predict_non_young_card_num(rs_length);
  2064   return predict_base_elapsed_time_ms(pending_cards, card_num);
  2067 double
  2068 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
  2069                                                 size_t scanned_cards) {
  2070   return
  2071     predict_rs_update_time_ms(pending_cards) +
  2072     predict_rs_scan_time_ms(scanned_cards) +
  2073     predict_constant_other_time_ms();
  2076 double
  2077 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
  2078                                                   bool young) {
  2079   size_t rs_length = hr->rem_set()->occupied();
  2080   size_t card_num;
  2081   if (full_young_gcs())
  2082     card_num = predict_young_card_num(rs_length);
  2083   else
  2084     card_num = predict_non_young_card_num(rs_length);
  2085   size_t bytes_to_copy = predict_bytes_to_copy(hr);
  2087   double region_elapsed_time_ms =
  2088     predict_rs_scan_time_ms(card_num) +
  2089     predict_object_copy_time_ms(bytes_to_copy);
  2091   if (young)
  2092     region_elapsed_time_ms += predict_young_other_time_ms(1);
  2093   else
  2094     region_elapsed_time_ms += predict_non_young_other_time_ms(1);
  2096   return region_elapsed_time_ms;
  2099 size_t
  2100 G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
  2101   size_t bytes_to_copy;
  2102   if (hr->is_marked())
  2103     bytes_to_copy = hr->max_live_bytes();
  2104   else {
  2105     guarantee( hr->is_young() && hr->age_in_surv_rate_group() != -1,
  2106                "invariant" );
  2107     int age = hr->age_in_surv_rate_group();
  2108     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
  2109     bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
  2112   return bytes_to_copy;
  2115 void
  2116 G1CollectorPolicy::start_recording_regions() {
  2117   _recorded_rs_lengths            = 0;
  2118   _recorded_scan_only_regions     = 0;
  2119   _recorded_young_regions         = 0;
  2120   _recorded_non_young_regions     = 0;
  2122 #if PREDICTIONS_VERBOSE
  2123   _predicted_rs_lengths           = 0;
  2124   _predicted_cards_scanned        = 0;
  2126   _recorded_marked_bytes          = 0;
  2127   _recorded_young_bytes           = 0;
  2128   _predicted_bytes_to_copy        = 0;
  2129 #endif // PREDICTIONS_VERBOSE
  2132 void
  2133 G1CollectorPolicy::record_cset_region(HeapRegion* hr, bool young) {
  2134   if (young) {
  2135     ++_recorded_young_regions;
  2136   } else {
  2137     ++_recorded_non_young_regions;
  2139 #if PREDICTIONS_VERBOSE
  2140   if (young) {
  2141     _recorded_young_bytes += hr->used();
  2142   } else {
  2143     _recorded_marked_bytes += hr->max_live_bytes();
  2145   _predicted_bytes_to_copy += predict_bytes_to_copy(hr);
  2146 #endif // PREDICTIONS_VERBOSE
  2148   size_t rs_length = hr->rem_set()->occupied();
  2149   _recorded_rs_lengths += rs_length;
  2152 void
  2153 G1CollectorPolicy::record_scan_only_regions(size_t scan_only_length) {
  2154   _recorded_scan_only_regions = scan_only_length;
  2157 void
  2158 G1CollectorPolicy::end_recording_regions() {
  2159 #if PREDICTIONS_VERBOSE
  2160   _predicted_pending_cards = predict_pending_cards();
  2161   _predicted_rs_lengths = _recorded_rs_lengths + predict_rs_length_diff();
  2162   if (full_young_gcs())
  2163     _predicted_cards_scanned += predict_young_card_num(_predicted_rs_lengths);
  2164   else
  2165     _predicted_cards_scanned +=
  2166       predict_non_young_card_num(_predicted_rs_lengths);
  2167   _recorded_region_num = _recorded_young_regions + _recorded_non_young_regions;
  2169   _predicted_scan_only_scan_time_ms =
  2170     predict_scan_only_time_ms(_recorded_scan_only_regions);
  2171   _predicted_rs_update_time_ms =
  2172     predict_rs_update_time_ms(_g1->pending_card_num());
  2173   _predicted_rs_scan_time_ms =
  2174     predict_rs_scan_time_ms(_predicted_cards_scanned);
  2175   _predicted_object_copy_time_ms =
  2176     predict_object_copy_time_ms(_predicted_bytes_to_copy);
  2177   _predicted_constant_other_time_ms =
  2178     predict_constant_other_time_ms();
  2179   _predicted_young_other_time_ms =
  2180     predict_young_other_time_ms(_recorded_young_regions);
  2181   _predicted_non_young_other_time_ms =
  2182     predict_non_young_other_time_ms(_recorded_non_young_regions);
  2184   _predicted_pause_time_ms =
  2185     _predicted_scan_only_scan_time_ms +
  2186     _predicted_rs_update_time_ms +
  2187     _predicted_rs_scan_time_ms +
  2188     _predicted_object_copy_time_ms +
  2189     _predicted_constant_other_time_ms +
  2190     _predicted_young_other_time_ms +
  2191     _predicted_non_young_other_time_ms;
  2192 #endif // PREDICTIONS_VERBOSE
  2195 void G1CollectorPolicy::check_if_region_is_too_expensive(double
  2196                                                            predicted_time_ms) {
  2197   // I don't think we need to do this when in young GC mode since
  2198   // marking will be initiated next time we hit the soft limit anyway...
  2199   if (predicted_time_ms > _expensive_region_limit_ms) {
  2200     if (!in_young_gc_mode()) {
  2201         set_full_young_gcs(true);
  2202       _should_initiate_conc_mark = true;
  2203     } else
  2204       // no point in doing another partial one
  2205       _should_revert_to_full_young_gcs = true;
  2209 // </NEW PREDICTION>
  2212 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
  2213                                                double elapsed_ms) {
  2214   _recent_gc_times_ms->add(elapsed_ms);
  2215   _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
  2216   _prev_collection_pause_end_ms = end_time_sec * 1000.0;
  2219 double G1CollectorPolicy::recent_avg_time_for_pauses_ms() {
  2220   if (_recent_pause_times_ms->num() == 0) return (double) G1MaxPauseTimeMS;
  2221   else return _recent_pause_times_ms->avg();
  2224 double G1CollectorPolicy::recent_avg_time_for_CH_strong_ms() {
  2225   if (_recent_CH_strong_roots_times_ms->num() == 0)
  2226     return (double)G1MaxPauseTimeMS/3.0;
  2227   else return _recent_CH_strong_roots_times_ms->avg();
  2230 double G1CollectorPolicy::recent_avg_time_for_G1_strong_ms() {
  2231   if (_recent_G1_strong_roots_times_ms->num() == 0)
  2232     return (double)G1MaxPauseTimeMS/3.0;
  2233   else return _recent_G1_strong_roots_times_ms->avg();
  2236 double G1CollectorPolicy::recent_avg_time_for_evac_ms() {
  2237   if (_recent_evac_times_ms->num() == 0) return (double)G1MaxPauseTimeMS/3.0;
  2238   else return _recent_evac_times_ms->avg();
  2241 int G1CollectorPolicy::number_of_recent_gcs() {
  2242   assert(_recent_CH_strong_roots_times_ms->num() ==
  2243          _recent_G1_strong_roots_times_ms->num(), "Sequence out of sync");
  2244   assert(_recent_G1_strong_roots_times_ms->num() ==
  2245          _recent_evac_times_ms->num(), "Sequence out of sync");
  2246   assert(_recent_evac_times_ms->num() ==
  2247          _recent_pause_times_ms->num(), "Sequence out of sync");
  2248   assert(_recent_pause_times_ms->num() ==
  2249          _recent_CS_bytes_used_before->num(), "Sequence out of sync");
  2250   assert(_recent_CS_bytes_used_before->num() ==
  2251          _recent_CS_bytes_surviving->num(), "Sequence out of sync");
  2252   return _recent_pause_times_ms->num();
  2255 double G1CollectorPolicy::recent_avg_survival_fraction() {
  2256   return recent_avg_survival_fraction_work(_recent_CS_bytes_surviving,
  2257                                            _recent_CS_bytes_used_before);
  2260 double G1CollectorPolicy::last_survival_fraction() {
  2261   return last_survival_fraction_work(_recent_CS_bytes_surviving,
  2262                                      _recent_CS_bytes_used_before);
  2265 double
  2266 G1CollectorPolicy::recent_avg_survival_fraction_work(TruncatedSeq* surviving,
  2267                                                      TruncatedSeq* before) {
  2268   assert(surviving->num() == before->num(), "Sequence out of sync");
  2269   if (before->sum() > 0.0) {
  2270       double recent_survival_rate = surviving->sum() / before->sum();
  2271       // We exempt parallel collection from this check because Alloc Buffer
  2272       // fragmentation can produce negative collections.
  2273       // Further, we're now always doing parallel collection.  But I'm still
  2274       // leaving this here as a placeholder for a more precise assertion later.
  2275       // (DLD, 10/05.)
  2276       assert((true || ParallelGCThreads > 0) ||
  2277              _g1->evacuation_failed() ||
  2278              recent_survival_rate <= 1.0, "Or bad frac");
  2279       return recent_survival_rate;
  2280   } else {
  2281     return 1.0; // Be conservative.
  2285 double
  2286 G1CollectorPolicy::last_survival_fraction_work(TruncatedSeq* surviving,
  2287                                                TruncatedSeq* before) {
  2288   assert(surviving->num() == before->num(), "Sequence out of sync");
  2289   if (surviving->num() > 0 && before->last() > 0.0) {
  2290     double last_survival_rate = surviving->last() / before->last();
  2291     // We exempt parallel collection from this check because Alloc Buffer
  2292     // fragmentation can produce negative collections.
  2293     // Further, we're now always doing parallel collection.  But I'm still
  2294     // leaving this here as a placeholder for a more precise assertion later.
  2295     // (DLD, 10/05.)
  2296     assert((true || ParallelGCThreads > 0) ||
  2297            last_survival_rate <= 1.0, "Or bad frac");
  2298     return last_survival_rate;
  2299   } else {
  2300     return 1.0;
  2304 static const int survival_min_obs = 5;
  2305 static double survival_min_obs_limits[] = { 0.9, 0.7, 0.5, 0.3, 0.1 };
  2306 static const double min_survival_rate = 0.1;
  2308 double
  2309 G1CollectorPolicy::conservative_avg_survival_fraction_work(double avg,
  2310                                                            double latest) {
  2311   double res = avg;
  2312   if (number_of_recent_gcs() < survival_min_obs) {
  2313     res = MAX2(res, survival_min_obs_limits[number_of_recent_gcs()]);
  2315   res = MAX2(res, latest);
  2316   res = MAX2(res, min_survival_rate);
  2317   // In the parallel case, LAB fragmentation can produce "negative
  2318   // collections"; so can evac failure.  Cap at 1.0
  2319   res = MIN2(res, 1.0);
  2320   return res;
  2323 size_t G1CollectorPolicy::expansion_amount() {
  2324   if ((int)(recent_avg_pause_time_ratio() * 100.0) > G1GCPct) {
  2325     // We will double the existing space, or take G1ExpandByPctOfAvail % of
  2326     // the available expansion space, whichever is smaller, bounded below
  2327     // by a minimum expansion (unless that's all that's left.)
  2328     const size_t min_expand_bytes = 1*M;
  2329     size_t reserved_bytes = _g1->g1_reserved_obj_bytes();
  2330     size_t committed_bytes = _g1->capacity();
  2331     size_t uncommitted_bytes = reserved_bytes - committed_bytes;
  2332     size_t expand_bytes;
  2333     size_t expand_bytes_via_pct =
  2334       uncommitted_bytes * G1ExpandByPctOfAvail / 100;
  2335     expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
  2336     expand_bytes = MAX2(expand_bytes, min_expand_bytes);
  2337     expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
  2338     if (G1PolicyVerbose > 1) {
  2339       gclog_or_tty->print("Decided to expand: ratio = %5.2f, "
  2340                  "committed = %d%s, uncommited = %d%s, via pct = %d%s.\n"
  2341                  "                   Answer = %d.\n",
  2342                  recent_avg_pause_time_ratio(),
  2343                  byte_size_in_proper_unit(committed_bytes),
  2344                  proper_unit_for_byte_size(committed_bytes),
  2345                  byte_size_in_proper_unit(uncommitted_bytes),
  2346                  proper_unit_for_byte_size(uncommitted_bytes),
  2347                  byte_size_in_proper_unit(expand_bytes_via_pct),
  2348                  proper_unit_for_byte_size(expand_bytes_via_pct),
  2349                  byte_size_in_proper_unit(expand_bytes),
  2350                  proper_unit_for_byte_size(expand_bytes));
  2352     return expand_bytes;
  2353   } else {
  2354     return 0;
  2358 void G1CollectorPolicy::note_start_of_mark_thread() {
  2359   _mark_thread_startup_sec = os::elapsedTime();
  2362 class CountCSClosure: public HeapRegionClosure {
  2363   G1CollectorPolicy* _g1_policy;
  2364 public:
  2365   CountCSClosure(G1CollectorPolicy* g1_policy) :
  2366     _g1_policy(g1_policy) {}
  2367   bool doHeapRegion(HeapRegion* r) {
  2368     _g1_policy->_bytes_in_collection_set_before_gc += r->used();
  2369     return false;
  2371 };
  2373 void G1CollectorPolicy::count_CS_bytes_used() {
  2374   CountCSClosure cs_closure(this);
  2375   _g1->collection_set_iterate(&cs_closure);
  2378 static void print_indent(int level) {
  2379   for (int j = 0; j < level+1; ++j)
  2380     gclog_or_tty->print("   ");
  2383 void G1CollectorPolicy::print_summary (int level,
  2384                                        const char* str,
  2385                                        NumberSeq* seq) const {
  2386   double sum = seq->sum();
  2387   print_indent(level);
  2388   gclog_or_tty->print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
  2389                 str, sum / 1000.0, seq->avg());
  2392 void G1CollectorPolicy::print_summary_sd (int level,
  2393                                           const char* str,
  2394                                           NumberSeq* seq) const {
  2395   print_summary(level, str, seq);
  2396   print_indent(level + 5);
  2397   gclog_or_tty->print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
  2398                 seq->num(), seq->sd(), seq->maximum());
  2401 void G1CollectorPolicy::check_other_times(int level,
  2402                                         NumberSeq* other_times_ms,
  2403                                         NumberSeq* calc_other_times_ms) const {
  2404   bool should_print = false;
  2406   double max_sum = MAX2(fabs(other_times_ms->sum()),
  2407                         fabs(calc_other_times_ms->sum()));
  2408   double min_sum = MIN2(fabs(other_times_ms->sum()),
  2409                         fabs(calc_other_times_ms->sum()));
  2410   double sum_ratio = max_sum / min_sum;
  2411   if (sum_ratio > 1.1) {
  2412     should_print = true;
  2413     print_indent(level + 1);
  2414     gclog_or_tty->print_cr("## CALCULATED OTHER SUM DOESN'T MATCH RECORDED ###");
  2417   double max_avg = MAX2(fabs(other_times_ms->avg()),
  2418                         fabs(calc_other_times_ms->avg()));
  2419   double min_avg = MIN2(fabs(other_times_ms->avg()),
  2420                         fabs(calc_other_times_ms->avg()));
  2421   double avg_ratio = max_avg / min_avg;
  2422   if (avg_ratio > 1.1) {
  2423     should_print = true;
  2424     print_indent(level + 1);
  2425     gclog_or_tty->print_cr("## CALCULATED OTHER AVG DOESN'T MATCH RECORDED ###");
  2428   if (other_times_ms->sum() < -0.01) {
  2429     print_indent(level + 1);
  2430     gclog_or_tty->print_cr("## RECORDED OTHER SUM IS NEGATIVE ###");
  2433   if (other_times_ms->avg() < -0.01) {
  2434     print_indent(level + 1);
  2435     gclog_or_tty->print_cr("## RECORDED OTHER AVG IS NEGATIVE ###");
  2438   if (calc_other_times_ms->sum() < -0.01) {
  2439     should_print = true;
  2440     print_indent(level + 1);
  2441     gclog_or_tty->print_cr("## CALCULATED OTHER SUM IS NEGATIVE ###");
  2444   if (calc_other_times_ms->avg() < -0.01) {
  2445     should_print = true;
  2446     print_indent(level + 1);
  2447     gclog_or_tty->print_cr("## CALCULATED OTHER AVG IS NEGATIVE ###");
  2450   if (should_print)
  2451     print_summary(level, "Other(Calc)", calc_other_times_ms);
  2454 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
  2455   bool parallel = ParallelGCThreads > 0;
  2456   MainBodySummary*    body_summary = summary->main_body_summary();
  2457   PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
  2459   if (summary->get_total_seq()->num() > 0) {
  2460     print_summary_sd(0,
  2461                      (preamble_summary == NULL) ? "Non-Popular Pauses" :
  2462                      "Popular Pauses",
  2463                      summary->get_total_seq());
  2464     if (preamble_summary != NULL) {
  2465       print_summary(1, "Popularity Preamble",
  2466                     preamble_summary->get_pop_preamble_seq());
  2467       print_summary(2, "Update RS", preamble_summary->get_pop_update_rs_seq());
  2468       print_summary(2, "Scan RS", preamble_summary->get_pop_scan_rs_seq());
  2469       print_summary(2, "Closure App",
  2470                     preamble_summary->get_pop_closure_app_seq());
  2471       print_summary(2, "Evacuation",
  2472                     preamble_summary->get_pop_evacuation_seq());
  2473       print_summary(2, "Other", preamble_summary->get_pop_other_seq());
  2475         NumberSeq* other_parts[] = {
  2476           preamble_summary->get_pop_update_rs_seq(),
  2477           preamble_summary->get_pop_scan_rs_seq(),
  2478           preamble_summary->get_pop_closure_app_seq(),
  2479           preamble_summary->get_pop_evacuation_seq()
  2480         };
  2481         NumberSeq calc_other_times_ms(preamble_summary->get_pop_preamble_seq(),
  2482                                       4, other_parts);
  2483         check_other_times(2, preamble_summary->get_pop_other_seq(),
  2484                           &calc_other_times_ms);
  2487     if (body_summary != NULL) {
  2488       print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
  2489       if (parallel) {
  2490         print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
  2491         print_summary(2, "Update RS", body_summary->get_update_rs_seq());
  2492         print_summary(2, "Ext Root Scanning",
  2493                       body_summary->get_ext_root_scan_seq());
  2494         print_summary(2, "Mark Stack Scanning",
  2495                       body_summary->get_mark_stack_scan_seq());
  2496         print_summary(2, "Scan-Only Scanning",
  2497                       body_summary->get_scan_only_seq());
  2498         print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
  2499         print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
  2500         print_summary(2, "Termination", body_summary->get_termination_seq());
  2501         print_summary(2, "Other", body_summary->get_parallel_other_seq());
  2503           NumberSeq* other_parts[] = {
  2504             body_summary->get_update_rs_seq(),
  2505             body_summary->get_ext_root_scan_seq(),
  2506             body_summary->get_mark_stack_scan_seq(),
  2507             body_summary->get_scan_only_seq(),
  2508             body_summary->get_scan_rs_seq(),
  2509             body_summary->get_obj_copy_seq(),
  2510             body_summary->get_termination_seq()
  2511           };
  2512           NumberSeq calc_other_times_ms(body_summary->get_parallel_seq(),
  2513                                         7, other_parts);
  2514           check_other_times(2, body_summary->get_parallel_other_seq(),
  2515                             &calc_other_times_ms);
  2517         print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
  2518         print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
  2519       } else {
  2520         print_summary(1, "Update RS", body_summary->get_update_rs_seq());
  2521         print_summary(1, "Ext Root Scanning",
  2522                       body_summary->get_ext_root_scan_seq());
  2523         print_summary(1, "Mark Stack Scanning",
  2524                       body_summary->get_mark_stack_scan_seq());
  2525         print_summary(1, "Scan-Only Scanning",
  2526                       body_summary->get_scan_only_seq());
  2527         print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
  2528         print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
  2531     print_summary(1, "Other", summary->get_other_seq());
  2533       NumberSeq calc_other_times_ms;
  2534       if (body_summary != NULL) {
  2535         // not abandoned
  2536         if (parallel) {
  2537           // parallel
  2538           NumberSeq* other_parts[] = {
  2539             body_summary->get_satb_drain_seq(),
  2540             (preamble_summary == NULL) ? NULL :
  2541               preamble_summary->get_pop_preamble_seq(),
  2542             body_summary->get_parallel_seq(),
  2543             body_summary->get_clear_ct_seq()
  2544           };
  2545           calc_other_times_ms = NumberSeq (summary->get_total_seq(),
  2546                                           4, other_parts);
  2547         } else {
  2548           // serial
  2549           NumberSeq* other_parts[] = {
  2550             body_summary->get_satb_drain_seq(),
  2551             (preamble_summary == NULL) ? NULL :
  2552               preamble_summary->get_pop_preamble_seq(),
  2553             body_summary->get_update_rs_seq(),
  2554             body_summary->get_ext_root_scan_seq(),
  2555             body_summary->get_mark_stack_scan_seq(),
  2556             body_summary->get_scan_only_seq(),
  2557             body_summary->get_scan_rs_seq(),
  2558             body_summary->get_obj_copy_seq()
  2559           };
  2560           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2561                                           8, other_parts);
  2563       } else {
  2564         // abandoned
  2565         NumberSeq* other_parts[] = {
  2566           (preamble_summary == NULL) ? NULL :
  2567             preamble_summary->get_pop_preamble_seq()
  2568         };
  2569         calc_other_times_ms = NumberSeq(summary->get_total_seq(),
  2570                                         1, other_parts);
  2572       check_other_times(1,  summary->get_other_seq(), &calc_other_times_ms);
  2574   } else {
  2575     print_indent(0);
  2576     gclog_or_tty->print_cr("none");
  2578   gclog_or_tty->print_cr("");
  2581 void
  2582 G1CollectorPolicy::print_abandoned_summary(PauseSummary* non_pop_summary,
  2583                                            PauseSummary* pop_summary) const {
  2584   bool printed = false;
  2585   if (non_pop_summary->get_total_seq()->num() > 0) {
  2586     printed = true;
  2587     print_summary(non_pop_summary);
  2589   if (pop_summary->get_total_seq()->num() > 0) {
  2590     printed = true;
  2591     print_summary(pop_summary);
  2594   if (!printed) {
  2595     print_indent(0);
  2596     gclog_or_tty->print_cr("none");
  2597     gclog_or_tty->print_cr("");
  2601 void G1CollectorPolicy::print_tracing_info() const {
  2602   if (TraceGen0Time) {
  2603     gclog_or_tty->print_cr("ALL PAUSES");
  2604     print_summary_sd(0, "Total", _all_pause_times_ms);
  2605     gclog_or_tty->print_cr("");
  2606     gclog_or_tty->print_cr("");
  2607     gclog_or_tty->print_cr("   Full Young GC Pauses:    %8d", _full_young_pause_num);
  2608     gclog_or_tty->print_cr("   Partial Young GC Pauses: %8d", _partial_young_pause_num);
  2609     gclog_or_tty->print_cr("");
  2611     gclog_or_tty->print_cr("NON-POPULAR PAUSES");
  2612     print_summary(_non_pop_summary);
  2614     gclog_or_tty->print_cr("POPULAR PAUSES");
  2615     print_summary(_pop_summary);
  2617     gclog_or_tty->print_cr("ABANDONED PAUSES");
  2618     print_abandoned_summary(_non_pop_abandoned_summary,
  2619                             _pop_abandoned_summary);
  2621     gclog_or_tty->print_cr("MISC");
  2622     print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
  2623     print_summary_sd(0, "Yields", _all_yield_times_ms);
  2624     for (int i = 0; i < _aux_num; ++i) {
  2625       if (_all_aux_times_ms[i].num() > 0) {
  2626         char buffer[96];
  2627         sprintf(buffer, "Aux%d", i);
  2628         print_summary_sd(0, buffer, &_all_aux_times_ms[i]);
  2632     size_t all_region_num = _region_num_young + _region_num_tenured;
  2633     gclog_or_tty->print_cr("   New Regions %8d, Young %8d (%6.2lf%%), "
  2634                "Tenured %8d (%6.2lf%%)",
  2635                all_region_num,
  2636                _region_num_young,
  2637                (double) _region_num_young / (double) all_region_num * 100.0,
  2638                _region_num_tenured,
  2639                (double) _region_num_tenured / (double) all_region_num * 100.0);
  2641     if (!G1RSBarrierUseQueue) {
  2642       gclog_or_tty->print_cr("Of %d times conc refinement was enabled, %d (%7.2f%%) "
  2643                     "did zero traversals.",
  2644                     _conc_refine_enabled, _conc_refine_zero_traversals,
  2645                     _conc_refine_enabled > 0 ?
  2646                     100.0 * (float)_conc_refine_zero_traversals/
  2647                     (float)_conc_refine_enabled : 0.0);
  2648       gclog_or_tty->print_cr("  Max # of traversals = %d.",
  2649                     _conc_refine_max_traversals);
  2650       gclog_or_tty->print_cr("");
  2653   if (TraceGen1Time) {
  2654     if (_all_full_gc_times_ms->num() > 0) {
  2655       gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
  2656                  _all_full_gc_times_ms->num(),
  2657                  _all_full_gc_times_ms->sum() / 1000.0);
  2658       gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times_ms->avg());
  2659       gclog_or_tty->print_cr("                     [std. dev = %8.2f ms, max = %8.2f ms]",
  2660                     _all_full_gc_times_ms->sd(),
  2661                     _all_full_gc_times_ms->maximum());
  2666 void G1CollectorPolicy::print_yg_surv_rate_info() const {
  2667 #ifndef PRODUCT
  2668   _short_lived_surv_rate_group->print_surv_rate_summary();
  2669   // add this call for any other surv rate groups
  2670 #endif // PRODUCT
  2673 void G1CollectorPolicy::update_conc_refine_data() {
  2674   unsigned traversals = _g1->concurrent_g1_refine()->disable();
  2675   if (traversals == 0) _conc_refine_zero_traversals++;
  2676   _conc_refine_max_traversals = MAX2(_conc_refine_max_traversals,
  2677                                      (size_t)traversals);
  2679   if (G1PolicyVerbose > 1)
  2680     gclog_or_tty->print_cr("Did a CR traversal series: %d traversals.", traversals);
  2681   double multiplier = 1.0;
  2682   if (traversals == 0) {
  2683     multiplier = 4.0;
  2684   } else if (traversals > (size_t)G1ConcRefineTargTraversals) {
  2685     multiplier = 1.0/1.5;
  2686   } else if (traversals < (size_t)G1ConcRefineTargTraversals) {
  2687     multiplier = 1.5;
  2689   if (G1PolicyVerbose > 1) {
  2690     gclog_or_tty->print_cr("  Multiplier = %7.2f.", multiplier);
  2691     gclog_or_tty->print("  Delta went from %d regions to ",
  2692                _conc_refine_current_delta);
  2694   _conc_refine_current_delta =
  2695     MIN2(_g1->n_regions(),
  2696          (size_t)(_conc_refine_current_delta * multiplier));
  2697   _conc_refine_current_delta =
  2698     MAX2(_conc_refine_current_delta, (size_t)1);
  2699   if (G1PolicyVerbose > 1) {
  2700     gclog_or_tty->print_cr("%d regions.", _conc_refine_current_delta);
  2702   _conc_refine_enabled++;
  2705 void G1CollectorPolicy::set_single_region_collection_set(HeapRegion* hr) {
  2706   assert(collection_set() == NULL, "Must be no current CS.");
  2707   _collection_set_size = 0;
  2708   _collection_set_bytes_used_before = 0;
  2709   add_to_collection_set(hr);
  2710   count_CS_bytes_used();
  2713 bool
  2714 G1CollectorPolicy::should_add_next_region_to_young_list() {
  2715   assert(in_young_gc_mode(), "should be in young GC mode");
  2716   bool ret;
  2717   size_t young_list_length = _g1->young_list_length();
  2718   size_t young_list_max_length = _young_list_target_length;
  2719   if (G1FixedEdenSize) {
  2720     young_list_max_length -= _max_survivor_regions;
  2722   if (young_list_length < young_list_max_length) {
  2723     ret = true;
  2724     ++_region_num_young;
  2725   } else {
  2726     ret = false;
  2727     ++_region_num_tenured;
  2730   return ret;
  2733 #ifndef PRODUCT
  2734 // for debugging, bit of a hack...
  2735 static char*
  2736 region_num_to_mbs(int length) {
  2737   static char buffer[64];
  2738   double bytes = (double) (length * HeapRegion::GrainBytes);
  2739   double mbs = bytes / (double) (1024 * 1024);
  2740   sprintf(buffer, "%7.2lfMB", mbs);
  2741   return buffer;
  2743 #endif // PRODUCT
  2745 void
  2746 G1CollectorPolicy::checkpoint_conc_overhead() {
  2747   double conc_overhead = 0.0;
  2748   if (G1AccountConcurrentOverhead)
  2749     conc_overhead = COTracker::totalPredConcOverhead();
  2750   _mmu_tracker->update_conc_overhead(conc_overhead);
  2751 #if 0
  2752   gclog_or_tty->print(" CO %1.4lf TARGET %1.4lf",
  2753              conc_overhead, _mmu_tracker->max_gc_time());
  2754 #endif
  2758 size_t G1CollectorPolicy::max_regions(int purpose) {
  2759   switch (purpose) {
  2760     case GCAllocForSurvived:
  2761       return _max_survivor_regions;
  2762     case GCAllocForTenured:
  2763       return REGIONS_UNLIMITED;
  2764     default:
  2765       ShouldNotReachHere();
  2766       return REGIONS_UNLIMITED;
  2767   };
  2770 // Calculates survivor space parameters.
  2771 void G1CollectorPolicy::calculate_survivors_policy()
  2773   if (!G1UseSurvivorSpace) {
  2774     return;
  2776   if (G1FixedSurvivorSpaceSize == 0) {
  2777     _max_survivor_regions = _young_list_target_length / SurvivorRatio;
  2778   } else {
  2779     _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
  2782   if (G1FixedTenuringThreshold) {
  2783     _tenuring_threshold = MaxTenuringThreshold;
  2784   } else {
  2785     _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
  2786         HeapRegion::GrainWords * _max_survivor_regions);
  2791 void
  2792 G1CollectorPolicy_BestRegionsFirst::
  2793 set_single_region_collection_set(HeapRegion* hr) {
  2794   G1CollectorPolicy::set_single_region_collection_set(hr);
  2795   _collectionSetChooser->removeRegion(hr);
  2799 bool
  2800 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
  2801                                                                word_size) {
  2802   assert(_g1->regions_accounted_for(), "Region leakage!");
  2803   // Initiate a pause when we reach the steady-state "used" target.
  2804   size_t used_hard = (_g1->capacity() / 100) * G1SteadyStateUsed;
  2805   size_t used_soft =
  2806    MAX2((_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta),
  2807         used_hard/2);
  2808   size_t used = _g1->used();
  2810   double max_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
  2812   size_t young_list_length = _g1->young_list_length();
  2813   size_t young_list_max_length = _young_list_target_length;
  2814   if (G1FixedEdenSize) {
  2815     young_list_max_length -= _max_survivor_regions;
  2817   bool reached_target_length = young_list_length >= young_list_max_length;
  2819   if (in_young_gc_mode()) {
  2820     if (reached_target_length) {
  2821       assert( young_list_length > 0 && _g1->young_list_length() > 0,
  2822               "invariant" );
  2823       _target_pause_time_ms = max_pause_time_ms;
  2824       return true;
  2826   } else {
  2827     guarantee( false, "should not reach here" );
  2830   return false;
  2833 #ifndef PRODUCT
  2834 class HRSortIndexIsOKClosure: public HeapRegionClosure {
  2835   CollectionSetChooser* _chooser;
  2836 public:
  2837   HRSortIndexIsOKClosure(CollectionSetChooser* chooser) :
  2838     _chooser(chooser) {}
  2840   bool doHeapRegion(HeapRegion* r) {
  2841     if (!r->continuesHumongous()) {
  2842       assert(_chooser->regionProperlyOrdered(r), "Ought to be.");
  2844     return false;
  2846 };
  2848 bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() {
  2849   HRSortIndexIsOKClosure cl(_collectionSetChooser);
  2850   _g1->heap_region_iterate(&cl);
  2851   return true;
  2853 #endif
  2855 void
  2856 G1CollectorPolicy_BestRegionsFirst::
  2857 record_collection_pause_start(double start_time_sec, size_t start_used) {
  2858   G1CollectorPolicy::record_collection_pause_start(start_time_sec, start_used);
  2861 class NextNonCSElemFinder: public HeapRegionClosure {
  2862   HeapRegion* _res;
  2863 public:
  2864   NextNonCSElemFinder(): _res(NULL) {}
  2865   bool doHeapRegion(HeapRegion* r) {
  2866     if (!r->in_collection_set()) {
  2867       _res = r;
  2868       return true;
  2869     } else {
  2870       return false;
  2873   HeapRegion* res() { return _res; }
  2874 };
  2876 class KnownGarbageClosure: public HeapRegionClosure {
  2877   CollectionSetChooser* _hrSorted;
  2879 public:
  2880   KnownGarbageClosure(CollectionSetChooser* hrSorted) :
  2881     _hrSorted(hrSorted)
  2882   {}
  2884   bool doHeapRegion(HeapRegion* r) {
  2885     // We only include humongous regions in collection
  2886     // sets when concurrent mark shows that their contained object is
  2887     // unreachable.
  2889     // Do we have any marking information for this region?
  2890     if (r->is_marked()) {
  2891       // We don't include humongous regions in collection
  2892       // sets because we collect them immediately at the end of a marking
  2893       // cycle.  We also don't include young regions because we *must*
  2894       // include them in the next collection pause.
  2895       if (!r->isHumongous() && !r->is_young()) {
  2896         _hrSorted->addMarkedHeapRegion(r);
  2899     return false;
  2901 };
  2903 class ParKnownGarbageHRClosure: public HeapRegionClosure {
  2904   CollectionSetChooser* _hrSorted;
  2905   jint _marked_regions_added;
  2906   jint _chunk_size;
  2907   jint _cur_chunk_idx;
  2908   jint _cur_chunk_end; // Cur chunk [_cur_chunk_idx, _cur_chunk_end)
  2909   int _worker;
  2910   int _invokes;
  2912   void get_new_chunk() {
  2913     _cur_chunk_idx = _hrSorted->getParMarkedHeapRegionChunk(_chunk_size);
  2914     _cur_chunk_end = _cur_chunk_idx + _chunk_size;
  2916   void add_region(HeapRegion* r) {
  2917     if (_cur_chunk_idx == _cur_chunk_end) {
  2918       get_new_chunk();
  2920     assert(_cur_chunk_idx < _cur_chunk_end, "postcondition");
  2921     _hrSorted->setMarkedHeapRegion(_cur_chunk_idx, r);
  2922     _marked_regions_added++;
  2923     _cur_chunk_idx++;
  2926 public:
  2927   ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
  2928                            jint chunk_size,
  2929                            int worker) :
  2930     _hrSorted(hrSorted), _chunk_size(chunk_size), _worker(worker),
  2931     _marked_regions_added(0), _cur_chunk_idx(0), _cur_chunk_end(0),
  2932     _invokes(0)
  2933   {}
  2935   bool doHeapRegion(HeapRegion* r) {
  2936     // We only include humongous regions in collection
  2937     // sets when concurrent mark shows that their contained object is
  2938     // unreachable.
  2939     _invokes++;
  2941     // Do we have any marking information for this region?
  2942     if (r->is_marked()) {
  2943       // We don't include humongous regions in collection
  2944       // sets because we collect them immediately at the end of a marking
  2945       // cycle.
  2946       // We also do not include young regions in collection sets
  2947       if (!r->isHumongous() && !r->is_young()) {
  2948         add_region(r);
  2951     return false;
  2953   jint marked_regions_added() { return _marked_regions_added; }
  2954   int invokes() { return _invokes; }
  2955 };
  2957 class ParKnownGarbageTask: public AbstractGangTask {
  2958   CollectionSetChooser* _hrSorted;
  2959   jint _chunk_size;
  2960   G1CollectedHeap* _g1;
  2961 public:
  2962   ParKnownGarbageTask(CollectionSetChooser* hrSorted, jint chunk_size) :
  2963     AbstractGangTask("ParKnownGarbageTask"),
  2964     _hrSorted(hrSorted), _chunk_size(chunk_size),
  2965     _g1(G1CollectedHeap::heap())
  2966   {}
  2968   void work(int i) {
  2969     ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size, i);
  2970     // Back to zero for the claim value.
  2971     _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, i,
  2972                                          HeapRegion::InitialClaimValue);
  2973     jint regions_added = parKnownGarbageCl.marked_regions_added();
  2974     _hrSorted->incNumMarkedHeapRegions(regions_added);
  2975     if (G1PrintParCleanupStats) {
  2976       gclog_or_tty->print("     Thread %d called %d times, added %d regions to list.\n",
  2977                  i, parKnownGarbageCl.invokes(), regions_added);
  2980 };
  2982 void
  2983 G1CollectorPolicy_BestRegionsFirst::
  2984 record_concurrent_mark_cleanup_end(size_t freed_bytes,
  2985                                    size_t max_live_bytes) {
  2986   double start;
  2987   if (G1PrintParCleanupStats) start = os::elapsedTime();
  2988   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
  2990   _collectionSetChooser->clearMarkedHeapRegions();
  2991   double clear_marked_end;
  2992   if (G1PrintParCleanupStats) {
  2993     clear_marked_end = os::elapsedTime();
  2994     gclog_or_tty->print_cr("  clear marked regions + work1: %8.3f ms.",
  2995                   (clear_marked_end - start)*1000.0);
  2997   if (ParallelGCThreads > 0) {
  2998     const size_t OverpartitionFactor = 4;
  2999     const size_t MinChunkSize = 8;
  3000     const size_t ChunkSize =
  3001       MAX2(_g1->n_regions() / (ParallelGCThreads * OverpartitionFactor),
  3002            MinChunkSize);
  3003     _collectionSetChooser->prepareForAddMarkedHeapRegionsPar(_g1->n_regions(),
  3004                                                              ChunkSize);
  3005     ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
  3006                                             (int) ChunkSize);
  3007     _g1->workers()->run_task(&parKnownGarbageTask);
  3009     assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
  3010            "sanity check");
  3011   } else {
  3012     KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
  3013     _g1->heap_region_iterate(&knownGarbagecl);
  3015   double known_garbage_end;
  3016   if (G1PrintParCleanupStats) {
  3017     known_garbage_end = os::elapsedTime();
  3018     gclog_or_tty->print_cr("  compute known garbage: %8.3f ms.",
  3019                   (known_garbage_end - clear_marked_end)*1000.0);
  3021   _collectionSetChooser->sortMarkedHeapRegions();
  3022   double sort_end;
  3023   if (G1PrintParCleanupStats) {
  3024     sort_end = os::elapsedTime();
  3025     gclog_or_tty->print_cr("  sorting: %8.3f ms.",
  3026                   (sort_end - known_garbage_end)*1000.0);
  3029   record_concurrent_mark_cleanup_end_work2();
  3030   double work2_end;
  3031   if (G1PrintParCleanupStats) {
  3032     work2_end = os::elapsedTime();
  3033     gclog_or_tty->print_cr("  work2: %8.3f ms.",
  3034                   (work2_end - sort_end)*1000.0);
  3038 // Add the heap region to the collection set and return the conservative
  3039 // estimate of the number of live bytes.
  3040 void G1CollectorPolicy::
  3041 add_to_collection_set(HeapRegion* hr) {
  3042   if (G1TraceRegions) {
  3043     gclog_or_tty->print_cr("added region to cset %d:["PTR_FORMAT", "PTR_FORMAT"], "
  3044                   "top "PTR_FORMAT", young %s",
  3045                   hr->hrs_index(), hr->bottom(), hr->end(),
  3046                   hr->top(), (hr->is_young()) ? "YES" : "NO");
  3049   if (_g1->mark_in_progress())
  3050     _g1->concurrent_mark()->registerCSetRegion(hr);
  3052   assert(!hr->in_collection_set(),
  3053               "should not already be in the CSet");
  3054   hr->set_in_collection_set(true);
  3055   hr->set_next_in_collection_set(_collection_set);
  3056   _collection_set = hr;
  3057   _collection_set_size++;
  3058   _collection_set_bytes_used_before += hr->used();
  3059   _g1->register_region_with_in_cset_fast_test(hr);
  3062 void
  3063 G1CollectorPolicy_BestRegionsFirst::
  3064 choose_collection_set(HeapRegion* pop_region) {
  3065   double non_young_start_time_sec;
  3066   start_recording_regions();
  3068   if (pop_region != NULL) {
  3069     _target_pause_time_ms = (double) G1MaxPauseTimeMS;
  3070   } else {
  3071     guarantee(_target_pause_time_ms > -1.0,
  3072               "_target_pause_time_ms should have been set!");
  3075   // pop region is either null (and so is CS), or else it *is* the CS.
  3076   assert(_collection_set == pop_region, "Precondition");
  3078   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
  3079   double predicted_pause_time_ms = base_time_ms;
  3081   double target_time_ms = _target_pause_time_ms;
  3082   double time_remaining_ms = target_time_ms - base_time_ms;
  3084   // the 10% and 50% values are arbitrary...
  3085   if (time_remaining_ms < 0.10*target_time_ms) {
  3086     time_remaining_ms = 0.50 * target_time_ms;
  3087     _within_target = false;
  3088   } else {
  3089     _within_target = true;
  3092   // We figure out the number of bytes available for future to-space.
  3093   // For new regions without marking information, we must assume the
  3094   // worst-case of complete survival.  If we have marking information for a
  3095   // region, we can bound the amount of live data.  We can add a number of
  3096   // such regions, as long as the sum of the live data bounds does not
  3097   // exceed the available evacuation space.
  3098   size_t max_live_bytes = _g1->free_regions() * HeapRegion::GrainBytes;
  3100   size_t expansion_bytes =
  3101     _g1->expansion_regions() * HeapRegion::GrainBytes;
  3103   if (pop_region == NULL) {
  3104     _collection_set_bytes_used_before = 0;
  3105     _collection_set_size = 0;
  3108   // Adjust for expansion and slop.
  3109   max_live_bytes = max_live_bytes + expansion_bytes;
  3111   assert(pop_region != NULL || _g1->regions_accounted_for(), "Region leakage!");
  3113   HeapRegion* hr;
  3114   if (in_young_gc_mode()) {
  3115     double young_start_time_sec = os::elapsedTime();
  3117     if (G1PolicyVerbose > 0) {
  3118       gclog_or_tty->print_cr("Adding %d young regions to the CSet",
  3119                     _g1->young_list_length());
  3121     _young_cset_length  = 0;
  3122     _last_young_gc_full = full_young_gcs() ? true : false;
  3123     if (_last_young_gc_full)
  3124       ++_full_young_pause_num;
  3125     else
  3126       ++_partial_young_pause_num;
  3127     hr = _g1->pop_region_from_young_list();
  3128     while (hr != NULL) {
  3130       assert( hr->young_index_in_cset() == -1, "invariant" );
  3131       assert( hr->age_in_surv_rate_group() != -1, "invariant" );
  3132       hr->set_young_index_in_cset((int) _young_cset_length);
  3134       ++_young_cset_length;
  3135       double predicted_time_ms = predict_region_elapsed_time_ms(hr, true);
  3136       time_remaining_ms -= predicted_time_ms;
  3137       predicted_pause_time_ms += predicted_time_ms;
  3138       if (hr == pop_region) {
  3139         // The popular region was young.  Skip over it.
  3140         assert(hr->in_collection_set(), "It's the pop region.");
  3141       } else {
  3142         assert(!hr->in_collection_set(), "It's not the pop region.");
  3143         add_to_collection_set(hr);
  3144         record_cset_region(hr, true);
  3146       max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  3147       if (G1PolicyVerbose > 0) {
  3148         gclog_or_tty->print_cr("  Added [" PTR_FORMAT ", " PTR_FORMAT") to CS.",
  3149                       hr->bottom(), hr->end());
  3150         gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  3151                       max_live_bytes/K);
  3153       hr = _g1->pop_region_from_young_list();
  3156     record_scan_only_regions(_g1->young_list_scan_only_length());
  3158     double young_end_time_sec = os::elapsedTime();
  3159     _recorded_young_cset_choice_time_ms =
  3160       (young_end_time_sec - young_start_time_sec) * 1000.0;
  3162     non_young_start_time_sec = os::elapsedTime();
  3164     if (_young_cset_length > 0 && _last_young_gc_full) {
  3165       // don't bother adding more regions...
  3166       goto choose_collection_set_end;
  3168   } else if (pop_region != NULL) {
  3169     // We're not in young mode, and we chose a popular region; don't choose
  3170     // any more.
  3171     return;
  3174   if (!in_young_gc_mode() || !full_young_gcs()) {
  3175     bool should_continue = true;
  3176     NumberSeq seq;
  3177     double avg_prediction = 100000000000000000.0; // something very large
  3178     do {
  3179       hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
  3180                                                       avg_prediction);
  3181       if (hr != NULL && !hr->popular()) {
  3182         double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
  3183         time_remaining_ms -= predicted_time_ms;
  3184         predicted_pause_time_ms += predicted_time_ms;
  3185         add_to_collection_set(hr);
  3186         record_cset_region(hr, false);
  3187         max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
  3188         if (G1PolicyVerbose > 0) {
  3189           gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
  3190                         max_live_bytes/K);
  3192         seq.add(predicted_time_ms);
  3193         avg_prediction = seq.avg() + seq.sd();
  3195       should_continue =
  3196         ( hr != NULL) &&
  3197         ( (adaptive_young_list_length()) ? time_remaining_ms > 0.0
  3198           : _collection_set_size < _young_list_fixed_length );
  3199     } while (should_continue);
  3201     if (!adaptive_young_list_length() &&
  3202         _collection_set_size < _young_list_fixed_length)
  3203       _should_revert_to_full_young_gcs  = true;
  3206 choose_collection_set_end:
  3207   count_CS_bytes_used();
  3209   end_recording_regions();
  3211   double non_young_end_time_sec = os::elapsedTime();
  3212   _recorded_non_young_cset_choice_time_ms =
  3213     (non_young_end_time_sec - non_young_start_time_sec) * 1000.0;
  3216 void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() {
  3217   G1CollectorPolicy::record_full_collection_end();
  3218   _collectionSetChooser->updateAfterFullCollection();
  3221 void G1CollectorPolicy_BestRegionsFirst::
  3222 expand_if_possible(size_t numRegions) {
  3223   size_t expansion_bytes = numRegions * HeapRegion::GrainBytes;
  3224   _g1->expand(expansion_bytes);
  3227 void G1CollectorPolicy_BestRegionsFirst::
  3228 record_collection_pause_end(bool popular, bool abandoned) {
  3229   G1CollectorPolicy::record_collection_pause_end(popular, abandoned);
  3230   assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
  3233 // Local Variables: ***
  3234 // c-indentation-style: gnu ***
  3235 // End: ***

mercurial