Mon, 09 Mar 2009 13:28:46 -0700
6814575: Update copyright year
Summary: Update copyright for files that have been modified in 2009, up to 03/09
Reviewed-by: katleman, tbell, ohair
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();
1004 }
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_sec);
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();
1048 }
1050 void G1CollectorPolicy::record_pop_compute_rc_start() {
1051 _pop_compute_rc_start = os::elapsedTime();
1052 }
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;
1057 }
1058 void G1CollectorPolicy::record_pop_evac_start() {
1059 _pop_evac_start = os::elapsedTime();
1060 }
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;
1065 }
1067 void G1CollectorPolicy::record_before_bytes(size_t bytes) {
1068 _bytes_in_to_space_before_gc += bytes;
1069 }
1071 void G1CollectorPolicy::record_after_bytes(size_t bytes) {
1072 _bytes_in_to_space_after_gc += bytes;
1073 }
1075 void G1CollectorPolicy::record_stop_world_start() {
1076 _stop_world_start = os::elapsedTime();
1077 }
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");
1086 }
1088 assert(_g1->used_regions() == _g1->recalculate_used_regions(),
1089 "sanity");
1091 double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
1092 _all_stop_world_times_ms->add(s_w_t_ms);
1093 _stop_world_start = 0.0;
1095 _cur_collection_start_sec = start_time_sec;
1096 _cur_collection_pause_used_at_start_bytes = start_used;
1097 _cur_collection_pause_used_regions_at_start = _g1->used_regions();
1098 _pending_cards = _g1->pending_card_num();
1099 _max_pending_cards = _g1->max_pending_card_num();
1101 _bytes_in_to_space_before_gc = 0;
1102 _bytes_in_to_space_after_gc = 0;
1103 _bytes_in_collection_set_before_gc = 0;
1105 #ifdef DEBUG
1106 // initialise these to something well known so that we can spot
1107 // if they are not set properly
1109 for (int i = 0; i < _parallel_gc_threads; ++i) {
1110 _par_last_ext_root_scan_times_ms[i] = -666.0;
1111 _par_last_mark_stack_scan_times_ms[i] = -666.0;
1112 _par_last_scan_only_times_ms[i] = -666.0;
1113 _par_last_scan_only_regions_scanned[i] = -666.0;
1114 _par_last_update_rs_start_times_ms[i] = -666.0;
1115 _par_last_update_rs_times_ms[i] = -666.0;
1116 _par_last_update_rs_processed_buffers[i] = -666.0;
1117 _par_last_scan_rs_start_times_ms[i] = -666.0;
1118 _par_last_scan_rs_times_ms[i] = -666.0;
1119 _par_last_scan_new_refs_times_ms[i] = -666.0;
1120 _par_last_obj_copy_times_ms[i] = -666.0;
1121 _par_last_termination_times_ms[i] = -666.0;
1123 _pop_par_last_update_rs_start_times_ms[i] = -666.0;
1124 _pop_par_last_update_rs_times_ms[i] = -666.0;
1125 _pop_par_last_update_rs_processed_buffers[i] = -666.0;
1126 _pop_par_last_scan_rs_start_times_ms[i] = -666.0;
1127 _pop_par_last_scan_rs_times_ms[i] = -666.0;
1128 _pop_par_last_closure_app_times_ms[i] = -666.0;
1129 }
1130 #endif
1132 for (int i = 0; i < _aux_num; ++i) {
1133 _cur_aux_times_ms[i] = 0.0;
1134 _cur_aux_times_set[i] = false;
1135 }
1137 _satb_drain_time_set = false;
1138 _last_satb_drain_processed_buffers = -1;
1140 if (in_young_gc_mode())
1141 _last_young_gc_full = false;
1144 // do that for any other surv rate groups
1145 _short_lived_surv_rate_group->stop_adding_regions();
1146 size_t short_lived_so_length = _young_list_so_prefix_length;
1147 _short_lived_surv_rate_group->record_scan_only_prefix(short_lived_so_length);
1148 tag_scan_only(short_lived_so_length);
1150 if (G1UseSurvivorSpace) {
1151 _survivors_age_table.clear();
1152 }
1154 assert( verify_young_ages(), "region age verification" );
1155 }
1157 void G1CollectorPolicy::tag_scan_only(size_t short_lived_scan_only_length) {
1158 // done in a way that it can be extended for other surv rate groups too...
1160 HeapRegion* head = _g1->young_list_first_region();
1161 bool finished_short_lived = (short_lived_scan_only_length == 0);
1163 if (finished_short_lived)
1164 return;
1166 for (HeapRegion* curr = head;
1167 curr != NULL;
1168 curr = curr->get_next_young_region()) {
1169 SurvRateGroup* surv_rate_group = curr->surv_rate_group();
1170 int age = curr->age_in_surv_rate_group();
1172 if (surv_rate_group == _short_lived_surv_rate_group) {
1173 if ((size_t)age < short_lived_scan_only_length)
1174 curr->set_scan_only();
1175 else
1176 finished_short_lived = true;
1177 }
1180 if (finished_short_lived)
1181 return;
1182 }
1184 guarantee( false, "we should never reach here" );
1185 }
1187 void G1CollectorPolicy::record_popular_pause_preamble_start() {
1188 _cur_popular_preamble_start_ms = os::elapsedTime() * 1000.0;
1189 }
1191 void G1CollectorPolicy::record_popular_pause_preamble_end() {
1192 _cur_popular_preamble_time_ms =
1193 (os::elapsedTime() * 1000.0) - _cur_popular_preamble_start_ms;
1195 // copy the recorded statistics of the first pass to temporary arrays
1196 for (int i = 0; i < _parallel_gc_threads; ++i) {
1197 _pop_par_last_update_rs_start_times_ms[i] = _par_last_update_rs_start_times_ms[i];
1198 _pop_par_last_update_rs_times_ms[i] = _par_last_update_rs_times_ms[i];
1199 _pop_par_last_update_rs_processed_buffers[i] = _par_last_update_rs_processed_buffers[i];
1200 _pop_par_last_scan_rs_start_times_ms[i] = _par_last_scan_rs_start_times_ms[i];
1201 _pop_par_last_scan_rs_times_ms[i] = _par_last_scan_rs_times_ms[i];
1202 _pop_par_last_closure_app_times_ms[i] = _par_last_obj_copy_times_ms[i];
1203 }
1204 }
1206 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
1207 _mark_closure_time_ms = mark_closure_time_ms;
1208 }
1210 void G1CollectorPolicy::record_concurrent_mark_init_start() {
1211 _mark_init_start_sec = os::elapsedTime();
1212 guarantee(!in_young_gc_mode(), "should not do be here in young GC mode");
1213 }
1215 void G1CollectorPolicy::record_concurrent_mark_init_end_pre(double
1216 mark_init_elapsed_time_ms) {
1217 _during_marking = true;
1218 _should_initiate_conc_mark = false;
1219 _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
1220 }
1222 void G1CollectorPolicy::record_concurrent_mark_init_end() {
1223 double end_time_sec = os::elapsedTime();
1224 double elapsed_time_ms = (end_time_sec - _mark_init_start_sec) * 1000.0;
1225 _concurrent_mark_init_times_ms->add(elapsed_time_ms);
1226 checkpoint_conc_overhead();
1227 record_concurrent_mark_init_end_pre(elapsed_time_ms);
1229 _mmu_tracker->add_pause(_mark_init_start_sec, end_time_sec, true);
1230 }
1232 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
1233 _mark_remark_start_sec = os::elapsedTime();
1234 _during_marking = false;
1235 }
1237 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
1238 double end_time_sec = os::elapsedTime();
1239 double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
1240 checkpoint_conc_overhead();
1241 _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
1242 _cur_mark_stop_world_time_ms += elapsed_time_ms;
1243 _prev_collection_pause_end_ms += elapsed_time_ms;
1245 _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
1246 }
1248 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
1249 _mark_cleanup_start_sec = os::elapsedTime();
1250 }
1252 void
1253 G1CollectorPolicy::record_concurrent_mark_cleanup_end(size_t freed_bytes,
1254 size_t max_live_bytes) {
1255 record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
1256 record_concurrent_mark_cleanup_end_work2();
1257 }
1259 void
1260 G1CollectorPolicy::
1261 record_concurrent_mark_cleanup_end_work1(size_t freed_bytes,
1262 size_t max_live_bytes) {
1263 if (_n_marks < 2) _n_marks++;
1264 if (G1PolicyVerbose > 0)
1265 gclog_or_tty->print_cr("At end of marking, max_live is " SIZE_FORMAT " MB "
1266 " (of " SIZE_FORMAT " MB heap).",
1267 max_live_bytes/M, _g1->capacity()/M);
1268 }
1270 // The important thing about this is that it includes "os::elapsedTime".
1271 void G1CollectorPolicy::record_concurrent_mark_cleanup_end_work2() {
1272 checkpoint_conc_overhead();
1273 double end_time_sec = os::elapsedTime();
1274 double elapsed_time_ms = (end_time_sec - _mark_cleanup_start_sec)*1000.0;
1275 _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
1276 _cur_mark_stop_world_time_ms += elapsed_time_ms;
1277 _prev_collection_pause_end_ms += elapsed_time_ms;
1279 _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_time_sec, true);
1281 _num_markings++;
1283 // We did a marking, so reset the "since_last_mark" variables.
1284 double considerConcMarkCost = 1.0;
1285 // If there are available processors, concurrent activity is free...
1286 if (Threads::number_of_non_daemon_threads() * 2 <
1287 os::active_processor_count()) {
1288 considerConcMarkCost = 0.0;
1289 }
1290 _n_pauses_at_mark_end = _n_pauses;
1291 _n_marks_since_last_pause++;
1292 _conc_mark_initiated = false;
1293 }
1295 void
1296 G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
1297 if (in_young_gc_mode()) {
1298 _should_revert_to_full_young_gcs = false;
1299 _last_full_young_gc = true;
1300 _in_marking_window = false;
1301 if (adaptive_young_list_length())
1302 calculate_young_list_target_config();
1303 }
1304 }
1306 void G1CollectorPolicy::record_concurrent_pause() {
1307 if (_stop_world_start > 0.0) {
1308 double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
1309 _all_yield_times_ms->add(yield_ms);
1310 }
1311 }
1313 void G1CollectorPolicy::record_concurrent_pause_end() {
1314 }
1316 void G1CollectorPolicy::record_collection_pause_end_CH_strong_roots() {
1317 _cur_CH_strong_roots_end_sec = os::elapsedTime();
1318 _cur_CH_strong_roots_dur_ms =
1319 (_cur_CH_strong_roots_end_sec - _cur_collection_start_sec) * 1000.0;
1320 }
1322 void G1CollectorPolicy::record_collection_pause_end_G1_strong_roots() {
1323 _cur_G1_strong_roots_end_sec = os::elapsedTime();
1324 _cur_G1_strong_roots_dur_ms =
1325 (_cur_G1_strong_roots_end_sec - _cur_CH_strong_roots_end_sec) * 1000.0;
1326 }
1328 template<class T>
1329 T sum_of(T* sum_arr, int start, int n, int N) {
1330 T sum = (T)0;
1331 for (int i = 0; i < n; i++) {
1332 int j = (start + i) % N;
1333 sum += sum_arr[j];
1334 }
1335 return sum;
1336 }
1338 void G1CollectorPolicy::print_par_stats (int level,
1339 const char* str,
1340 double* data,
1341 bool summary) {
1342 double min = data[0], max = data[0];
1343 double total = 0.0;
1344 int j;
1345 for (j = 0; j < level; ++j)
1346 gclog_or_tty->print(" ");
1347 gclog_or_tty->print("[%s (ms):", str);
1348 for (uint i = 0; i < ParallelGCThreads; ++i) {
1349 double val = data[i];
1350 if (val < min)
1351 min = val;
1352 if (val > max)
1353 max = val;
1354 total += val;
1355 gclog_or_tty->print(" %3.1lf", val);
1356 }
1357 if (summary) {
1358 gclog_or_tty->print_cr("");
1359 double avg = total / (double) ParallelGCThreads;
1360 gclog_or_tty->print(" ");
1361 for (j = 0; j < level; ++j)
1362 gclog_or_tty->print(" ");
1363 gclog_or_tty->print("Avg: %5.1lf, Min: %5.1lf, Max: %5.1lf",
1364 avg, min, max);
1365 }
1366 gclog_or_tty->print_cr("]");
1367 }
1369 void G1CollectorPolicy::print_par_buffers (int level,
1370 const char* str,
1371 double* data,
1372 bool summary) {
1373 double min = data[0], max = data[0];
1374 double total = 0.0;
1375 int j;
1376 for (j = 0; j < level; ++j)
1377 gclog_or_tty->print(" ");
1378 gclog_or_tty->print("[%s :", str);
1379 for (uint i = 0; i < ParallelGCThreads; ++i) {
1380 double val = data[i];
1381 if (val < min)
1382 min = val;
1383 if (val > max)
1384 max = val;
1385 total += val;
1386 gclog_or_tty->print(" %d", (int) val);
1387 }
1388 if (summary) {
1389 gclog_or_tty->print_cr("");
1390 double avg = total / (double) ParallelGCThreads;
1391 gclog_or_tty->print(" ");
1392 for (j = 0; j < level; ++j)
1393 gclog_or_tty->print(" ");
1394 gclog_or_tty->print("Sum: %d, Avg: %d, Min: %d, Max: %d",
1395 (int)total, (int)avg, (int)min, (int)max);
1396 }
1397 gclog_or_tty->print_cr("]");
1398 }
1400 void G1CollectorPolicy::print_stats (int level,
1401 const char* str,
1402 double value) {
1403 for (int j = 0; j < level; ++j)
1404 gclog_or_tty->print(" ");
1405 gclog_or_tty->print_cr("[%s: %5.1lf ms]", str, value);
1406 }
1408 void G1CollectorPolicy::print_stats (int level,
1409 const char* str,
1410 int value) {
1411 for (int j = 0; j < level; ++j)
1412 gclog_or_tty->print(" ");
1413 gclog_or_tty->print_cr("[%s: %d]", str, value);
1414 }
1416 double G1CollectorPolicy::avg_value (double* data) {
1417 if (ParallelGCThreads > 0) {
1418 double ret = 0.0;
1419 for (uint i = 0; i < ParallelGCThreads; ++i)
1420 ret += data[i];
1421 return ret / (double) ParallelGCThreads;
1422 } else {
1423 return data[0];
1424 }
1425 }
1427 double G1CollectorPolicy::max_value (double* data) {
1428 if (ParallelGCThreads > 0) {
1429 double ret = data[0];
1430 for (uint i = 1; i < ParallelGCThreads; ++i)
1431 if (data[i] > ret)
1432 ret = data[i];
1433 return ret;
1434 } else {
1435 return data[0];
1436 }
1437 }
1439 double G1CollectorPolicy::sum_of_values (double* data) {
1440 if (ParallelGCThreads > 0) {
1441 double sum = 0.0;
1442 for (uint i = 0; i < ParallelGCThreads; i++)
1443 sum += data[i];
1444 return sum;
1445 } else {
1446 return data[0];
1447 }
1448 }
1450 double G1CollectorPolicy::max_sum (double* data1,
1451 double* data2) {
1452 double ret = data1[0] + data2[0];
1454 if (ParallelGCThreads > 0) {
1455 for (uint i = 1; i < ParallelGCThreads; ++i) {
1456 double data = data1[i] + data2[i];
1457 if (data > ret)
1458 ret = data;
1459 }
1460 }
1461 return ret;
1462 }
1464 // Anything below that is considered to be zero
1465 #define MIN_TIMER_GRANULARITY 0.0000001
1467 void G1CollectorPolicy::record_collection_pause_end(bool popular,
1468 bool abandoned) {
1469 double end_time_sec = os::elapsedTime();
1470 double elapsed_ms = _last_pause_time_ms;
1471 bool parallel = ParallelGCThreads > 0;
1472 double evac_ms = (end_time_sec - _cur_G1_strong_roots_end_sec) * 1000.0;
1473 size_t rs_size =
1474 _cur_collection_pause_used_regions_at_start - collection_set_size();
1475 size_t cur_used_bytes = _g1->used();
1476 assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
1477 bool last_pause_included_initial_mark = false;
1479 #ifndef PRODUCT
1480 if (G1YoungSurvRateVerbose) {
1481 gclog_or_tty->print_cr("");
1482 _short_lived_surv_rate_group->print();
1483 // do that for any other surv rate groups too
1484 }
1485 #endif // PRODUCT
1487 checkpoint_conc_overhead();
1489 if (in_young_gc_mode()) {
1490 last_pause_included_initial_mark = _should_initiate_conc_mark;
1491 if (last_pause_included_initial_mark)
1492 record_concurrent_mark_init_end_pre(0.0);
1494 size_t min_used_targ =
1495 (_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta);
1497 if (cur_used_bytes > min_used_targ) {
1498 if (cur_used_bytes <= _prev_collection_pause_used_at_end_bytes) {
1499 } else if (!_g1->mark_in_progress() && !_last_full_young_gc) {
1500 _should_initiate_conc_mark = true;
1501 }
1502 }
1504 _prev_collection_pause_used_at_end_bytes = cur_used_bytes;
1505 }
1507 _mmu_tracker->add_pause(end_time_sec - elapsed_ms/1000.0,
1508 end_time_sec, false);
1510 guarantee(_cur_collection_pause_used_regions_at_start >=
1511 collection_set_size(),
1512 "Negative RS size?");
1514 // This assert is exempted when we're doing parallel collection pauses,
1515 // because the fragmentation caused by the parallel GC allocation buffers
1516 // can lead to more memory being used during collection than was used
1517 // before. Best leave this out until the fragmentation problem is fixed.
1518 // Pauses in which evacuation failed can also lead to negative
1519 // collections, since no space is reclaimed from a region containing an
1520 // object whose evacuation failed.
1521 // Further, we're now always doing parallel collection. But I'm still
1522 // leaving this here as a placeholder for a more precise assertion later.
1523 // (DLD, 10/05.)
1524 assert((true || parallel) // Always using GC LABs now.
1525 || _g1->evacuation_failed()
1526 || _cur_collection_pause_used_at_start_bytes >= cur_used_bytes,
1527 "Negative collection");
1529 size_t freed_bytes =
1530 _cur_collection_pause_used_at_start_bytes - cur_used_bytes;
1531 size_t surviving_bytes = _collection_set_bytes_used_before - freed_bytes;
1532 double survival_fraction =
1533 (double)surviving_bytes/
1534 (double)_collection_set_bytes_used_before;
1536 _n_pauses++;
1538 if (!abandoned) {
1539 _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
1540 _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
1541 _recent_evac_times_ms->add(evac_ms);
1542 _recent_pause_times_ms->add(elapsed_ms);
1544 _recent_rs_sizes->add(rs_size);
1546 // We exempt parallel collection from this check because Alloc Buffer
1547 // fragmentation can produce negative collections. Same with evac
1548 // failure.
1549 // Further, we're now always doing parallel collection. But I'm still
1550 // leaving this here as a placeholder for a more precise assertion later.
1551 // (DLD, 10/05.
1552 assert((true || parallel)
1553 || _g1->evacuation_failed()
1554 || surviving_bytes <= _collection_set_bytes_used_before,
1555 "Or else negative collection!");
1556 _recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
1557 _recent_CS_bytes_surviving->add(surviving_bytes);
1559 // this is where we update the allocation rate of the application
1560 double app_time_ms =
1561 (_cur_collection_start_sec * 1000.0 - _prev_collection_pause_end_ms);
1562 if (app_time_ms < MIN_TIMER_GRANULARITY) {
1563 // This usually happens due to the timer not having the required
1564 // granularity. Some Linuxes are the usual culprits.
1565 // We'll just set it to something (arbitrarily) small.
1566 app_time_ms = 1.0;
1567 }
1568 size_t regions_allocated =
1569 (_region_num_young - _prev_region_num_young) +
1570 (_region_num_tenured - _prev_region_num_tenured);
1571 double alloc_rate_ms = (double) regions_allocated / app_time_ms;
1572 _alloc_rate_ms_seq->add(alloc_rate_ms);
1573 _prev_region_num_young = _region_num_young;
1574 _prev_region_num_tenured = _region_num_tenured;
1576 double interval_ms =
1577 (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
1578 update_recent_gc_times(end_time_sec, elapsed_ms);
1579 _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
1580 assert(recent_avg_pause_time_ratio() < 1.00, "All GC?");
1581 }
1583 if (G1PolicyVerbose > 1) {
1584 gclog_or_tty->print_cr(" Recording collection pause(%d)", _n_pauses);
1585 }
1587 PauseSummary* summary;
1588 if (!abandoned && !popular)
1589 summary = _non_pop_summary;
1590 else if (!abandoned && popular)
1591 summary = _pop_summary;
1592 else if (abandoned && !popular)
1593 summary = _non_pop_abandoned_summary;
1594 else if (abandoned && popular)
1595 summary = _pop_abandoned_summary;
1596 else
1597 guarantee(false, "should not get here!");
1599 double pop_update_rs_time;
1600 double pop_update_rs_processed_buffers;
1601 double pop_scan_rs_time;
1602 double pop_closure_app_time;
1603 double pop_other_time;
1605 if (popular) {
1606 PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
1607 guarantee(preamble_summary != NULL, "should not be null!");
1609 pop_update_rs_time = avg_value(_pop_par_last_update_rs_times_ms);
1610 pop_update_rs_processed_buffers =
1611 sum_of_values(_pop_par_last_update_rs_processed_buffers);
1612 pop_scan_rs_time = avg_value(_pop_par_last_scan_rs_times_ms);
1613 pop_closure_app_time = avg_value(_pop_par_last_closure_app_times_ms);
1614 pop_other_time = _cur_popular_preamble_time_ms -
1615 (pop_update_rs_time + pop_scan_rs_time + pop_closure_app_time +
1616 _cur_popular_evac_time_ms);
1618 preamble_summary->record_pop_preamble_time_ms(_cur_popular_preamble_time_ms);
1619 preamble_summary->record_pop_update_rs_time_ms(pop_update_rs_time);
1620 preamble_summary->record_pop_scan_rs_time_ms(pop_scan_rs_time);
1621 preamble_summary->record_pop_closure_app_time_ms(pop_closure_app_time);
1622 preamble_summary->record_pop_evacuation_time_ms(_cur_popular_evac_time_ms);
1623 preamble_summary->record_pop_other_time_ms(pop_other_time);
1624 }
1626 double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
1627 double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
1628 double scan_only_time = avg_value(_par_last_scan_only_times_ms);
1629 double scan_only_regions_scanned =
1630 sum_of_values(_par_last_scan_only_regions_scanned);
1631 double update_rs_time = avg_value(_par_last_update_rs_times_ms);
1632 double update_rs_processed_buffers =
1633 sum_of_values(_par_last_update_rs_processed_buffers);
1634 double scan_rs_time = avg_value(_par_last_scan_rs_times_ms);
1635 double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
1636 double termination_time = avg_value(_par_last_termination_times_ms);
1638 double parallel_other_time;
1639 if (!abandoned) {
1640 MainBodySummary* body_summary = summary->main_body_summary();
1641 guarantee(body_summary != NULL, "should not be null!");
1643 if (_satb_drain_time_set)
1644 body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
1645 else
1646 body_summary->record_satb_drain_time_ms(0.0);
1647 body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
1648 body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
1649 body_summary->record_scan_only_time_ms(scan_only_time);
1650 body_summary->record_update_rs_time_ms(update_rs_time);
1651 body_summary->record_scan_rs_time_ms(scan_rs_time);
1652 body_summary->record_obj_copy_time_ms(obj_copy_time);
1653 if (parallel) {
1654 body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
1655 body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
1656 body_summary->record_termination_time_ms(termination_time);
1657 parallel_other_time = _cur_collection_par_time_ms -
1658 (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
1659 scan_only_time + scan_rs_time + obj_copy_time + termination_time);
1660 body_summary->record_parallel_other_time_ms(parallel_other_time);
1661 }
1662 body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
1663 }
1665 if (G1PolicyVerbose > 1) {
1666 gclog_or_tty->print_cr(" ET: %10.6f ms (avg: %10.6f ms)\n"
1667 " CH Strong: %10.6f ms (avg: %10.6f ms)\n"
1668 " G1 Strong: %10.6f ms (avg: %10.6f ms)\n"
1669 " Evac: %10.6f ms (avg: %10.6f ms)\n"
1670 " ET-RS: %10.6f ms (avg: %10.6f ms)\n"
1671 " |RS|: " SIZE_FORMAT,
1672 elapsed_ms, recent_avg_time_for_pauses_ms(),
1673 _cur_CH_strong_roots_dur_ms, recent_avg_time_for_CH_strong_ms(),
1674 _cur_G1_strong_roots_dur_ms, recent_avg_time_for_G1_strong_ms(),
1675 evac_ms, recent_avg_time_for_evac_ms(),
1676 scan_rs_time,
1677 recent_avg_time_for_pauses_ms() -
1678 recent_avg_time_for_G1_strong_ms(),
1679 rs_size);
1681 gclog_or_tty->print_cr(" Used at start: " SIZE_FORMAT"K"
1682 " At end " SIZE_FORMAT "K\n"
1683 " garbage : " SIZE_FORMAT "K"
1684 " of " SIZE_FORMAT "K\n"
1685 " survival : %6.2f%% (%6.2f%% avg)",
1686 _cur_collection_pause_used_at_start_bytes/K,
1687 _g1->used()/K, freed_bytes/K,
1688 _collection_set_bytes_used_before/K,
1689 survival_fraction*100.0,
1690 recent_avg_survival_fraction()*100.0);
1691 gclog_or_tty->print_cr(" Recent %% gc pause time: %6.2f",
1692 recent_avg_pause_time_ratio() * 100.0);
1693 }
1695 double other_time_ms = elapsed_ms;
1696 if (popular)
1697 other_time_ms -= _cur_popular_preamble_time_ms;
1699 if (!abandoned) {
1700 if (_satb_drain_time_set)
1701 other_time_ms -= _cur_satb_drain_time_ms;
1703 if (parallel)
1704 other_time_ms -= _cur_collection_par_time_ms + _cur_clear_ct_time_ms;
1705 else
1706 other_time_ms -=
1707 update_rs_time +
1708 ext_root_scan_time + mark_stack_scan_time + scan_only_time +
1709 scan_rs_time + obj_copy_time;
1710 }
1712 if (PrintGCDetails) {
1713 gclog_or_tty->print_cr("%s%s, %1.8lf secs]",
1714 (popular && !abandoned) ? " (popular)" :
1715 (!popular && abandoned) ? " (abandoned)" :
1716 (popular && abandoned) ? " (popular/abandoned)" : "",
1717 (last_pause_included_initial_mark) ? " (initial-mark)" : "",
1718 elapsed_ms / 1000.0);
1720 if (!abandoned) {
1721 if (_satb_drain_time_set)
1722 print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
1723 if (_last_satb_drain_processed_buffers >= 0)
1724 print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
1725 }
1726 if (popular)
1727 print_stats(1, "Popularity Preamble", _cur_popular_preamble_time_ms);
1728 if (parallel) {
1729 if (popular) {
1730 print_par_stats(2, "Update RS (Start)", _pop_par_last_update_rs_start_times_ms, false);
1731 print_par_stats(2, "Update RS", _pop_par_last_update_rs_times_ms);
1732 if (G1RSBarrierUseQueue)
1733 print_par_buffers(3, "Processed Buffers",
1734 _pop_par_last_update_rs_processed_buffers, true);
1735 print_par_stats(2, "Scan RS", _pop_par_last_scan_rs_times_ms);
1736 print_par_stats(2, "Closure app", _pop_par_last_closure_app_times_ms);
1737 print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
1738 print_stats(2, "Other", pop_other_time);
1739 }
1740 if (!abandoned) {
1741 print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
1742 if (!popular) {
1743 print_par_stats(2, "Update RS (Start)", _par_last_update_rs_start_times_ms, false);
1744 print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
1745 if (G1RSBarrierUseQueue)
1746 print_par_buffers(3, "Processed Buffers",
1747 _par_last_update_rs_processed_buffers, true);
1748 }
1749 print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
1750 print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
1751 print_par_stats(2, "Scan-Only Scanning", _par_last_scan_only_times_ms);
1752 print_par_buffers(3, "Scan-Only Regions",
1753 _par_last_scan_only_regions_scanned, true);
1754 print_par_stats(2, "Scan RS", _par_last_scan_rs_times_ms);
1755 print_par_stats(2, "Object Copy", _par_last_obj_copy_times_ms);
1756 print_par_stats(2, "Termination", _par_last_termination_times_ms);
1757 print_stats(2, "Other", parallel_other_time);
1758 print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
1759 }
1760 } else {
1761 if (popular) {
1762 print_stats(2, "Update RS", pop_update_rs_time);
1763 if (G1RSBarrierUseQueue)
1764 print_stats(3, "Processed Buffers",
1765 (int)pop_update_rs_processed_buffers);
1766 print_stats(2, "Scan RS", pop_scan_rs_time);
1767 print_stats(2, "Closure App", pop_closure_app_time);
1768 print_stats(2, "Evacuation", _cur_popular_evac_time_ms);
1769 print_stats(2, "Other", pop_other_time);
1770 }
1771 if (!abandoned) {
1772 if (!popular) {
1773 print_stats(1, "Update RS", update_rs_time);
1774 if (G1RSBarrierUseQueue)
1775 print_stats(2, "Processed Buffers",
1776 (int)update_rs_processed_buffers);
1777 }
1778 print_stats(1, "Ext Root Scanning", ext_root_scan_time);
1779 print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
1780 print_stats(1, "Scan-Only Scanning", scan_only_time);
1781 print_stats(1, "Scan RS", scan_rs_time);
1782 print_stats(1, "Object Copying", obj_copy_time);
1783 }
1784 }
1785 print_stats(1, "Other", other_time_ms);
1786 for (int i = 0; i < _aux_num; ++i) {
1787 if (_cur_aux_times_set[i]) {
1788 char buffer[96];
1789 sprintf(buffer, "Aux%d", i);
1790 print_stats(1, buffer, _cur_aux_times_ms[i]);
1791 }
1792 }
1793 }
1794 if (PrintGCDetails)
1795 gclog_or_tty->print(" [");
1796 if (PrintGC || PrintGCDetails)
1797 _g1->print_size_transition(gclog_or_tty,
1798 _cur_collection_pause_used_at_start_bytes,
1799 _g1->used(), _g1->capacity());
1800 if (PrintGCDetails)
1801 gclog_or_tty->print_cr("]");
1803 _all_pause_times_ms->add(elapsed_ms);
1804 summary->record_total_time_ms(elapsed_ms);
1805 summary->record_other_time_ms(other_time_ms);
1806 for (int i = 0; i < _aux_num; ++i)
1807 if (_cur_aux_times_set[i])
1808 _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
1810 // Reset marks-between-pauses counter.
1811 _n_marks_since_last_pause = 0;
1813 // Update the efficiency-since-mark vars.
1814 double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
1815 if (elapsed_ms < MIN_TIMER_GRANULARITY) {
1816 // This usually happens due to the timer not having the required
1817 // granularity. Some Linuxes are the usual culprits.
1818 // We'll just set it to something (arbitrarily) small.
1819 proc_ms = 1.0;
1820 }
1821 double cur_efficiency = (double) freed_bytes / proc_ms;
1823 bool new_in_marking_window = _in_marking_window;
1824 bool new_in_marking_window_im = false;
1825 if (_should_initiate_conc_mark) {
1826 new_in_marking_window = true;
1827 new_in_marking_window_im = true;
1828 }
1830 if (in_young_gc_mode()) {
1831 if (_last_full_young_gc) {
1832 set_full_young_gcs(false);
1833 _last_full_young_gc = false;
1834 }
1836 if ( !_last_young_gc_full ) {
1837 if ( _should_revert_to_full_young_gcs ||
1838 _known_garbage_ratio < 0.05 ||
1839 (adaptive_young_list_length() &&
1840 (get_gc_eff_factor() * cur_efficiency < predict_young_gc_eff())) ) {
1841 set_full_young_gcs(true);
1842 }
1843 }
1844 _should_revert_to_full_young_gcs = false;
1846 if (_last_young_gc_full && !_during_marking)
1847 _young_gc_eff_seq->add(cur_efficiency);
1848 }
1850 _short_lived_surv_rate_group->start_adding_regions();
1851 // do that for any other surv rate groupsx
1853 // <NEW PREDICTION>
1855 if (!popular && !abandoned) {
1856 double pause_time_ms = elapsed_ms;
1858 size_t diff = 0;
1859 if (_max_pending_cards >= _pending_cards)
1860 diff = _max_pending_cards - _pending_cards;
1861 _pending_card_diff_seq->add((double) diff);
1863 double cost_per_card_ms = 0.0;
1864 if (_pending_cards > 0) {
1865 cost_per_card_ms = update_rs_time / (double) _pending_cards;
1866 _cost_per_card_ms_seq->add(cost_per_card_ms);
1867 }
1869 double cost_per_scan_only_region_ms = 0.0;
1870 if (scan_only_regions_scanned > 0.0) {
1871 cost_per_scan_only_region_ms =
1872 scan_only_time / scan_only_regions_scanned;
1873 if (_in_marking_window_im)
1874 _cost_per_scan_only_region_ms_during_cm_seq->add(cost_per_scan_only_region_ms);
1875 else
1876 _cost_per_scan_only_region_ms_seq->add(cost_per_scan_only_region_ms);
1877 }
1879 size_t cards_scanned = _g1->cards_scanned();
1881 double cost_per_entry_ms = 0.0;
1882 if (cards_scanned > 10) {
1883 cost_per_entry_ms = scan_rs_time / (double) cards_scanned;
1884 if (_last_young_gc_full)
1885 _cost_per_entry_ms_seq->add(cost_per_entry_ms);
1886 else
1887 _partially_young_cost_per_entry_ms_seq->add(cost_per_entry_ms);
1888 }
1890 if (_max_rs_lengths > 0) {
1891 double cards_per_entry_ratio =
1892 (double) cards_scanned / (double) _max_rs_lengths;
1893 if (_last_young_gc_full)
1894 _fully_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1895 else
1896 _partially_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1897 }
1899 size_t rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
1900 if (rs_length_diff >= 0)
1901 _rs_length_diff_seq->add((double) rs_length_diff);
1903 size_t copied_bytes = surviving_bytes;
1904 double cost_per_byte_ms = 0.0;
1905 if (copied_bytes > 0) {
1906 cost_per_byte_ms = obj_copy_time / (double) copied_bytes;
1907 if (_in_marking_window)
1908 _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
1909 else
1910 _cost_per_byte_ms_seq->add(cost_per_byte_ms);
1911 }
1913 double all_other_time_ms = pause_time_ms -
1914 (update_rs_time + scan_only_time + scan_rs_time + obj_copy_time +
1915 _mark_closure_time_ms + termination_time);
1917 double young_other_time_ms = 0.0;
1918 if (_recorded_young_regions > 0) {
1919 young_other_time_ms =
1920 _recorded_young_cset_choice_time_ms +
1921 _recorded_young_free_cset_time_ms;
1922 _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
1923 (double) _recorded_young_regions);
1924 }
1925 double non_young_other_time_ms = 0.0;
1926 if (_recorded_non_young_regions > 0) {
1927 non_young_other_time_ms =
1928 _recorded_non_young_cset_choice_time_ms +
1929 _recorded_non_young_free_cset_time_ms;
1931 _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
1932 (double) _recorded_non_young_regions);
1933 }
1935 double constant_other_time_ms = all_other_time_ms -
1936 (young_other_time_ms + non_young_other_time_ms);
1937 _constant_other_time_ms_seq->add(constant_other_time_ms);
1939 double survival_ratio = 0.0;
1940 if (_bytes_in_collection_set_before_gc > 0) {
1941 survival_ratio = (double) bytes_in_to_space_during_gc() /
1942 (double) _bytes_in_collection_set_before_gc;
1943 }
1945 _pending_cards_seq->add((double) _pending_cards);
1946 _scanned_cards_seq->add((double) cards_scanned);
1947 _rs_lengths_seq->add((double) _max_rs_lengths);
1949 double expensive_region_limit_ms =
1950 (double) G1MaxPauseTimeMS - predict_constant_other_time_ms();
1951 if (expensive_region_limit_ms < 0.0) {
1952 // this means that the other time was predicted to be longer than
1953 // than the max pause time
1954 expensive_region_limit_ms = (double) G1MaxPauseTimeMS;
1955 }
1956 _expensive_region_limit_ms = expensive_region_limit_ms;
1958 if (PREDICTIONS_VERBOSE) {
1959 gclog_or_tty->print_cr("");
1960 gclog_or_tty->print_cr("PREDICTIONS %1.4lf %d "
1961 "REGIONS %d %d %d %d "
1962 "PENDING_CARDS %d %d "
1963 "CARDS_SCANNED %d %d "
1964 "RS_LENGTHS %d %d "
1965 "SCAN_ONLY_SCAN %1.6lf %1.6lf "
1966 "RS_UPDATE %1.6lf %1.6lf RS_SCAN %1.6lf %1.6lf "
1967 "SURVIVAL_RATIO %1.6lf %1.6lf "
1968 "OBJECT_COPY %1.6lf %1.6lf OTHER_CONSTANT %1.6lf %1.6lf "
1969 "OTHER_YOUNG %1.6lf %1.6lf "
1970 "OTHER_NON_YOUNG %1.6lf %1.6lf "
1971 "VTIME_DIFF %1.6lf TERMINATION %1.6lf "
1972 "ELAPSED %1.6lf %1.6lf ",
1973 _cur_collection_start_sec,
1974 (!_last_young_gc_full) ? 2 :
1975 (last_pause_included_initial_mark) ? 1 : 0,
1976 _recorded_region_num,
1977 _recorded_young_regions,
1978 _recorded_scan_only_regions,
1979 _recorded_non_young_regions,
1980 _predicted_pending_cards, _pending_cards,
1981 _predicted_cards_scanned, cards_scanned,
1982 _predicted_rs_lengths, _max_rs_lengths,
1983 _predicted_scan_only_scan_time_ms, scan_only_time,
1984 _predicted_rs_update_time_ms, update_rs_time,
1985 _predicted_rs_scan_time_ms, scan_rs_time,
1986 _predicted_survival_ratio, survival_ratio,
1987 _predicted_object_copy_time_ms, obj_copy_time,
1988 _predicted_constant_other_time_ms, constant_other_time_ms,
1989 _predicted_young_other_time_ms, young_other_time_ms,
1990 _predicted_non_young_other_time_ms,
1991 non_young_other_time_ms,
1992 _vtime_diff_ms, termination_time,
1993 _predicted_pause_time_ms, elapsed_ms);
1994 }
1996 if (G1PolicyVerbose > 0) {
1997 gclog_or_tty->print_cr("Pause Time, predicted: %1.4lfms (predicted %s), actual: %1.4lfms",
1998 _predicted_pause_time_ms,
1999 (_within_target) ? "within" : "outside",
2000 elapsed_ms);
2001 }
2003 }
2005 _in_marking_window = new_in_marking_window;
2006 _in_marking_window_im = new_in_marking_window_im;
2007 _free_regions_at_end_of_collection = _g1->free_regions();
2008 _scan_only_regions_at_end_of_collection = _g1->young_list_length();
2009 calculate_young_list_min_length();
2010 calculate_young_list_target_config();
2012 // </NEW PREDICTION>
2014 _target_pause_time_ms = -1.0;
2015 }
2017 // <NEW PREDICTION>
2019 double
2020 G1CollectorPolicy::
2021 predict_young_collection_elapsed_time_ms(size_t adjustment) {
2022 guarantee( adjustment == 0 || adjustment == 1, "invariant" );
2024 G1CollectedHeap* g1h = G1CollectedHeap::heap();
2025 size_t young_num = g1h->young_list_length();
2026 if (young_num == 0)
2027 return 0.0;
2029 young_num += adjustment;
2030 size_t pending_cards = predict_pending_cards();
2031 size_t rs_lengths = g1h->young_list_sampled_rs_lengths() +
2032 predict_rs_length_diff();
2033 size_t card_num;
2034 if (full_young_gcs())
2035 card_num = predict_young_card_num(rs_lengths);
2036 else
2037 card_num = predict_non_young_card_num(rs_lengths);
2038 size_t young_byte_size = young_num * HeapRegion::GrainBytes;
2039 double accum_yg_surv_rate =
2040 _short_lived_surv_rate_group->accum_surv_rate(adjustment);
2042 size_t bytes_to_copy =
2043 (size_t) (accum_yg_surv_rate * (double) HeapRegion::GrainBytes);
2045 return
2046 predict_rs_update_time_ms(pending_cards) +
2047 predict_rs_scan_time_ms(card_num) +
2048 predict_object_copy_time_ms(bytes_to_copy) +
2049 predict_young_other_time_ms(young_num) +
2050 predict_constant_other_time_ms();
2051 }
2053 double
2054 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
2055 size_t rs_length = predict_rs_length_diff();
2056 size_t card_num;
2057 if (full_young_gcs())
2058 card_num = predict_young_card_num(rs_length);
2059 else
2060 card_num = predict_non_young_card_num(rs_length);
2061 return predict_base_elapsed_time_ms(pending_cards, card_num);
2062 }
2064 double
2065 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
2066 size_t scanned_cards) {
2067 return
2068 predict_rs_update_time_ms(pending_cards) +
2069 predict_rs_scan_time_ms(scanned_cards) +
2070 predict_constant_other_time_ms();
2071 }
2073 double
2074 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
2075 bool young) {
2076 size_t rs_length = hr->rem_set()->occupied();
2077 size_t card_num;
2078 if (full_young_gcs())
2079 card_num = predict_young_card_num(rs_length);
2080 else
2081 card_num = predict_non_young_card_num(rs_length);
2082 size_t bytes_to_copy = predict_bytes_to_copy(hr);
2084 double region_elapsed_time_ms =
2085 predict_rs_scan_time_ms(card_num) +
2086 predict_object_copy_time_ms(bytes_to_copy);
2088 if (young)
2089 region_elapsed_time_ms += predict_young_other_time_ms(1);
2090 else
2091 region_elapsed_time_ms += predict_non_young_other_time_ms(1);
2093 return region_elapsed_time_ms;
2094 }
2096 size_t
2097 G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
2098 size_t bytes_to_copy;
2099 if (hr->is_marked())
2100 bytes_to_copy = hr->max_live_bytes();
2101 else {
2102 guarantee( hr->is_young() && hr->age_in_surv_rate_group() != -1,
2103 "invariant" );
2104 int age = hr->age_in_surv_rate_group();
2105 double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
2106 bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
2107 }
2109 return bytes_to_copy;
2110 }
2112 void
2113 G1CollectorPolicy::start_recording_regions() {
2114 _recorded_rs_lengths = 0;
2115 _recorded_scan_only_regions = 0;
2116 _recorded_young_regions = 0;
2117 _recorded_non_young_regions = 0;
2119 #if PREDICTIONS_VERBOSE
2120 _predicted_rs_lengths = 0;
2121 _predicted_cards_scanned = 0;
2123 _recorded_marked_bytes = 0;
2124 _recorded_young_bytes = 0;
2125 _predicted_bytes_to_copy = 0;
2126 #endif // PREDICTIONS_VERBOSE
2127 }
2129 void
2130 G1CollectorPolicy::record_cset_region(HeapRegion* hr, bool young) {
2131 if (young) {
2132 ++_recorded_young_regions;
2133 } else {
2134 ++_recorded_non_young_regions;
2135 }
2136 #if PREDICTIONS_VERBOSE
2137 if (young) {
2138 _recorded_young_bytes += hr->used();
2139 } else {
2140 _recorded_marked_bytes += hr->max_live_bytes();
2141 }
2142 _predicted_bytes_to_copy += predict_bytes_to_copy(hr);
2143 #endif // PREDICTIONS_VERBOSE
2145 size_t rs_length = hr->rem_set()->occupied();
2146 _recorded_rs_lengths += rs_length;
2147 }
2149 void
2150 G1CollectorPolicy::record_scan_only_regions(size_t scan_only_length) {
2151 _recorded_scan_only_regions = scan_only_length;
2152 }
2154 void
2155 G1CollectorPolicy::end_recording_regions() {
2156 #if PREDICTIONS_VERBOSE
2157 _predicted_pending_cards = predict_pending_cards();
2158 _predicted_rs_lengths = _recorded_rs_lengths + predict_rs_length_diff();
2159 if (full_young_gcs())
2160 _predicted_cards_scanned += predict_young_card_num(_predicted_rs_lengths);
2161 else
2162 _predicted_cards_scanned +=
2163 predict_non_young_card_num(_predicted_rs_lengths);
2164 _recorded_region_num = _recorded_young_regions + _recorded_non_young_regions;
2166 _predicted_scan_only_scan_time_ms =
2167 predict_scan_only_time_ms(_recorded_scan_only_regions);
2168 _predicted_rs_update_time_ms =
2169 predict_rs_update_time_ms(_g1->pending_card_num());
2170 _predicted_rs_scan_time_ms =
2171 predict_rs_scan_time_ms(_predicted_cards_scanned);
2172 _predicted_object_copy_time_ms =
2173 predict_object_copy_time_ms(_predicted_bytes_to_copy);
2174 _predicted_constant_other_time_ms =
2175 predict_constant_other_time_ms();
2176 _predicted_young_other_time_ms =
2177 predict_young_other_time_ms(_recorded_young_regions);
2178 _predicted_non_young_other_time_ms =
2179 predict_non_young_other_time_ms(_recorded_non_young_regions);
2181 _predicted_pause_time_ms =
2182 _predicted_scan_only_scan_time_ms +
2183 _predicted_rs_update_time_ms +
2184 _predicted_rs_scan_time_ms +
2185 _predicted_object_copy_time_ms +
2186 _predicted_constant_other_time_ms +
2187 _predicted_young_other_time_ms +
2188 _predicted_non_young_other_time_ms;
2189 #endif // PREDICTIONS_VERBOSE
2190 }
2192 void G1CollectorPolicy::check_if_region_is_too_expensive(double
2193 predicted_time_ms) {
2194 // I don't think we need to do this when in young GC mode since
2195 // marking will be initiated next time we hit the soft limit anyway...
2196 if (predicted_time_ms > _expensive_region_limit_ms) {
2197 if (!in_young_gc_mode()) {
2198 set_full_young_gcs(true);
2199 _should_initiate_conc_mark = true;
2200 } else
2201 // no point in doing another partial one
2202 _should_revert_to_full_young_gcs = true;
2203 }
2204 }
2206 // </NEW PREDICTION>
2209 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
2210 double elapsed_ms) {
2211 _recent_gc_times_ms->add(elapsed_ms);
2212 _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
2213 _prev_collection_pause_end_ms = end_time_sec * 1000.0;
2214 }
2216 double G1CollectorPolicy::recent_avg_time_for_pauses_ms() {
2217 if (_recent_pause_times_ms->num() == 0) return (double) G1MaxPauseTimeMS;
2218 else return _recent_pause_times_ms->avg();
2219 }
2221 double G1CollectorPolicy::recent_avg_time_for_CH_strong_ms() {
2222 if (_recent_CH_strong_roots_times_ms->num() == 0)
2223 return (double)G1MaxPauseTimeMS/3.0;
2224 else return _recent_CH_strong_roots_times_ms->avg();
2225 }
2227 double G1CollectorPolicy::recent_avg_time_for_G1_strong_ms() {
2228 if (_recent_G1_strong_roots_times_ms->num() == 0)
2229 return (double)G1MaxPauseTimeMS/3.0;
2230 else return _recent_G1_strong_roots_times_ms->avg();
2231 }
2233 double G1CollectorPolicy::recent_avg_time_for_evac_ms() {
2234 if (_recent_evac_times_ms->num() == 0) return (double)G1MaxPauseTimeMS/3.0;
2235 else return _recent_evac_times_ms->avg();
2236 }
2238 int G1CollectorPolicy::number_of_recent_gcs() {
2239 assert(_recent_CH_strong_roots_times_ms->num() ==
2240 _recent_G1_strong_roots_times_ms->num(), "Sequence out of sync");
2241 assert(_recent_G1_strong_roots_times_ms->num() ==
2242 _recent_evac_times_ms->num(), "Sequence out of sync");
2243 assert(_recent_evac_times_ms->num() ==
2244 _recent_pause_times_ms->num(), "Sequence out of sync");
2245 assert(_recent_pause_times_ms->num() ==
2246 _recent_CS_bytes_used_before->num(), "Sequence out of sync");
2247 assert(_recent_CS_bytes_used_before->num() ==
2248 _recent_CS_bytes_surviving->num(), "Sequence out of sync");
2249 return _recent_pause_times_ms->num();
2250 }
2252 double G1CollectorPolicy::recent_avg_survival_fraction() {
2253 return recent_avg_survival_fraction_work(_recent_CS_bytes_surviving,
2254 _recent_CS_bytes_used_before);
2255 }
2257 double G1CollectorPolicy::last_survival_fraction() {
2258 return last_survival_fraction_work(_recent_CS_bytes_surviving,
2259 _recent_CS_bytes_used_before);
2260 }
2262 double
2263 G1CollectorPolicy::recent_avg_survival_fraction_work(TruncatedSeq* surviving,
2264 TruncatedSeq* before) {
2265 assert(surviving->num() == before->num(), "Sequence out of sync");
2266 if (before->sum() > 0.0) {
2267 double recent_survival_rate = surviving->sum() / before->sum();
2268 // We exempt parallel collection from this check because Alloc Buffer
2269 // fragmentation can produce negative collections.
2270 // Further, we're now always doing parallel collection. But I'm still
2271 // leaving this here as a placeholder for a more precise assertion later.
2272 // (DLD, 10/05.)
2273 assert((true || ParallelGCThreads > 0) ||
2274 _g1->evacuation_failed() ||
2275 recent_survival_rate <= 1.0, "Or bad frac");
2276 return recent_survival_rate;
2277 } else {
2278 return 1.0; // Be conservative.
2279 }
2280 }
2282 double
2283 G1CollectorPolicy::last_survival_fraction_work(TruncatedSeq* surviving,
2284 TruncatedSeq* before) {
2285 assert(surviving->num() == before->num(), "Sequence out of sync");
2286 if (surviving->num() > 0 && before->last() > 0.0) {
2287 double last_survival_rate = surviving->last() / before->last();
2288 // We exempt parallel collection from this check because Alloc Buffer
2289 // fragmentation can produce negative collections.
2290 // Further, we're now always doing parallel collection. But I'm still
2291 // leaving this here as a placeholder for a more precise assertion later.
2292 // (DLD, 10/05.)
2293 assert((true || ParallelGCThreads > 0) ||
2294 last_survival_rate <= 1.0, "Or bad frac");
2295 return last_survival_rate;
2296 } else {
2297 return 1.0;
2298 }
2299 }
2301 static const int survival_min_obs = 5;
2302 static double survival_min_obs_limits[] = { 0.9, 0.7, 0.5, 0.3, 0.1 };
2303 static const double min_survival_rate = 0.1;
2305 double
2306 G1CollectorPolicy::conservative_avg_survival_fraction_work(double avg,
2307 double latest) {
2308 double res = avg;
2309 if (number_of_recent_gcs() < survival_min_obs) {
2310 res = MAX2(res, survival_min_obs_limits[number_of_recent_gcs()]);
2311 }
2312 res = MAX2(res, latest);
2313 res = MAX2(res, min_survival_rate);
2314 // In the parallel case, LAB fragmentation can produce "negative
2315 // collections"; so can evac failure. Cap at 1.0
2316 res = MIN2(res, 1.0);
2317 return res;
2318 }
2320 size_t G1CollectorPolicy::expansion_amount() {
2321 if ((int)(recent_avg_pause_time_ratio() * 100.0) > G1GCPct) {
2322 // We will double the existing space, or take G1ExpandByPctOfAvail % of
2323 // the available expansion space, whichever is smaller, bounded below
2324 // by a minimum expansion (unless that's all that's left.)
2325 const size_t min_expand_bytes = 1*M;
2326 size_t reserved_bytes = _g1->g1_reserved_obj_bytes();
2327 size_t committed_bytes = _g1->capacity();
2328 size_t uncommitted_bytes = reserved_bytes - committed_bytes;
2329 size_t expand_bytes;
2330 size_t expand_bytes_via_pct =
2331 uncommitted_bytes * G1ExpandByPctOfAvail / 100;
2332 expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
2333 expand_bytes = MAX2(expand_bytes, min_expand_bytes);
2334 expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
2335 if (G1PolicyVerbose > 1) {
2336 gclog_or_tty->print("Decided to expand: ratio = %5.2f, "
2337 "committed = %d%s, uncommited = %d%s, via pct = %d%s.\n"
2338 " Answer = %d.\n",
2339 recent_avg_pause_time_ratio(),
2340 byte_size_in_proper_unit(committed_bytes),
2341 proper_unit_for_byte_size(committed_bytes),
2342 byte_size_in_proper_unit(uncommitted_bytes),
2343 proper_unit_for_byte_size(uncommitted_bytes),
2344 byte_size_in_proper_unit(expand_bytes_via_pct),
2345 proper_unit_for_byte_size(expand_bytes_via_pct),
2346 byte_size_in_proper_unit(expand_bytes),
2347 proper_unit_for_byte_size(expand_bytes));
2348 }
2349 return expand_bytes;
2350 } else {
2351 return 0;
2352 }
2353 }
2355 void G1CollectorPolicy::note_start_of_mark_thread() {
2356 _mark_thread_startup_sec = os::elapsedTime();
2357 }
2359 class CountCSClosure: public HeapRegionClosure {
2360 G1CollectorPolicy* _g1_policy;
2361 public:
2362 CountCSClosure(G1CollectorPolicy* g1_policy) :
2363 _g1_policy(g1_policy) {}
2364 bool doHeapRegion(HeapRegion* r) {
2365 _g1_policy->_bytes_in_collection_set_before_gc += r->used();
2366 return false;
2367 }
2368 };
2370 void G1CollectorPolicy::count_CS_bytes_used() {
2371 CountCSClosure cs_closure(this);
2372 _g1->collection_set_iterate(&cs_closure);
2373 }
2375 static void print_indent(int level) {
2376 for (int j = 0; j < level+1; ++j)
2377 gclog_or_tty->print(" ");
2378 }
2380 void G1CollectorPolicy::print_summary (int level,
2381 const char* str,
2382 NumberSeq* seq) const {
2383 double sum = seq->sum();
2384 print_indent(level);
2385 gclog_or_tty->print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
2386 str, sum / 1000.0, seq->avg());
2387 }
2389 void G1CollectorPolicy::print_summary_sd (int level,
2390 const char* str,
2391 NumberSeq* seq) const {
2392 print_summary(level, str, seq);
2393 print_indent(level + 5);
2394 gclog_or_tty->print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
2395 seq->num(), seq->sd(), seq->maximum());
2396 }
2398 void G1CollectorPolicy::check_other_times(int level,
2399 NumberSeq* other_times_ms,
2400 NumberSeq* calc_other_times_ms) const {
2401 bool should_print = false;
2403 double max_sum = MAX2(fabs(other_times_ms->sum()),
2404 fabs(calc_other_times_ms->sum()));
2405 double min_sum = MIN2(fabs(other_times_ms->sum()),
2406 fabs(calc_other_times_ms->sum()));
2407 double sum_ratio = max_sum / min_sum;
2408 if (sum_ratio > 1.1) {
2409 should_print = true;
2410 print_indent(level + 1);
2411 gclog_or_tty->print_cr("## CALCULATED OTHER SUM DOESN'T MATCH RECORDED ###");
2412 }
2414 double max_avg = MAX2(fabs(other_times_ms->avg()),
2415 fabs(calc_other_times_ms->avg()));
2416 double min_avg = MIN2(fabs(other_times_ms->avg()),
2417 fabs(calc_other_times_ms->avg()));
2418 double avg_ratio = max_avg / min_avg;
2419 if (avg_ratio > 1.1) {
2420 should_print = true;
2421 print_indent(level + 1);
2422 gclog_or_tty->print_cr("## CALCULATED OTHER AVG DOESN'T MATCH RECORDED ###");
2423 }
2425 if (other_times_ms->sum() < -0.01) {
2426 print_indent(level + 1);
2427 gclog_or_tty->print_cr("## RECORDED OTHER SUM IS NEGATIVE ###");
2428 }
2430 if (other_times_ms->avg() < -0.01) {
2431 print_indent(level + 1);
2432 gclog_or_tty->print_cr("## RECORDED OTHER AVG IS NEGATIVE ###");
2433 }
2435 if (calc_other_times_ms->sum() < -0.01) {
2436 should_print = true;
2437 print_indent(level + 1);
2438 gclog_or_tty->print_cr("## CALCULATED OTHER SUM IS NEGATIVE ###");
2439 }
2441 if (calc_other_times_ms->avg() < -0.01) {
2442 should_print = true;
2443 print_indent(level + 1);
2444 gclog_or_tty->print_cr("## CALCULATED OTHER AVG IS NEGATIVE ###");
2445 }
2447 if (should_print)
2448 print_summary(level, "Other(Calc)", calc_other_times_ms);
2449 }
2451 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
2452 bool parallel = ParallelGCThreads > 0;
2453 MainBodySummary* body_summary = summary->main_body_summary();
2454 PopPreambleSummary* preamble_summary = summary->pop_preamble_summary();
2456 if (summary->get_total_seq()->num() > 0) {
2457 print_summary_sd(0,
2458 (preamble_summary == NULL) ? "Non-Popular Pauses" :
2459 "Popular Pauses",
2460 summary->get_total_seq());
2461 if (preamble_summary != NULL) {
2462 print_summary(1, "Popularity Preamble",
2463 preamble_summary->get_pop_preamble_seq());
2464 print_summary(2, "Update RS", preamble_summary->get_pop_update_rs_seq());
2465 print_summary(2, "Scan RS", preamble_summary->get_pop_scan_rs_seq());
2466 print_summary(2, "Closure App",
2467 preamble_summary->get_pop_closure_app_seq());
2468 print_summary(2, "Evacuation",
2469 preamble_summary->get_pop_evacuation_seq());
2470 print_summary(2, "Other", preamble_summary->get_pop_other_seq());
2471 {
2472 NumberSeq* other_parts[] = {
2473 preamble_summary->get_pop_update_rs_seq(),
2474 preamble_summary->get_pop_scan_rs_seq(),
2475 preamble_summary->get_pop_closure_app_seq(),
2476 preamble_summary->get_pop_evacuation_seq()
2477 };
2478 NumberSeq calc_other_times_ms(preamble_summary->get_pop_preamble_seq(),
2479 4, other_parts);
2480 check_other_times(2, preamble_summary->get_pop_other_seq(),
2481 &calc_other_times_ms);
2482 }
2483 }
2484 if (body_summary != NULL) {
2485 print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
2486 if (parallel) {
2487 print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
2488 print_summary(2, "Update RS", body_summary->get_update_rs_seq());
2489 print_summary(2, "Ext Root Scanning",
2490 body_summary->get_ext_root_scan_seq());
2491 print_summary(2, "Mark Stack Scanning",
2492 body_summary->get_mark_stack_scan_seq());
2493 print_summary(2, "Scan-Only Scanning",
2494 body_summary->get_scan_only_seq());
2495 print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
2496 print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
2497 print_summary(2, "Termination", body_summary->get_termination_seq());
2498 print_summary(2, "Other", body_summary->get_parallel_other_seq());
2499 {
2500 NumberSeq* other_parts[] = {
2501 body_summary->get_update_rs_seq(),
2502 body_summary->get_ext_root_scan_seq(),
2503 body_summary->get_mark_stack_scan_seq(),
2504 body_summary->get_scan_only_seq(),
2505 body_summary->get_scan_rs_seq(),
2506 body_summary->get_obj_copy_seq(),
2507 body_summary->get_termination_seq()
2508 };
2509 NumberSeq calc_other_times_ms(body_summary->get_parallel_seq(),
2510 7, other_parts);
2511 check_other_times(2, body_summary->get_parallel_other_seq(),
2512 &calc_other_times_ms);
2513 }
2514 print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
2515 print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
2516 } else {
2517 print_summary(1, "Update RS", body_summary->get_update_rs_seq());
2518 print_summary(1, "Ext Root Scanning",
2519 body_summary->get_ext_root_scan_seq());
2520 print_summary(1, "Mark Stack Scanning",
2521 body_summary->get_mark_stack_scan_seq());
2522 print_summary(1, "Scan-Only Scanning",
2523 body_summary->get_scan_only_seq());
2524 print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
2525 print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
2526 }
2527 }
2528 print_summary(1, "Other", summary->get_other_seq());
2529 {
2530 NumberSeq calc_other_times_ms;
2531 if (body_summary != NULL) {
2532 // not abandoned
2533 if (parallel) {
2534 // parallel
2535 NumberSeq* other_parts[] = {
2536 body_summary->get_satb_drain_seq(),
2537 (preamble_summary == NULL) ? NULL :
2538 preamble_summary->get_pop_preamble_seq(),
2539 body_summary->get_parallel_seq(),
2540 body_summary->get_clear_ct_seq()
2541 };
2542 calc_other_times_ms = NumberSeq (summary->get_total_seq(),
2543 4, other_parts);
2544 } else {
2545 // serial
2546 NumberSeq* other_parts[] = {
2547 body_summary->get_satb_drain_seq(),
2548 (preamble_summary == NULL) ? NULL :
2549 preamble_summary->get_pop_preamble_seq(),
2550 body_summary->get_update_rs_seq(),
2551 body_summary->get_ext_root_scan_seq(),
2552 body_summary->get_mark_stack_scan_seq(),
2553 body_summary->get_scan_only_seq(),
2554 body_summary->get_scan_rs_seq(),
2555 body_summary->get_obj_copy_seq()
2556 };
2557 calc_other_times_ms = NumberSeq(summary->get_total_seq(),
2558 8, other_parts);
2559 }
2560 } else {
2561 // abandoned
2562 NumberSeq* other_parts[] = {
2563 (preamble_summary == NULL) ? NULL :
2564 preamble_summary->get_pop_preamble_seq()
2565 };
2566 calc_other_times_ms = NumberSeq(summary->get_total_seq(),
2567 1, other_parts);
2568 }
2569 check_other_times(1, summary->get_other_seq(), &calc_other_times_ms);
2570 }
2571 } else {
2572 print_indent(0);
2573 gclog_or_tty->print_cr("none");
2574 }
2575 gclog_or_tty->print_cr("");
2576 }
2578 void
2579 G1CollectorPolicy::print_abandoned_summary(PauseSummary* non_pop_summary,
2580 PauseSummary* pop_summary) const {
2581 bool printed = false;
2582 if (non_pop_summary->get_total_seq()->num() > 0) {
2583 printed = true;
2584 print_summary(non_pop_summary);
2585 }
2586 if (pop_summary->get_total_seq()->num() > 0) {
2587 printed = true;
2588 print_summary(pop_summary);
2589 }
2591 if (!printed) {
2592 print_indent(0);
2593 gclog_or_tty->print_cr("none");
2594 gclog_or_tty->print_cr("");
2595 }
2596 }
2598 void G1CollectorPolicy::print_tracing_info() const {
2599 if (TraceGen0Time) {
2600 gclog_or_tty->print_cr("ALL PAUSES");
2601 print_summary_sd(0, "Total", _all_pause_times_ms);
2602 gclog_or_tty->print_cr("");
2603 gclog_or_tty->print_cr("");
2604 gclog_or_tty->print_cr(" Full Young GC Pauses: %8d", _full_young_pause_num);
2605 gclog_or_tty->print_cr(" Partial Young GC Pauses: %8d", _partial_young_pause_num);
2606 gclog_or_tty->print_cr("");
2608 gclog_or_tty->print_cr("NON-POPULAR PAUSES");
2609 print_summary(_non_pop_summary);
2611 gclog_or_tty->print_cr("POPULAR PAUSES");
2612 print_summary(_pop_summary);
2614 gclog_or_tty->print_cr("ABANDONED PAUSES");
2615 print_abandoned_summary(_non_pop_abandoned_summary,
2616 _pop_abandoned_summary);
2618 gclog_or_tty->print_cr("MISC");
2619 print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
2620 print_summary_sd(0, "Yields", _all_yield_times_ms);
2621 for (int i = 0; i < _aux_num; ++i) {
2622 if (_all_aux_times_ms[i].num() > 0) {
2623 char buffer[96];
2624 sprintf(buffer, "Aux%d", i);
2625 print_summary_sd(0, buffer, &_all_aux_times_ms[i]);
2626 }
2627 }
2629 size_t all_region_num = _region_num_young + _region_num_tenured;
2630 gclog_or_tty->print_cr(" New Regions %8d, Young %8d (%6.2lf%%), "
2631 "Tenured %8d (%6.2lf%%)",
2632 all_region_num,
2633 _region_num_young,
2634 (double) _region_num_young / (double) all_region_num * 100.0,
2635 _region_num_tenured,
2636 (double) _region_num_tenured / (double) all_region_num * 100.0);
2638 if (!G1RSBarrierUseQueue) {
2639 gclog_or_tty->print_cr("Of %d times conc refinement was enabled, %d (%7.2f%%) "
2640 "did zero traversals.",
2641 _conc_refine_enabled, _conc_refine_zero_traversals,
2642 _conc_refine_enabled > 0 ?
2643 100.0 * (float)_conc_refine_zero_traversals/
2644 (float)_conc_refine_enabled : 0.0);
2645 gclog_or_tty->print_cr(" Max # of traversals = %d.",
2646 _conc_refine_max_traversals);
2647 gclog_or_tty->print_cr("");
2648 }
2649 }
2650 if (TraceGen1Time) {
2651 if (_all_full_gc_times_ms->num() > 0) {
2652 gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
2653 _all_full_gc_times_ms->num(),
2654 _all_full_gc_times_ms->sum() / 1000.0);
2655 gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times_ms->avg());
2656 gclog_or_tty->print_cr(" [std. dev = %8.2f ms, max = %8.2f ms]",
2657 _all_full_gc_times_ms->sd(),
2658 _all_full_gc_times_ms->maximum());
2659 }
2660 }
2661 }
2663 void G1CollectorPolicy::print_yg_surv_rate_info() const {
2664 #ifndef PRODUCT
2665 _short_lived_surv_rate_group->print_surv_rate_summary();
2666 // add this call for any other surv rate groups
2667 #endif // PRODUCT
2668 }
2670 void G1CollectorPolicy::update_conc_refine_data() {
2671 unsigned traversals = _g1->concurrent_g1_refine()->disable();
2672 if (traversals == 0) _conc_refine_zero_traversals++;
2673 _conc_refine_max_traversals = MAX2(_conc_refine_max_traversals,
2674 (size_t)traversals);
2676 if (G1PolicyVerbose > 1)
2677 gclog_or_tty->print_cr("Did a CR traversal series: %d traversals.", traversals);
2678 double multiplier = 1.0;
2679 if (traversals == 0) {
2680 multiplier = 4.0;
2681 } else if (traversals > (size_t)G1ConcRefineTargTraversals) {
2682 multiplier = 1.0/1.5;
2683 } else if (traversals < (size_t)G1ConcRefineTargTraversals) {
2684 multiplier = 1.5;
2685 }
2686 if (G1PolicyVerbose > 1) {
2687 gclog_or_tty->print_cr(" Multiplier = %7.2f.", multiplier);
2688 gclog_or_tty->print(" Delta went from %d regions to ",
2689 _conc_refine_current_delta);
2690 }
2691 _conc_refine_current_delta =
2692 MIN2(_g1->n_regions(),
2693 (size_t)(_conc_refine_current_delta * multiplier));
2694 _conc_refine_current_delta =
2695 MAX2(_conc_refine_current_delta, (size_t)1);
2696 if (G1PolicyVerbose > 1) {
2697 gclog_or_tty->print_cr("%d regions.", _conc_refine_current_delta);
2698 }
2699 _conc_refine_enabled++;
2700 }
2702 void G1CollectorPolicy::set_single_region_collection_set(HeapRegion* hr) {
2703 assert(collection_set() == NULL, "Must be no current CS.");
2704 _collection_set_size = 0;
2705 _collection_set_bytes_used_before = 0;
2706 add_to_collection_set(hr);
2707 count_CS_bytes_used();
2708 }
2710 bool
2711 G1CollectorPolicy::should_add_next_region_to_young_list() {
2712 assert(in_young_gc_mode(), "should be in young GC mode");
2713 bool ret;
2714 size_t young_list_length = _g1->young_list_length();
2715 size_t young_list_max_length = _young_list_target_length;
2716 if (G1FixedEdenSize) {
2717 young_list_max_length -= _max_survivor_regions;
2718 }
2719 if (young_list_length < young_list_max_length) {
2720 ret = true;
2721 ++_region_num_young;
2722 } else {
2723 ret = false;
2724 ++_region_num_tenured;
2725 }
2727 return ret;
2728 }
2730 #ifndef PRODUCT
2731 // for debugging, bit of a hack...
2732 static char*
2733 region_num_to_mbs(int length) {
2734 static char buffer[64];
2735 double bytes = (double) (length * HeapRegion::GrainBytes);
2736 double mbs = bytes / (double) (1024 * 1024);
2737 sprintf(buffer, "%7.2lfMB", mbs);
2738 return buffer;
2739 }
2740 #endif // PRODUCT
2742 void
2743 G1CollectorPolicy::checkpoint_conc_overhead() {
2744 double conc_overhead = 0.0;
2745 if (G1AccountConcurrentOverhead)
2746 conc_overhead = COTracker::totalPredConcOverhead();
2747 _mmu_tracker->update_conc_overhead(conc_overhead);
2748 #if 0
2749 gclog_or_tty->print(" CO %1.4lf TARGET %1.4lf",
2750 conc_overhead, _mmu_tracker->max_gc_time());
2751 #endif
2752 }
2755 size_t G1CollectorPolicy::max_regions(int purpose) {
2756 switch (purpose) {
2757 case GCAllocForSurvived:
2758 return _max_survivor_regions;
2759 case GCAllocForTenured:
2760 return REGIONS_UNLIMITED;
2761 default:
2762 ShouldNotReachHere();
2763 return REGIONS_UNLIMITED;
2764 };
2765 }
2767 // Calculates survivor space parameters.
2768 void G1CollectorPolicy::calculate_survivors_policy()
2769 {
2770 if (!G1UseSurvivorSpace) {
2771 return;
2772 }
2773 if (G1FixedSurvivorSpaceSize == 0) {
2774 _max_survivor_regions = _young_list_target_length / SurvivorRatio;
2775 } else {
2776 _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
2777 }
2779 if (G1FixedTenuringThreshold) {
2780 _tenuring_threshold = MaxTenuringThreshold;
2781 } else {
2782 _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
2783 HeapRegion::GrainWords * _max_survivor_regions);
2784 }
2785 }
2788 void
2789 G1CollectorPolicy_BestRegionsFirst::
2790 set_single_region_collection_set(HeapRegion* hr) {
2791 G1CollectorPolicy::set_single_region_collection_set(hr);
2792 _collectionSetChooser->removeRegion(hr);
2793 }
2796 bool
2797 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
2798 word_size) {
2799 assert(_g1->regions_accounted_for(), "Region leakage!");
2800 // Initiate a pause when we reach the steady-state "used" target.
2801 size_t used_hard = (_g1->capacity() / 100) * G1SteadyStateUsed;
2802 size_t used_soft =
2803 MAX2((_g1->capacity() / 100) * (G1SteadyStateUsed - G1SteadyStateUsedDelta),
2804 used_hard/2);
2805 size_t used = _g1->used();
2807 double max_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
2809 size_t young_list_length = _g1->young_list_length();
2810 size_t young_list_max_length = _young_list_target_length;
2811 if (G1FixedEdenSize) {
2812 young_list_max_length -= _max_survivor_regions;
2813 }
2814 bool reached_target_length = young_list_length >= young_list_max_length;
2816 if (in_young_gc_mode()) {
2817 if (reached_target_length) {
2818 assert( young_list_length > 0 && _g1->young_list_length() > 0,
2819 "invariant" );
2820 _target_pause_time_ms = max_pause_time_ms;
2821 return true;
2822 }
2823 } else {
2824 guarantee( false, "should not reach here" );
2825 }
2827 return false;
2828 }
2830 #ifndef PRODUCT
2831 class HRSortIndexIsOKClosure: public HeapRegionClosure {
2832 CollectionSetChooser* _chooser;
2833 public:
2834 HRSortIndexIsOKClosure(CollectionSetChooser* chooser) :
2835 _chooser(chooser) {}
2837 bool doHeapRegion(HeapRegion* r) {
2838 if (!r->continuesHumongous()) {
2839 assert(_chooser->regionProperlyOrdered(r), "Ought to be.");
2840 }
2841 return false;
2842 }
2843 };
2845 bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() {
2846 HRSortIndexIsOKClosure cl(_collectionSetChooser);
2847 _g1->heap_region_iterate(&cl);
2848 return true;
2849 }
2850 #endif
2852 void
2853 G1CollectorPolicy_BestRegionsFirst::
2854 record_collection_pause_start(double start_time_sec, size_t start_used) {
2855 G1CollectorPolicy::record_collection_pause_start(start_time_sec, start_used);
2856 }
2858 class NextNonCSElemFinder: public HeapRegionClosure {
2859 HeapRegion* _res;
2860 public:
2861 NextNonCSElemFinder(): _res(NULL) {}
2862 bool doHeapRegion(HeapRegion* r) {
2863 if (!r->in_collection_set()) {
2864 _res = r;
2865 return true;
2866 } else {
2867 return false;
2868 }
2869 }
2870 HeapRegion* res() { return _res; }
2871 };
2873 class KnownGarbageClosure: public HeapRegionClosure {
2874 CollectionSetChooser* _hrSorted;
2876 public:
2877 KnownGarbageClosure(CollectionSetChooser* hrSorted) :
2878 _hrSorted(hrSorted)
2879 {}
2881 bool doHeapRegion(HeapRegion* r) {
2882 // We only include humongous regions in collection
2883 // sets when concurrent mark shows that their contained object is
2884 // unreachable.
2886 // Do we have any marking information for this region?
2887 if (r->is_marked()) {
2888 // We don't include humongous regions in collection
2889 // sets because we collect them immediately at the end of a marking
2890 // cycle. We also don't include young regions because we *must*
2891 // include them in the next collection pause.
2892 if (!r->isHumongous() && !r->is_young()) {
2893 _hrSorted->addMarkedHeapRegion(r);
2894 }
2895 }
2896 return false;
2897 }
2898 };
2900 class ParKnownGarbageHRClosure: public HeapRegionClosure {
2901 CollectionSetChooser* _hrSorted;
2902 jint _marked_regions_added;
2903 jint _chunk_size;
2904 jint _cur_chunk_idx;
2905 jint _cur_chunk_end; // Cur chunk [_cur_chunk_idx, _cur_chunk_end)
2906 int _worker;
2907 int _invokes;
2909 void get_new_chunk() {
2910 _cur_chunk_idx = _hrSorted->getParMarkedHeapRegionChunk(_chunk_size);
2911 _cur_chunk_end = _cur_chunk_idx + _chunk_size;
2912 }
2913 void add_region(HeapRegion* r) {
2914 if (_cur_chunk_idx == _cur_chunk_end) {
2915 get_new_chunk();
2916 }
2917 assert(_cur_chunk_idx < _cur_chunk_end, "postcondition");
2918 _hrSorted->setMarkedHeapRegion(_cur_chunk_idx, r);
2919 _marked_regions_added++;
2920 _cur_chunk_idx++;
2921 }
2923 public:
2924 ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
2925 jint chunk_size,
2926 int worker) :
2927 _hrSorted(hrSorted), _chunk_size(chunk_size), _worker(worker),
2928 _marked_regions_added(0), _cur_chunk_idx(0), _cur_chunk_end(0),
2929 _invokes(0)
2930 {}
2932 bool doHeapRegion(HeapRegion* r) {
2933 // We only include humongous regions in collection
2934 // sets when concurrent mark shows that their contained object is
2935 // unreachable.
2936 _invokes++;
2938 // Do we have any marking information for this region?
2939 if (r->is_marked()) {
2940 // We don't include humongous regions in collection
2941 // sets because we collect them immediately at the end of a marking
2942 // cycle.
2943 // We also do not include young regions in collection sets
2944 if (!r->isHumongous() && !r->is_young()) {
2945 add_region(r);
2946 }
2947 }
2948 return false;
2949 }
2950 jint marked_regions_added() { return _marked_regions_added; }
2951 int invokes() { return _invokes; }
2952 };
2954 class ParKnownGarbageTask: public AbstractGangTask {
2955 CollectionSetChooser* _hrSorted;
2956 jint _chunk_size;
2957 G1CollectedHeap* _g1;
2958 public:
2959 ParKnownGarbageTask(CollectionSetChooser* hrSorted, jint chunk_size) :
2960 AbstractGangTask("ParKnownGarbageTask"),
2961 _hrSorted(hrSorted), _chunk_size(chunk_size),
2962 _g1(G1CollectedHeap::heap())
2963 {}
2965 void work(int i) {
2966 ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size, i);
2967 // Back to zero for the claim value.
2968 _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, i,
2969 HeapRegion::InitialClaimValue);
2970 jint regions_added = parKnownGarbageCl.marked_regions_added();
2971 _hrSorted->incNumMarkedHeapRegions(regions_added);
2972 if (G1PrintParCleanupStats) {
2973 gclog_or_tty->print(" Thread %d called %d times, added %d regions to list.\n",
2974 i, parKnownGarbageCl.invokes(), regions_added);
2975 }
2976 }
2977 };
2979 void
2980 G1CollectorPolicy_BestRegionsFirst::
2981 record_concurrent_mark_cleanup_end(size_t freed_bytes,
2982 size_t max_live_bytes) {
2983 double start;
2984 if (G1PrintParCleanupStats) start = os::elapsedTime();
2985 record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
2987 _collectionSetChooser->clearMarkedHeapRegions();
2988 double clear_marked_end;
2989 if (G1PrintParCleanupStats) {
2990 clear_marked_end = os::elapsedTime();
2991 gclog_or_tty->print_cr(" clear marked regions + work1: %8.3f ms.",
2992 (clear_marked_end - start)*1000.0);
2993 }
2994 if (ParallelGCThreads > 0) {
2995 const size_t OverpartitionFactor = 4;
2996 const size_t MinChunkSize = 8;
2997 const size_t ChunkSize =
2998 MAX2(_g1->n_regions() / (ParallelGCThreads * OverpartitionFactor),
2999 MinChunkSize);
3000 _collectionSetChooser->prepareForAddMarkedHeapRegionsPar(_g1->n_regions(),
3001 ChunkSize);
3002 ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
3003 (int) ChunkSize);
3004 _g1->workers()->run_task(&parKnownGarbageTask);
3006 assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3007 "sanity check");
3008 } else {
3009 KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
3010 _g1->heap_region_iterate(&knownGarbagecl);
3011 }
3012 double known_garbage_end;
3013 if (G1PrintParCleanupStats) {
3014 known_garbage_end = os::elapsedTime();
3015 gclog_or_tty->print_cr(" compute known garbage: %8.3f ms.",
3016 (known_garbage_end - clear_marked_end)*1000.0);
3017 }
3018 _collectionSetChooser->sortMarkedHeapRegions();
3019 double sort_end;
3020 if (G1PrintParCleanupStats) {
3021 sort_end = os::elapsedTime();
3022 gclog_or_tty->print_cr(" sorting: %8.3f ms.",
3023 (sort_end - known_garbage_end)*1000.0);
3024 }
3026 record_concurrent_mark_cleanup_end_work2();
3027 double work2_end;
3028 if (G1PrintParCleanupStats) {
3029 work2_end = os::elapsedTime();
3030 gclog_or_tty->print_cr(" work2: %8.3f ms.",
3031 (work2_end - sort_end)*1000.0);
3032 }
3033 }
3035 // Add the heap region to the collection set and return the conservative
3036 // estimate of the number of live bytes.
3037 void G1CollectorPolicy::
3038 add_to_collection_set(HeapRegion* hr) {
3039 if (G1TraceRegions) {
3040 gclog_or_tty->print_cr("added region to cset %d:["PTR_FORMAT", "PTR_FORMAT"], "
3041 "top "PTR_FORMAT", young %s",
3042 hr->hrs_index(), hr->bottom(), hr->end(),
3043 hr->top(), (hr->is_young()) ? "YES" : "NO");
3044 }
3046 if (_g1->mark_in_progress())
3047 _g1->concurrent_mark()->registerCSetRegion(hr);
3049 assert(!hr->in_collection_set(),
3050 "should not already be in the CSet");
3051 hr->set_in_collection_set(true);
3052 hr->set_next_in_collection_set(_collection_set);
3053 _collection_set = hr;
3054 _collection_set_size++;
3055 _collection_set_bytes_used_before += hr->used();
3056 _g1->register_region_with_in_cset_fast_test(hr);
3057 }
3059 void
3060 G1CollectorPolicy_BestRegionsFirst::
3061 choose_collection_set(HeapRegion* pop_region) {
3062 double non_young_start_time_sec;
3063 start_recording_regions();
3065 if (pop_region != NULL) {
3066 _target_pause_time_ms = (double) G1MaxPauseTimeMS;
3067 } else {
3068 guarantee(_target_pause_time_ms > -1.0,
3069 "_target_pause_time_ms should have been set!");
3070 }
3072 // pop region is either null (and so is CS), or else it *is* the CS.
3073 assert(_collection_set == pop_region, "Precondition");
3075 double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
3076 double predicted_pause_time_ms = base_time_ms;
3078 double target_time_ms = _target_pause_time_ms;
3079 double time_remaining_ms = target_time_ms - base_time_ms;
3081 // the 10% and 50% values are arbitrary...
3082 if (time_remaining_ms < 0.10*target_time_ms) {
3083 time_remaining_ms = 0.50 * target_time_ms;
3084 _within_target = false;
3085 } else {
3086 _within_target = true;
3087 }
3089 // We figure out the number of bytes available for future to-space.
3090 // For new regions without marking information, we must assume the
3091 // worst-case of complete survival. If we have marking information for a
3092 // region, we can bound the amount of live data. We can add a number of
3093 // such regions, as long as the sum of the live data bounds does not
3094 // exceed the available evacuation space.
3095 size_t max_live_bytes = _g1->free_regions() * HeapRegion::GrainBytes;
3097 size_t expansion_bytes =
3098 _g1->expansion_regions() * HeapRegion::GrainBytes;
3100 if (pop_region == NULL) {
3101 _collection_set_bytes_used_before = 0;
3102 _collection_set_size = 0;
3103 }
3105 // Adjust for expansion and slop.
3106 max_live_bytes = max_live_bytes + expansion_bytes;
3108 assert(pop_region != NULL || _g1->regions_accounted_for(), "Region leakage!");
3110 HeapRegion* hr;
3111 if (in_young_gc_mode()) {
3112 double young_start_time_sec = os::elapsedTime();
3114 if (G1PolicyVerbose > 0) {
3115 gclog_or_tty->print_cr("Adding %d young regions to the CSet",
3116 _g1->young_list_length());
3117 }
3118 _young_cset_length = 0;
3119 _last_young_gc_full = full_young_gcs() ? true : false;
3120 if (_last_young_gc_full)
3121 ++_full_young_pause_num;
3122 else
3123 ++_partial_young_pause_num;
3124 hr = _g1->pop_region_from_young_list();
3125 while (hr != NULL) {
3127 assert( hr->young_index_in_cset() == -1, "invariant" );
3128 assert( hr->age_in_surv_rate_group() != -1, "invariant" );
3129 hr->set_young_index_in_cset((int) _young_cset_length);
3131 ++_young_cset_length;
3132 double predicted_time_ms = predict_region_elapsed_time_ms(hr, true);
3133 time_remaining_ms -= predicted_time_ms;
3134 predicted_pause_time_ms += predicted_time_ms;
3135 if (hr == pop_region) {
3136 // The popular region was young. Skip over it.
3137 assert(hr->in_collection_set(), "It's the pop region.");
3138 } else {
3139 assert(!hr->in_collection_set(), "It's not the pop region.");
3140 add_to_collection_set(hr);
3141 record_cset_region(hr, true);
3142 }
3143 max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
3144 if (G1PolicyVerbose > 0) {
3145 gclog_or_tty->print_cr(" Added [" PTR_FORMAT ", " PTR_FORMAT") to CS.",
3146 hr->bottom(), hr->end());
3147 gclog_or_tty->print_cr(" (" SIZE_FORMAT " KB left in heap.)",
3148 max_live_bytes/K);
3149 }
3150 hr = _g1->pop_region_from_young_list();
3151 }
3153 record_scan_only_regions(_g1->young_list_scan_only_length());
3155 double young_end_time_sec = os::elapsedTime();
3156 _recorded_young_cset_choice_time_ms =
3157 (young_end_time_sec - young_start_time_sec) * 1000.0;
3159 non_young_start_time_sec = os::elapsedTime();
3161 if (_young_cset_length > 0 && _last_young_gc_full) {
3162 // don't bother adding more regions...
3163 goto choose_collection_set_end;
3164 }
3165 } else if (pop_region != NULL) {
3166 // We're not in young mode, and we chose a popular region; don't choose
3167 // any more.
3168 return;
3169 }
3171 if (!in_young_gc_mode() || !full_young_gcs()) {
3172 bool should_continue = true;
3173 NumberSeq seq;
3174 double avg_prediction = 100000000000000000.0; // something very large
3175 do {
3176 hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
3177 avg_prediction);
3178 if (hr != NULL && !hr->popular()) {
3179 double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
3180 time_remaining_ms -= predicted_time_ms;
3181 predicted_pause_time_ms += predicted_time_ms;
3182 add_to_collection_set(hr);
3183 record_cset_region(hr, false);
3184 max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
3185 if (G1PolicyVerbose > 0) {
3186 gclog_or_tty->print_cr(" (" SIZE_FORMAT " KB left in heap.)",
3187 max_live_bytes/K);
3188 }
3189 seq.add(predicted_time_ms);
3190 avg_prediction = seq.avg() + seq.sd();
3191 }
3192 should_continue =
3193 ( hr != NULL) &&
3194 ( (adaptive_young_list_length()) ? time_remaining_ms > 0.0
3195 : _collection_set_size < _young_list_fixed_length );
3196 } while (should_continue);
3198 if (!adaptive_young_list_length() &&
3199 _collection_set_size < _young_list_fixed_length)
3200 _should_revert_to_full_young_gcs = true;
3201 }
3203 choose_collection_set_end:
3204 count_CS_bytes_used();
3206 end_recording_regions();
3208 double non_young_end_time_sec = os::elapsedTime();
3209 _recorded_non_young_cset_choice_time_ms =
3210 (non_young_end_time_sec - non_young_start_time_sec) * 1000.0;
3211 }
3213 void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() {
3214 G1CollectorPolicy::record_full_collection_end();
3215 _collectionSetChooser->updateAfterFullCollection();
3216 }
3218 void G1CollectorPolicy_BestRegionsFirst::
3219 expand_if_possible(size_t numRegions) {
3220 size_t expansion_bytes = numRegions * HeapRegion::GrainBytes;
3221 _g1->expand(expansion_bytes);
3222 }
3224 void G1CollectorPolicy_BestRegionsFirst::
3225 record_collection_pause_end(bool popular, bool abandoned) {
3226 G1CollectorPolicy::record_collection_pause_end(popular, abandoned);
3227 assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
3228 }
3230 // Local Variables: ***
3231 // c-indentation-style: gnu ***
3232 // End: ***