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