Fri, 16 Apr 2010 08:48:16 -0700
6942253: G1: replace G1ParallelGCAllocBufferSize with YoungPLABSize and OldPLABSize
Summary: Replaces the G1-specific parameter with the existing ones that are used by the other GCs (YoungPLABSize and OldPLABSize)
Reviewed-by: tonyp, johnc
1 /*
2 * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
25 #include "incls/_precompiled.incl"
26 #include "incls/_g1CollectorPolicy.cpp.incl"
28 #define PREDICTIONS_VERBOSE 0
30 // <NEW PREDICTION>
32 // Different defaults for different number of GC threads
33 // They were chosen by running GCOld and SPECjbb on debris with different
34 // numbers of GC threads and choosing them based on the results
36 // all the same
37 static double rs_length_diff_defaults[] = {
38 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
39 };
41 static double cost_per_card_ms_defaults[] = {
42 0.01, 0.005, 0.005, 0.003, 0.003, 0.002, 0.002, 0.0015
43 };
45 static double cost_per_scan_only_region_ms_defaults[] = {
46 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
47 };
49 // all the same
50 static double fully_young_cards_per_entry_ratio_defaults[] = {
51 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
52 };
54 static double cost_per_entry_ms_defaults[] = {
55 0.015, 0.01, 0.01, 0.008, 0.008, 0.0055, 0.0055, 0.005
56 };
58 static double cost_per_byte_ms_defaults[] = {
59 0.00006, 0.00003, 0.00003, 0.000015, 0.000015, 0.00001, 0.00001, 0.000009
60 };
62 // these should be pretty consistent
63 static double constant_other_time_ms_defaults[] = {
64 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0
65 };
68 static double young_other_cost_per_region_ms_defaults[] = {
69 0.3, 0.2, 0.2, 0.15, 0.15, 0.12, 0.12, 0.1
70 };
72 static double non_young_other_cost_per_region_ms_defaults[] = {
73 1.0, 0.7, 0.7, 0.5, 0.5, 0.42, 0.42, 0.30
74 };
76 // </NEW PREDICTION>
78 G1CollectorPolicy::G1CollectorPolicy() :
79 _parallel_gc_threads((ParallelGCThreads > 0) ? ParallelGCThreads : 1),
80 _n_pauses(0),
81 _recent_CH_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
82 _recent_G1_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
83 _recent_evac_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
84 _recent_pause_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
85 _recent_rs_sizes(new TruncatedSeq(NumPrevPausesForHeuristics)),
86 _recent_gc_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
87 _all_pause_times_ms(new NumberSeq()),
88 _stop_world_start(0.0),
89 _all_stop_world_times_ms(new NumberSeq()),
90 _all_yield_times_ms(new NumberSeq()),
92 _all_mod_union_times_ms(new NumberSeq()),
94 _summary(new Summary()),
95 _abandoned_summary(new AbandonedSummary()),
97 #ifndef PRODUCT
98 _cur_clear_ct_time_ms(0.0),
99 _min_clear_cc_time_ms(-1.0),
100 _max_clear_cc_time_ms(-1.0),
101 _cur_clear_cc_time_ms(0.0),
102 _cum_clear_cc_time_ms(0.0),
103 _num_cc_clears(0L),
104 #endif
106 _region_num_young(0),
107 _region_num_tenured(0),
108 _prev_region_num_young(0),
109 _prev_region_num_tenured(0),
111 _aux_num(10),
112 _all_aux_times_ms(new NumberSeq[_aux_num]),
113 _cur_aux_start_times_ms(new double[_aux_num]),
114 _cur_aux_times_ms(new double[_aux_num]),
115 _cur_aux_times_set(new bool[_aux_num]),
117 _concurrent_mark_init_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
118 _concurrent_mark_remark_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
119 _concurrent_mark_cleanup_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
121 // <NEW PREDICTION>
123 _alloc_rate_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
124 _prev_collection_pause_end_ms(0.0),
125 _pending_card_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
126 _rs_length_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
127 _cost_per_card_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
128 _cost_per_scan_only_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
129 _fully_young_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),
130 _partially_young_cards_per_entry_ratio_seq(
131 new TruncatedSeq(TruncatedSeqLength)),
132 _cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
133 _partially_young_cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
134 _cost_per_byte_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
135 _cost_per_byte_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
136 _cost_per_scan_only_region_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
137 _constant_other_time_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
138 _young_other_cost_per_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
139 _non_young_other_cost_per_region_ms_seq(
140 new TruncatedSeq(TruncatedSeqLength)),
142 _pending_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
143 _scanned_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
144 _rs_lengths_seq(new TruncatedSeq(TruncatedSeqLength)),
146 _pause_time_target_ms((double) MaxGCPauseMillis),
148 // </NEW PREDICTION>
150 _in_young_gc_mode(false),
151 _full_young_gcs(true),
152 _full_young_pause_num(0),
153 _partial_young_pause_num(0),
155 _during_marking(false),
156 _in_marking_window(false),
157 _in_marking_window_im(false),
159 _known_garbage_ratio(0.0),
160 _known_garbage_bytes(0),
162 _young_gc_eff_seq(new TruncatedSeq(TruncatedSeqLength)),
163 _target_pause_time_ms(-1.0),
165 _recent_prev_end_times_for_all_gcs_sec(new TruncatedSeq(NumPrevPausesForHeuristics)),
167 _recent_CS_bytes_used_before(new TruncatedSeq(NumPrevPausesForHeuristics)),
168 _recent_CS_bytes_surviving(new TruncatedSeq(NumPrevPausesForHeuristics)),
170 _recent_avg_pause_time_ratio(0.0),
171 _num_markings(0),
172 _n_marks(0),
173 _n_pauses_at_mark_end(0),
175 _all_full_gc_times_ms(new NumberSeq()),
177 // G1PausesBtwnConcMark defaults to -1
178 // so the hack is to do the cast QQQ FIXME
179 _pauses_btwn_concurrent_mark((size_t)G1PausesBtwnConcMark),
180 _n_marks_since_last_pause(0),
181 _initiate_conc_mark_if_possible(false),
182 _during_initial_mark_pause(false),
183 _should_revert_to_full_young_gcs(false),
184 _last_full_young_gc(false),
186 _prev_collection_pause_used_at_end_bytes(0),
188 _collection_set(NULL),
189 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
190 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
191 #endif // _MSC_VER
193 _short_lived_surv_rate_group(new SurvRateGroup(this, "Short Lived",
194 G1YoungSurvRateNumRegionsSummary)),
195 _survivor_surv_rate_group(new SurvRateGroup(this, "Survivor",
196 G1YoungSurvRateNumRegionsSummary)),
197 // add here any more surv rate groups
198 _recorded_survivor_regions(0),
199 _recorded_survivor_head(NULL),
200 _recorded_survivor_tail(NULL),
201 _survivors_age_table(true),
203 _gc_overhead_perc(0.0)
205 {
206 // Set up the region size and associated fields. Given that the
207 // policy is created before the heap, we have to set this up here,
208 // so it's done as soon as possible.
209 HeapRegion::setup_heap_region_size(Arguments::min_heap_size());
210 HeapRegionRemSet::setup_remset_size();
212 // Verify PLAB sizes
213 const uint region_size = HeapRegion::GrainWords;
214 if (YoungPLABSize > region_size || OldPLABSize > region_size) {
215 char buffer[128];
216 jio_snprintf(buffer, sizeof(buffer), "%sPLABSize should be at most %u",
217 OldPLABSize > region_size ? "Old" : "Young", region_size);
218 vm_exit_during_initialization(buffer);
219 }
221 _recent_prev_end_times_for_all_gcs_sec->add(os::elapsedTime());
222 _prev_collection_pause_end_ms = os::elapsedTime() * 1000.0;
224 _par_last_ext_root_scan_times_ms = new double[_parallel_gc_threads];
225 _par_last_mark_stack_scan_times_ms = new double[_parallel_gc_threads];
226 _par_last_scan_only_times_ms = new double[_parallel_gc_threads];
227 _par_last_scan_only_regions_scanned = new double[_parallel_gc_threads];
229 _par_last_update_rs_start_times_ms = new double[_parallel_gc_threads];
230 _par_last_update_rs_times_ms = new double[_parallel_gc_threads];
231 _par_last_update_rs_processed_buffers = new double[_parallel_gc_threads];
233 _par_last_scan_rs_start_times_ms = new double[_parallel_gc_threads];
234 _par_last_scan_rs_times_ms = new double[_parallel_gc_threads];
235 _par_last_scan_new_refs_times_ms = new double[_parallel_gc_threads];
237 _par_last_obj_copy_times_ms = new double[_parallel_gc_threads];
239 _par_last_termination_times_ms = new double[_parallel_gc_threads];
241 // start conservatively
242 _expensive_region_limit_ms = 0.5 * (double) MaxGCPauseMillis;
244 // <NEW PREDICTION>
246 int index;
247 if (ParallelGCThreads == 0)
248 index = 0;
249 else if (ParallelGCThreads > 8)
250 index = 7;
251 else
252 index = ParallelGCThreads - 1;
254 _pending_card_diff_seq->add(0.0);
255 _rs_length_diff_seq->add(rs_length_diff_defaults[index]);
256 _cost_per_card_ms_seq->add(cost_per_card_ms_defaults[index]);
257 _cost_per_scan_only_region_ms_seq->add(
258 cost_per_scan_only_region_ms_defaults[index]);
259 _fully_young_cards_per_entry_ratio_seq->add(
260 fully_young_cards_per_entry_ratio_defaults[index]);
261 _cost_per_entry_ms_seq->add(cost_per_entry_ms_defaults[index]);
262 _cost_per_byte_ms_seq->add(cost_per_byte_ms_defaults[index]);
263 _constant_other_time_ms_seq->add(constant_other_time_ms_defaults[index]);
264 _young_other_cost_per_region_ms_seq->add(
265 young_other_cost_per_region_ms_defaults[index]);
266 _non_young_other_cost_per_region_ms_seq->add(
267 non_young_other_cost_per_region_ms_defaults[index]);
269 // </NEW PREDICTION>
271 double time_slice = (double) GCPauseIntervalMillis / 1000.0;
272 double max_gc_time = (double) MaxGCPauseMillis / 1000.0;
273 guarantee(max_gc_time < time_slice,
274 "Max GC time should not be greater than the time slice");
275 _mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);
276 _sigma = (double) G1ConfidencePercent / 100.0;
278 // start conservatively (around 50ms is about right)
279 _concurrent_mark_init_times_ms->add(0.05);
280 _concurrent_mark_remark_times_ms->add(0.05);
281 _concurrent_mark_cleanup_times_ms->add(0.20);
282 _tenuring_threshold = MaxTenuringThreshold;
284 // if G1FixedSurvivorSpaceSize is 0 which means the size is not
285 // fixed, then _max_survivor_regions will be calculated at
286 // calculate_young_list_target_config during initialization
287 _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
289 assert(GCTimeRatio > 0,
290 "we should have set it to a default value set_g1_gc_flags() "
291 "if a user set it to 0");
292 _gc_overhead_perc = 100.0 * (1.0 / (1.0 + GCTimeRatio));
294 initialize_all();
295 }
297 // Increment "i", mod "len"
298 static void inc_mod(int& i, int len) {
299 i++; if (i == len) i = 0;
300 }
302 void G1CollectorPolicy::initialize_flags() {
303 set_min_alignment(HeapRegion::GrainBytes);
304 set_max_alignment(GenRemSet::max_alignment_constraint(rem_set_name()));
305 if (SurvivorRatio < 1) {
306 vm_exit_during_initialization("Invalid survivor ratio specified");
307 }
308 CollectorPolicy::initialize_flags();
309 }
311 // The easiest way to deal with the parsing of the NewSize /
312 // MaxNewSize / etc. parameteres is to re-use the code in the
313 // TwoGenerationCollectorPolicy class. This is similar to what
314 // ParallelScavenge does with its GenerationSizer class (see
315 // ParallelScavengeHeap::initialize()). We might change this in the
316 // future, but it's a good start.
317 class G1YoungGenSizer : public TwoGenerationCollectorPolicy {
318 size_t size_to_region_num(size_t byte_size) {
319 return MAX2((size_t) 1, byte_size / HeapRegion::GrainBytes);
320 }
322 public:
323 G1YoungGenSizer() {
324 initialize_flags();
325 initialize_size_info();
326 }
328 size_t min_young_region_num() {
329 return size_to_region_num(_min_gen0_size);
330 }
331 size_t initial_young_region_num() {
332 return size_to_region_num(_initial_gen0_size);
333 }
334 size_t max_young_region_num() {
335 return size_to_region_num(_max_gen0_size);
336 }
337 };
339 void G1CollectorPolicy::init() {
340 // Set aside an initial future to_space.
341 _g1 = G1CollectedHeap::heap();
343 assert(Heap_lock->owned_by_self(), "Locking discipline.");
345 initialize_gc_policy_counters();
347 if (G1Gen) {
348 _in_young_gc_mode = true;
350 G1YoungGenSizer sizer;
351 size_t initial_region_num = sizer.initial_young_region_num();
353 if (UseAdaptiveSizePolicy) {
354 set_adaptive_young_list_length(true);
355 _young_list_fixed_length = 0;
356 } else {
357 set_adaptive_young_list_length(false);
358 _young_list_fixed_length = initial_region_num;
359 }
360 _free_regions_at_end_of_collection = _g1->free_regions();
361 _scan_only_regions_at_end_of_collection = 0;
362 calculate_young_list_min_length();
363 guarantee( _young_list_min_length == 0, "invariant, not enough info" );
364 calculate_young_list_target_config();
365 } else {
366 _young_list_fixed_length = 0;
367 _in_young_gc_mode = false;
368 }
369 }
371 // Create the jstat counters for the policy.
372 void G1CollectorPolicy::initialize_gc_policy_counters()
373 {
374 _gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 2 + G1Gen);
375 }
377 void G1CollectorPolicy::calculate_young_list_min_length() {
378 _young_list_min_length = 0;
380 if (!adaptive_young_list_length())
381 return;
383 if (_alloc_rate_ms_seq->num() > 3) {
384 double now_sec = os::elapsedTime();
385 double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;
386 double alloc_rate_ms = predict_alloc_rate_ms();
387 int min_regions = (int) ceil(alloc_rate_ms * when_ms);
388 int current_region_num = (int) _g1->young_list_length();
389 _young_list_min_length = min_regions + current_region_num;
390 }
391 }
393 void G1CollectorPolicy::calculate_young_list_target_config() {
394 if (adaptive_young_list_length()) {
395 size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
396 calculate_young_list_target_config(rs_lengths);
397 } else {
398 if (full_young_gcs())
399 _young_list_target_length = _young_list_fixed_length;
400 else
401 _young_list_target_length = _young_list_fixed_length / 2;
402 _young_list_target_length = MAX2(_young_list_target_length, (size_t)1);
403 size_t so_length = calculate_optimal_so_length(_young_list_target_length);
404 guarantee( so_length < _young_list_target_length, "invariant" );
405 _young_list_so_prefix_length = so_length;
406 }
407 calculate_survivors_policy();
408 }
410 // This method calculate the optimal scan-only set for a fixed young
411 // gen size. I couldn't work out how to reuse the more elaborate one,
412 // i.e. calculate_young_list_target_config(rs_length), as the loops are
413 // fundamentally different (the other one finds a config for different
414 // S-O lengths, whereas here we need to do the opposite).
415 size_t G1CollectorPolicy::calculate_optimal_so_length(
416 size_t young_list_length) {
417 if (!G1UseScanOnlyPrefix)
418 return 0;
420 if (_all_pause_times_ms->num() < 3) {
421 // we won't use a scan-only set at the beginning to allow the rest
422 // of the predictors to warm up
423 return 0;
424 }
426 if (_cost_per_scan_only_region_ms_seq->num() < 3) {
427 // then, we'll only set the S-O set to 1 for a little bit of time,
428 // to get enough information on the scanning cost
429 return 1;
430 }
432 size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
433 size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
434 size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
435 size_t scanned_cards;
436 if (full_young_gcs())
437 scanned_cards = predict_young_card_num(adj_rs_lengths);
438 else
439 scanned_cards = predict_non_young_card_num(adj_rs_lengths);
440 double base_time_ms = predict_base_elapsed_time_ms(pending_cards,
441 scanned_cards);
443 size_t so_length = 0;
444 double max_gc_eff = 0.0;
445 for (size_t i = 0; i < young_list_length; ++i) {
446 double gc_eff = 0.0;
447 double pause_time_ms = 0.0;
448 predict_gc_eff(young_list_length, i, base_time_ms,
449 &gc_eff, &pause_time_ms);
450 if (gc_eff > max_gc_eff) {
451 max_gc_eff = gc_eff;
452 so_length = i;
453 }
454 }
456 // set it to 95% of the optimal to make sure we sample the "area"
457 // around the optimal length to get up-to-date survival rate data
458 return so_length * 950 / 1000;
459 }
461 // This is a really cool piece of code! It finds the best
462 // target configuration (young length / scan-only prefix length) so
463 // that GC efficiency is maximized and that we also meet a pause
464 // time. It's a triple nested loop. These loops are explained below
465 // from the inside-out :-)
466 //
467 // (a) The innermost loop will try to find the optimal young length
468 // for a fixed S-O length. It uses a binary search to speed up the
469 // process. We assume that, for a fixed S-O length, as we add more
470 // young regions to the CSet, the GC efficiency will only go up (I'll
471 // skip the proof). So, using a binary search to optimize this process
472 // makes perfect sense.
473 //
474 // (b) The middle loop will fix the S-O length before calling the
475 // innermost one. It will vary it between two parameters, increasing
476 // it by a given increment.
477 //
478 // (c) The outermost loop will call the middle loop three times.
479 // (1) The first time it will explore all possible S-O length values
480 // from 0 to as large as it can get, using a coarse increment (to
481 // quickly "home in" to where the optimal seems to be).
482 // (2) The second time it will explore the values around the optimal
483 // that was found by the first iteration using a fine increment.
484 // (3) Once the optimal config has been determined by the second
485 // iteration, we'll redo the calculation, but setting the S-O length
486 // to 95% of the optimal to make sure we sample the "area"
487 // around the optimal length to get up-to-date survival rate data
488 //
489 // Termination conditions for the iterations are several: the pause
490 // time is over the limit, we do not have enough to-space, etc.
492 void G1CollectorPolicy::calculate_young_list_target_config(size_t rs_lengths) {
493 guarantee( adaptive_young_list_length(), "pre-condition" );
495 double start_time_sec = os::elapsedTime();
496 size_t min_reserve_perc = MAX2((size_t)2, (size_t)G1ReservePercent);
497 min_reserve_perc = MIN2((size_t) 50, min_reserve_perc);
498 size_t reserve_regions =
499 (size_t) ((double) min_reserve_perc * (double) _g1->n_regions() / 100.0);
501 if (full_young_gcs() && _free_regions_at_end_of_collection > 0) {
502 // we are in fully-young mode and there are free regions in the heap
504 double survivor_regions_evac_time =
505 predict_survivor_regions_evac_time();
507 size_t min_so_length = 0;
508 size_t max_so_length = 0;
510 if (G1UseScanOnlyPrefix) {
511 if (_all_pause_times_ms->num() < 3) {
512 // we won't use a scan-only set at the beginning to allow the rest
513 // of the predictors to warm up
514 min_so_length = 0;
515 max_so_length = 0;
516 } else if (_cost_per_scan_only_region_ms_seq->num() < 3) {
517 // then, we'll only set the S-O set to 1 for a little bit of time,
518 // to get enough information on the scanning cost
519 min_so_length = 1;
520 max_so_length = 1;
521 } else if (_in_marking_window || _last_full_young_gc) {
522 // no S-O prefix during a marking phase either, as at the end
523 // of the marking phase we'll have to use a very small young
524 // length target to fill up the rest of the CSet with
525 // non-young regions and, if we have lots of scan-only regions
526 // left-over, we will not be able to add any more non-young
527 // regions.
528 min_so_length = 0;
529 max_so_length = 0;
530 } else {
531 // this is the common case; we'll never reach the maximum, we
532 // one of the end conditions will fire well before that
533 // (hopefully!)
534 min_so_length = 0;
535 max_so_length = _free_regions_at_end_of_collection - 1;
536 }
537 } else {
538 // no S-O prefix, as the switch is not set, but we still need to
539 // do one iteration to calculate the best young target that
540 // meets the pause time; this way we reuse the same code instead
541 // of replicating it
542 min_so_length = 0;
543 max_so_length = 0;
544 }
546 double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
547 size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
548 size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
549 size_t scanned_cards;
550 if (full_young_gcs())
551 scanned_cards = predict_young_card_num(adj_rs_lengths);
552 else
553 scanned_cards = predict_non_young_card_num(adj_rs_lengths);
554 // calculate this once, so that we don't have to recalculate it in
555 // the innermost loop
556 double base_time_ms = predict_base_elapsed_time_ms(pending_cards, scanned_cards)
557 + survivor_regions_evac_time;
558 // the result
559 size_t final_young_length = 0;
560 size_t final_so_length = 0;
561 double final_gc_eff = 0.0;
562 // we'll also keep track of how many times we go into the inner loop
563 // this is for profiling reasons
564 size_t calculations = 0;
566 // this determines which of the three iterations the outer loop is in
567 typedef enum {
568 pass_type_coarse,
569 pass_type_fine,
570 pass_type_final
571 } pass_type_t;
573 // range of the outer loop's iteration
574 size_t from_so_length = min_so_length;
575 size_t to_so_length = max_so_length;
576 guarantee( from_so_length <= to_so_length, "invariant" );
578 // this will keep the S-O length that's found by the second
579 // iteration of the outer loop; we'll keep it just in case the third
580 // iteration fails to find something
581 size_t fine_so_length = 0;
583 // the increment step for the coarse (first) iteration
584 size_t so_coarse_increments = 5;
586 // the common case, we'll start with the coarse iteration
587 pass_type_t pass = pass_type_coarse;
588 size_t so_length_incr = so_coarse_increments;
590 if (from_so_length == to_so_length) {
591 // not point in doing the coarse iteration, we'll go directly into
592 // the fine one (we essentially trying to find the optimal young
593 // length for a fixed S-O length).
594 so_length_incr = 1;
595 pass = pass_type_final;
596 } else if (to_so_length - from_so_length < 3 * so_coarse_increments) {
597 // again, the range is too short so no point in foind the coarse
598 // iteration either
599 so_length_incr = 1;
600 pass = pass_type_fine;
601 }
603 bool done = false;
604 // this is the outermost loop
605 while (!done) {
606 #ifdef TRACE_CALC_YOUNG_CONFIG
607 // leave this in for debugging, just in case
608 gclog_or_tty->print_cr("searching between " SIZE_FORMAT " and " SIZE_FORMAT
609 ", incr " SIZE_FORMAT ", pass %s",
610 from_so_length, to_so_length, so_length_incr,
611 (pass == pass_type_coarse) ? "coarse" :
612 (pass == pass_type_fine) ? "fine" : "final");
613 #endif // TRACE_CALC_YOUNG_CONFIG
615 size_t so_length = from_so_length;
616 size_t init_free_regions =
617 MAX2((size_t)0,
618 _free_regions_at_end_of_collection +
619 _scan_only_regions_at_end_of_collection - reserve_regions);
621 // this determines whether a configuration was found
622 bool gc_eff_set = false;
623 // this is the middle loop
624 while (so_length <= to_so_length) {
625 // base time, which excludes region-related time; again we
626 // calculate it once to avoid recalculating it in the
627 // innermost loop
628 double base_time_with_so_ms =
629 base_time_ms + predict_scan_only_time_ms(so_length);
630 // it's already over the pause target, go around
631 if (base_time_with_so_ms > target_pause_time_ms)
632 break;
634 size_t starting_young_length = so_length+1;
636 // we make sure that the short young length that makes sense
637 // (one more than the S-O length) is feasible
638 size_t min_young_length = starting_young_length;
639 double min_gc_eff;
640 bool min_ok;
641 ++calculations;
642 min_ok = predict_gc_eff(min_young_length, so_length,
643 base_time_with_so_ms,
644 init_free_regions, target_pause_time_ms,
645 &min_gc_eff);
647 if (min_ok) {
648 // the shortest young length is indeed feasible; we'll know
649 // set up the max young length and we'll do a binary search
650 // between min_young_length and max_young_length
651 size_t max_young_length = _free_regions_at_end_of_collection - 1;
652 double max_gc_eff = 0.0;
653 bool max_ok = false;
655 // the innermost loop! (finally!)
656 while (max_young_length > min_young_length) {
657 // we'll make sure that min_young_length is always at a
658 // feasible config
659 guarantee( min_ok, "invariant" );
661 ++calculations;
662 max_ok = predict_gc_eff(max_young_length, so_length,
663 base_time_with_so_ms,
664 init_free_regions, target_pause_time_ms,
665 &max_gc_eff);
667 size_t diff = (max_young_length - min_young_length) / 2;
668 if (max_ok) {
669 min_young_length = max_young_length;
670 min_gc_eff = max_gc_eff;
671 min_ok = true;
672 }
673 max_young_length = min_young_length + diff;
674 }
676 // the innermost loop found a config
677 guarantee( min_ok, "invariant" );
678 if (min_gc_eff > final_gc_eff) {
679 // it's the best config so far, so we'll keep it
680 final_gc_eff = min_gc_eff;
681 final_young_length = min_young_length;
682 final_so_length = so_length;
683 gc_eff_set = true;
684 }
685 }
687 // incremental the fixed S-O length and go around
688 so_length += so_length_incr;
689 }
691 // this is the end of the outermost loop and we need to decide
692 // what to do during the next iteration
693 if (pass == pass_type_coarse) {
694 // we just did the coarse pass (first iteration)
696 if (!gc_eff_set)
697 // we didn't find a feasible config so we'll just bail out; of
698 // course, it might be the case that we missed it; but I'd say
699 // it's a bit unlikely
700 done = true;
701 else {
702 // We did find a feasible config with optimal GC eff during
703 // the first pass. So the second pass we'll only consider the
704 // S-O lengths around that config with a fine increment.
706 guarantee( so_length_incr == so_coarse_increments, "invariant" );
707 guarantee( final_so_length >= min_so_length, "invariant" );
709 #ifdef TRACE_CALC_YOUNG_CONFIG
710 // leave this in for debugging, just in case
711 gclog_or_tty->print_cr(" coarse pass: SO length " SIZE_FORMAT,
712 final_so_length);
713 #endif // TRACE_CALC_YOUNG_CONFIG
715 from_so_length =
716 (final_so_length - min_so_length > so_coarse_increments) ?
717 final_so_length - so_coarse_increments + 1 : min_so_length;
718 to_so_length =
719 (max_so_length - final_so_length > so_coarse_increments) ?
720 final_so_length + so_coarse_increments - 1 : max_so_length;
722 pass = pass_type_fine;
723 so_length_incr = 1;
724 }
725 } else if (pass == pass_type_fine) {
726 // we just finished the second pass
728 if (!gc_eff_set) {
729 // we didn't find a feasible config (yes, it's possible;
730 // notice that, sometimes, we go directly into the fine
731 // iteration and skip the coarse one) so we bail out
732 done = true;
733 } else {
734 // We did find a feasible config with optimal GC eff
735 guarantee( so_length_incr == 1, "invariant" );
737 if (final_so_length == 0) {
738 // The config is of an empty S-O set, so we'll just bail out
739 done = true;
740 } else {
741 // we'll go around once more, setting the S-O length to 95%
742 // of the optimal
743 size_t new_so_length = 950 * final_so_length / 1000;
745 #ifdef TRACE_CALC_YOUNG_CONFIG
746 // leave this in for debugging, just in case
747 gclog_or_tty->print_cr(" fine pass: SO length " SIZE_FORMAT
748 ", setting it to " SIZE_FORMAT,
749 final_so_length, new_so_length);
750 #endif // TRACE_CALC_YOUNG_CONFIG
752 from_so_length = new_so_length;
753 to_so_length = new_so_length;
754 fine_so_length = final_so_length;
756 pass = pass_type_final;
757 }
758 }
759 } else if (pass == pass_type_final) {
760 // we just finished the final (third) pass
762 if (!gc_eff_set)
763 // we didn't find a feasible config, so we'll just use the one
764 // we found during the second pass, which we saved
765 final_so_length = fine_so_length;
767 // and we're done!
768 done = true;
769 } else {
770 guarantee( false, "should never reach here" );
771 }
773 // we now go around the outermost loop
774 }
776 // we should have at least one region in the target young length
777 _young_list_target_length =
778 MAX2((size_t) 1, final_young_length + _recorded_survivor_regions);
779 if (final_so_length >= final_young_length)
780 // and we need to ensure that the S-O length is not greater than
781 // the target young length (this is being a bit careful)
782 final_so_length = 0;
783 _young_list_so_prefix_length = final_so_length;
784 guarantee( !_in_marking_window || !_last_full_young_gc ||
785 _young_list_so_prefix_length == 0, "invariant" );
787 // let's keep an eye of how long we spend on this calculation
788 // right now, I assume that we'll print it when we need it; we
789 // should really adde it to the breakdown of a pause
790 double end_time_sec = os::elapsedTime();
791 double elapsed_time_ms = (end_time_sec - start_time_sec) * 1000.0;
793 #ifdef TRACE_CALC_YOUNG_CONFIG
794 // leave this in for debugging, just in case
795 gclog_or_tty->print_cr("target = %1.1lf ms, young = " SIZE_FORMAT
796 ", SO = " SIZE_FORMAT ", "
797 "elapsed %1.2lf ms, calcs: " SIZE_FORMAT " (%s%s) "
798 SIZE_FORMAT SIZE_FORMAT,
799 target_pause_time_ms,
800 _young_list_target_length - _young_list_so_prefix_length,
801 _young_list_so_prefix_length,
802 elapsed_time_ms,
803 calculations,
804 full_young_gcs() ? "full" : "partial",
805 during_initial_mark_pause() ? " i-m" : "",
806 _in_marking_window,
807 _in_marking_window_im);
808 #endif // TRACE_CALC_YOUNG_CONFIG
810 if (_young_list_target_length < _young_list_min_length) {
811 // bummer; this means that, if we do a pause when the optimal
812 // config dictates, we'll violate the pause spacing target (the
813 // min length was calculate based on the application's current
814 // alloc rate);
816 // so, we have to bite the bullet, and allocate the minimum
817 // number. We'll violate our target, but we just can't meet it.
819 size_t so_length = 0;
820 // a note further up explains why we do not want an S-O length
821 // during marking
822 if (!_in_marking_window && !_last_full_young_gc)
823 // but we can still try to see whether we can find an optimal
824 // S-O length
825 so_length = calculate_optimal_so_length(_young_list_min_length);
827 #ifdef TRACE_CALC_YOUNG_CONFIG
828 // leave this in for debugging, just in case
829 gclog_or_tty->print_cr("adjusted target length from "
830 SIZE_FORMAT " to " SIZE_FORMAT
831 ", SO " SIZE_FORMAT,
832 _young_list_target_length, _young_list_min_length,
833 so_length);
834 #endif // TRACE_CALC_YOUNG_CONFIG
836 _young_list_target_length =
837 MAX2(_young_list_min_length, (size_t)1);
838 _young_list_so_prefix_length = so_length;
839 }
840 } else {
841 // we are in a partially-young mode or we've run out of regions (due
842 // to evacuation failure)
844 #ifdef TRACE_CALC_YOUNG_CONFIG
845 // leave this in for debugging, just in case
846 gclog_or_tty->print_cr("(partial) setting target to " SIZE_FORMAT
847 ", SO " SIZE_FORMAT,
848 _young_list_min_length, 0);
849 #endif // TRACE_CALC_YOUNG_CONFIG
851 // we'll do the pause as soon as possible and with no S-O prefix
852 // (see above for the reasons behind the latter)
853 _young_list_target_length =
854 MAX2(_young_list_min_length, (size_t) 1);
855 _young_list_so_prefix_length = 0;
856 }
858 _rs_lengths_prediction = rs_lengths;
859 }
861 // This is used by: calculate_optimal_so_length(length). It returns
862 // the GC eff and predicted pause time for a particular config
863 void
864 G1CollectorPolicy::predict_gc_eff(size_t young_length,
865 size_t so_length,
866 double base_time_ms,
867 double* ret_gc_eff,
868 double* ret_pause_time_ms) {
869 double so_time_ms = predict_scan_only_time_ms(so_length);
870 double accum_surv_rate_adj = 0.0;
871 if (so_length > 0)
872 accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
873 double accum_surv_rate =
874 accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
875 size_t bytes_to_copy =
876 (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
877 double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
878 double young_other_time_ms =
879 predict_young_other_time_ms(young_length - so_length);
880 double pause_time_ms =
881 base_time_ms + so_time_ms + copy_time_ms + young_other_time_ms;
882 size_t reclaimed_bytes =
883 (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
884 double gc_eff = (double) reclaimed_bytes / pause_time_ms;
886 *ret_gc_eff = gc_eff;
887 *ret_pause_time_ms = pause_time_ms;
888 }
890 // This is used by: calculate_young_list_target_config(rs_length). It
891 // returns the GC eff of a particular config. It returns false if that
892 // config violates any of the end conditions of the search in the
893 // calling method, or true upon success. The end conditions were put
894 // here since it's called twice and it was best not to replicate them
895 // in the caller. Also, passing the parameteres avoids having to
896 // recalculate them in the innermost loop.
897 bool
898 G1CollectorPolicy::predict_gc_eff(size_t young_length,
899 size_t so_length,
900 double base_time_with_so_ms,
901 size_t init_free_regions,
902 double target_pause_time_ms,
903 double* ret_gc_eff) {
904 *ret_gc_eff = 0.0;
906 if (young_length >= init_free_regions)
907 // end condition 1: not enough space for the young regions
908 return false;
910 double accum_surv_rate_adj = 0.0;
911 if (so_length > 0)
912 accum_surv_rate_adj = accum_yg_surv_rate_pred((int)(so_length - 1));
913 double accum_surv_rate =
914 accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
915 size_t bytes_to_copy =
916 (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
917 double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
918 double young_other_time_ms =
919 predict_young_other_time_ms(young_length - so_length);
920 double pause_time_ms =
921 base_time_with_so_ms + copy_time_ms + young_other_time_ms;
923 if (pause_time_ms > target_pause_time_ms)
924 // end condition 2: over the target pause time
925 return false;
927 size_t reclaimed_bytes =
928 (young_length - so_length) * HeapRegion::GrainBytes - bytes_to_copy;
929 size_t free_bytes =
930 (init_free_regions - young_length) * HeapRegion::GrainBytes;
932 if ((2.0 + sigma()) * (double) bytes_to_copy > (double) free_bytes)
933 // end condition 3: out of to-space (conservatively)
934 return false;
936 // success!
937 double gc_eff = (double) reclaimed_bytes / pause_time_ms;
938 *ret_gc_eff = gc_eff;
940 return true;
941 }
943 double G1CollectorPolicy::predict_survivor_regions_evac_time() {
944 double survivor_regions_evac_time = 0.0;
945 for (HeapRegion * r = _recorded_survivor_head;
946 r != NULL && r != _recorded_survivor_tail->get_next_young_region();
947 r = r->get_next_young_region()) {
948 survivor_regions_evac_time += predict_region_elapsed_time_ms(r, true);
949 }
950 return survivor_regions_evac_time;
951 }
953 void G1CollectorPolicy::check_prediction_validity() {
954 guarantee( adaptive_young_list_length(), "should not call this otherwise" );
956 size_t rs_lengths = _g1->young_list_sampled_rs_lengths();
957 if (rs_lengths > _rs_lengths_prediction) {
958 // add 10% to avoid having to recalculate often
959 size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;
960 calculate_young_list_target_config(rs_lengths_prediction);
961 }
962 }
964 HeapWord* G1CollectorPolicy::mem_allocate_work(size_t size,
965 bool is_tlab,
966 bool* gc_overhead_limit_was_exceeded) {
967 guarantee(false, "Not using this policy feature yet.");
968 return NULL;
969 }
971 // This method controls how a collector handles one or more
972 // of its generations being fully allocated.
973 HeapWord* G1CollectorPolicy::satisfy_failed_allocation(size_t size,
974 bool is_tlab) {
975 guarantee(false, "Not using this policy feature yet.");
976 return NULL;
977 }
980 #ifndef PRODUCT
981 bool G1CollectorPolicy::verify_young_ages() {
982 HeapRegion* head = _g1->young_list_first_region();
983 return
984 verify_young_ages(head, _short_lived_surv_rate_group);
985 // also call verify_young_ages on any additional surv rate groups
986 }
988 bool
989 G1CollectorPolicy::verify_young_ages(HeapRegion* head,
990 SurvRateGroup *surv_rate_group) {
991 guarantee( surv_rate_group != NULL, "pre-condition" );
993 const char* name = surv_rate_group->name();
994 bool ret = true;
995 int prev_age = -1;
997 for (HeapRegion* curr = head;
998 curr != NULL;
999 curr = curr->get_next_young_region()) {
1000 SurvRateGroup* group = curr->surv_rate_group();
1001 if (group == NULL && !curr->is_survivor()) {
1002 gclog_or_tty->print_cr("## %s: encountered NULL surv_rate_group", name);
1003 ret = false;
1004 }
1006 if (surv_rate_group == group) {
1007 int age = curr->age_in_surv_rate_group();
1009 if (age < 0) {
1010 gclog_or_tty->print_cr("## %s: encountered negative age", name);
1011 ret = false;
1012 }
1014 if (age <= prev_age) {
1015 gclog_or_tty->print_cr("## %s: region ages are not strictly increasing "
1016 "(%d, %d)", name, age, prev_age);
1017 ret = false;
1018 }
1019 prev_age = age;
1020 }
1021 }
1023 return ret;
1024 }
1025 #endif // PRODUCT
1027 void G1CollectorPolicy::record_full_collection_start() {
1028 _cur_collection_start_sec = os::elapsedTime();
1029 // Release the future to-space so that it is available for compaction into.
1030 _g1->set_full_collection();
1031 }
1033 void G1CollectorPolicy::record_full_collection_end() {
1034 // Consider this like a collection pause for the purposes of allocation
1035 // since last pause.
1036 double end_sec = os::elapsedTime();
1037 double full_gc_time_sec = end_sec - _cur_collection_start_sec;
1038 double full_gc_time_ms = full_gc_time_sec * 1000.0;
1040 _all_full_gc_times_ms->add(full_gc_time_ms);
1042 update_recent_gc_times(end_sec, full_gc_time_ms);
1044 _g1->clear_full_collection();
1046 // "Nuke" the heuristics that control the fully/partially young GC
1047 // transitions and make sure we start with fully young GCs after the
1048 // Full GC.
1049 set_full_young_gcs(true);
1050 _last_full_young_gc = false;
1051 _should_revert_to_full_young_gcs = false;
1052 clear_initiate_conc_mark_if_possible();
1053 clear_during_initial_mark_pause();
1054 _known_garbage_bytes = 0;
1055 _known_garbage_ratio = 0.0;
1056 _in_marking_window = false;
1057 _in_marking_window_im = false;
1059 _short_lived_surv_rate_group->record_scan_only_prefix(0);
1060 _short_lived_surv_rate_group->start_adding_regions();
1061 // also call this on any additional surv rate groups
1063 record_survivor_regions(0, NULL, NULL);
1065 _prev_region_num_young = _region_num_young;
1066 _prev_region_num_tenured = _region_num_tenured;
1068 _free_regions_at_end_of_collection = _g1->free_regions();
1069 _scan_only_regions_at_end_of_collection = 0;
1070 // Reset survivors SurvRateGroup.
1071 _survivor_surv_rate_group->reset();
1072 calculate_young_list_min_length();
1073 calculate_young_list_target_config();
1074 }
1076 void G1CollectorPolicy::record_before_bytes(size_t bytes) {
1077 _bytes_in_to_space_before_gc += bytes;
1078 }
1080 void G1CollectorPolicy::record_after_bytes(size_t bytes) {
1081 _bytes_in_to_space_after_gc += bytes;
1082 }
1084 void G1CollectorPolicy::record_stop_world_start() {
1085 _stop_world_start = os::elapsedTime();
1086 }
1088 void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
1089 size_t start_used) {
1090 if (PrintGCDetails) {
1091 gclog_or_tty->stamp(PrintGCTimeStamps);
1092 gclog_or_tty->print("[GC pause");
1093 if (in_young_gc_mode())
1094 gclog_or_tty->print(" (%s)", full_young_gcs() ? "young" : "partial");
1095 }
1097 assert(_g1->used_regions() == _g1->recalculate_used_regions(),
1098 "sanity");
1099 assert(_g1->used() == _g1->recalculate_used(), "sanity");
1101 double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
1102 _all_stop_world_times_ms->add(s_w_t_ms);
1103 _stop_world_start = 0.0;
1105 _cur_collection_start_sec = start_time_sec;
1106 _cur_collection_pause_used_at_start_bytes = start_used;
1107 _cur_collection_pause_used_regions_at_start = _g1->used_regions();
1108 _pending_cards = _g1->pending_card_num();
1109 _max_pending_cards = _g1->max_pending_card_num();
1111 _bytes_in_to_space_before_gc = 0;
1112 _bytes_in_to_space_after_gc = 0;
1113 _bytes_in_collection_set_before_gc = 0;
1115 #ifdef DEBUG
1116 // initialise these to something well known so that we can spot
1117 // if they are not set properly
1119 for (int i = 0; i < _parallel_gc_threads; ++i) {
1120 _par_last_ext_root_scan_times_ms[i] = -666.0;
1121 _par_last_mark_stack_scan_times_ms[i] = -666.0;
1122 _par_last_scan_only_times_ms[i] = -666.0;
1123 _par_last_scan_only_regions_scanned[i] = -666.0;
1124 _par_last_update_rs_start_times_ms[i] = -666.0;
1125 _par_last_update_rs_times_ms[i] = -666.0;
1126 _par_last_update_rs_processed_buffers[i] = -666.0;
1127 _par_last_scan_rs_start_times_ms[i] = -666.0;
1128 _par_last_scan_rs_times_ms[i] = -666.0;
1129 _par_last_scan_new_refs_times_ms[i] = -666.0;
1130 _par_last_obj_copy_times_ms[i] = -666.0;
1131 _par_last_termination_times_ms[i] = -666.0;
1132 }
1133 #endif
1135 for (int i = 0; i < _aux_num; ++i) {
1136 _cur_aux_times_ms[i] = 0.0;
1137 _cur_aux_times_set[i] = false;
1138 }
1140 _satb_drain_time_set = false;
1141 _last_satb_drain_processed_buffers = -1;
1143 if (in_young_gc_mode())
1144 _last_young_gc_full = false;
1147 // do that for any other surv rate groups
1148 _short_lived_surv_rate_group->stop_adding_regions();
1149 size_t short_lived_so_length = _young_list_so_prefix_length;
1150 _short_lived_surv_rate_group->record_scan_only_prefix(short_lived_so_length);
1151 tag_scan_only(short_lived_so_length);
1152 _survivors_age_table.clear();
1154 assert( verify_young_ages(), "region age verification" );
1155 }
1157 void G1CollectorPolicy::tag_scan_only(size_t short_lived_scan_only_length) {
1158 // done in a way that it can be extended for other surv rate groups too...
1160 HeapRegion* head = _g1->young_list_first_region();
1161 bool finished_short_lived = (short_lived_scan_only_length == 0);
1163 if (finished_short_lived)
1164 return;
1166 for (HeapRegion* curr = head;
1167 curr != NULL;
1168 curr = curr->get_next_young_region()) {
1169 SurvRateGroup* surv_rate_group = curr->surv_rate_group();
1170 int age = curr->age_in_surv_rate_group();
1172 if (surv_rate_group == _short_lived_surv_rate_group) {
1173 if ((size_t)age < short_lived_scan_only_length)
1174 curr->set_scan_only();
1175 else
1176 finished_short_lived = true;
1177 }
1180 if (finished_short_lived)
1181 return;
1182 }
1184 guarantee( false, "we should never reach here" );
1185 }
1187 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
1188 _mark_closure_time_ms = mark_closure_time_ms;
1189 }
1191 void G1CollectorPolicy::record_concurrent_mark_init_start() {
1192 _mark_init_start_sec = os::elapsedTime();
1193 guarantee(!in_young_gc_mode(), "should not do be here in young GC mode");
1194 }
1196 void G1CollectorPolicy::record_concurrent_mark_init_end_pre(double
1197 mark_init_elapsed_time_ms) {
1198 _during_marking = true;
1199 assert(!initiate_conc_mark_if_possible(), "we should have cleared it by now");
1200 clear_during_initial_mark_pause();
1201 _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
1202 }
1204 void G1CollectorPolicy::record_concurrent_mark_init_end() {
1205 double end_time_sec = os::elapsedTime();
1206 double elapsed_time_ms = (end_time_sec - _mark_init_start_sec) * 1000.0;
1207 _concurrent_mark_init_times_ms->add(elapsed_time_ms);
1208 record_concurrent_mark_init_end_pre(elapsed_time_ms);
1210 _mmu_tracker->add_pause(_mark_init_start_sec, end_time_sec, true);
1211 }
1213 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
1214 _mark_remark_start_sec = os::elapsedTime();
1215 _during_marking = false;
1216 }
1218 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
1219 double end_time_sec = os::elapsedTime();
1220 double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
1221 _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
1222 _cur_mark_stop_world_time_ms += elapsed_time_ms;
1223 _prev_collection_pause_end_ms += elapsed_time_ms;
1225 _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
1226 }
1228 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
1229 _mark_cleanup_start_sec = os::elapsedTime();
1230 }
1232 void
1233 G1CollectorPolicy::record_concurrent_mark_cleanup_end(size_t freed_bytes,
1234 size_t max_live_bytes) {
1235 record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
1236 record_concurrent_mark_cleanup_end_work2();
1237 }
1239 void
1240 G1CollectorPolicy::
1241 record_concurrent_mark_cleanup_end_work1(size_t freed_bytes,
1242 size_t max_live_bytes) {
1243 if (_n_marks < 2) _n_marks++;
1244 if (G1PolicyVerbose > 0)
1245 gclog_or_tty->print_cr("At end of marking, max_live is " SIZE_FORMAT " MB "
1246 " (of " SIZE_FORMAT " MB heap).",
1247 max_live_bytes/M, _g1->capacity()/M);
1248 }
1250 // The important thing about this is that it includes "os::elapsedTime".
1251 void G1CollectorPolicy::record_concurrent_mark_cleanup_end_work2() {
1252 double end_time_sec = os::elapsedTime();
1253 double elapsed_time_ms = (end_time_sec - _mark_cleanup_start_sec)*1000.0;
1254 _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
1255 _cur_mark_stop_world_time_ms += elapsed_time_ms;
1256 _prev_collection_pause_end_ms += elapsed_time_ms;
1258 _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_time_sec, true);
1260 _num_markings++;
1262 // We did a marking, so reset the "since_last_mark" variables.
1263 double considerConcMarkCost = 1.0;
1264 // If there are available processors, concurrent activity is free...
1265 if (Threads::number_of_non_daemon_threads() * 2 <
1266 os::active_processor_count()) {
1267 considerConcMarkCost = 0.0;
1268 }
1269 _n_pauses_at_mark_end = _n_pauses;
1270 _n_marks_since_last_pause++;
1271 }
1273 void
1274 G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
1275 if (in_young_gc_mode()) {
1276 _should_revert_to_full_young_gcs = false;
1277 _last_full_young_gc = true;
1278 _in_marking_window = false;
1279 if (adaptive_young_list_length())
1280 calculate_young_list_target_config();
1281 }
1282 }
1284 void G1CollectorPolicy::record_concurrent_pause() {
1285 if (_stop_world_start > 0.0) {
1286 double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
1287 _all_yield_times_ms->add(yield_ms);
1288 }
1289 }
1291 void G1CollectorPolicy::record_concurrent_pause_end() {
1292 }
1294 void G1CollectorPolicy::record_collection_pause_end_CH_strong_roots() {
1295 _cur_CH_strong_roots_end_sec = os::elapsedTime();
1296 _cur_CH_strong_roots_dur_ms =
1297 (_cur_CH_strong_roots_end_sec - _cur_collection_start_sec) * 1000.0;
1298 }
1300 void G1CollectorPolicy::record_collection_pause_end_G1_strong_roots() {
1301 _cur_G1_strong_roots_end_sec = os::elapsedTime();
1302 _cur_G1_strong_roots_dur_ms =
1303 (_cur_G1_strong_roots_end_sec - _cur_CH_strong_roots_end_sec) * 1000.0;
1304 }
1306 template<class T>
1307 T sum_of(T* sum_arr, int start, int n, int N) {
1308 T sum = (T)0;
1309 for (int i = 0; i < n; i++) {
1310 int j = (start + i) % N;
1311 sum += sum_arr[j];
1312 }
1313 return sum;
1314 }
1316 void G1CollectorPolicy::print_par_stats (int level,
1317 const char* str,
1318 double* data,
1319 bool summary) {
1320 double min = data[0], max = data[0];
1321 double total = 0.0;
1322 int j;
1323 for (j = 0; j < level; ++j)
1324 gclog_or_tty->print(" ");
1325 gclog_or_tty->print("[%s (ms):", str);
1326 for (uint i = 0; i < ParallelGCThreads; ++i) {
1327 double val = data[i];
1328 if (val < min)
1329 min = val;
1330 if (val > max)
1331 max = val;
1332 total += val;
1333 gclog_or_tty->print(" %3.1lf", val);
1334 }
1335 if (summary) {
1336 gclog_or_tty->print_cr("");
1337 double avg = total / (double) ParallelGCThreads;
1338 gclog_or_tty->print(" ");
1339 for (j = 0; j < level; ++j)
1340 gclog_or_tty->print(" ");
1341 gclog_or_tty->print("Avg: %5.1lf, Min: %5.1lf, Max: %5.1lf",
1342 avg, min, max);
1343 }
1344 gclog_or_tty->print_cr("]");
1345 }
1347 void G1CollectorPolicy::print_par_buffers (int level,
1348 const char* str,
1349 double* data,
1350 bool summary) {
1351 double min = data[0], max = data[0];
1352 double total = 0.0;
1353 int j;
1354 for (j = 0; j < level; ++j)
1355 gclog_or_tty->print(" ");
1356 gclog_or_tty->print("[%s :", str);
1357 for (uint i = 0; i < ParallelGCThreads; ++i) {
1358 double val = data[i];
1359 if (val < min)
1360 min = val;
1361 if (val > max)
1362 max = val;
1363 total += val;
1364 gclog_or_tty->print(" %d", (int) val);
1365 }
1366 if (summary) {
1367 gclog_or_tty->print_cr("");
1368 double avg = total / (double) ParallelGCThreads;
1369 gclog_or_tty->print(" ");
1370 for (j = 0; j < level; ++j)
1371 gclog_or_tty->print(" ");
1372 gclog_or_tty->print("Sum: %d, Avg: %d, Min: %d, Max: %d",
1373 (int)total, (int)avg, (int)min, (int)max);
1374 }
1375 gclog_or_tty->print_cr("]");
1376 }
1378 void G1CollectorPolicy::print_stats (int level,
1379 const char* str,
1380 double value) {
1381 for (int j = 0; j < level; ++j)
1382 gclog_or_tty->print(" ");
1383 gclog_or_tty->print_cr("[%s: %5.1lf ms]", str, value);
1384 }
1386 void G1CollectorPolicy::print_stats (int level,
1387 const char* str,
1388 int value) {
1389 for (int j = 0; j < level; ++j)
1390 gclog_or_tty->print(" ");
1391 gclog_or_tty->print_cr("[%s: %d]", str, value);
1392 }
1394 double G1CollectorPolicy::avg_value (double* data) {
1395 if (ParallelGCThreads > 0) {
1396 double ret = 0.0;
1397 for (uint i = 0; i < ParallelGCThreads; ++i)
1398 ret += data[i];
1399 return ret / (double) ParallelGCThreads;
1400 } else {
1401 return data[0];
1402 }
1403 }
1405 double G1CollectorPolicy::max_value (double* data) {
1406 if (ParallelGCThreads > 0) {
1407 double ret = data[0];
1408 for (uint i = 1; i < ParallelGCThreads; ++i)
1409 if (data[i] > ret)
1410 ret = data[i];
1411 return ret;
1412 } else {
1413 return data[0];
1414 }
1415 }
1417 double G1CollectorPolicy::sum_of_values (double* data) {
1418 if (ParallelGCThreads > 0) {
1419 double sum = 0.0;
1420 for (uint i = 0; i < ParallelGCThreads; i++)
1421 sum += data[i];
1422 return sum;
1423 } else {
1424 return data[0];
1425 }
1426 }
1428 double G1CollectorPolicy::max_sum (double* data1,
1429 double* data2) {
1430 double ret = data1[0] + data2[0];
1432 if (ParallelGCThreads > 0) {
1433 for (uint i = 1; i < ParallelGCThreads; ++i) {
1434 double data = data1[i] + data2[i];
1435 if (data > ret)
1436 ret = data;
1437 }
1438 }
1439 return ret;
1440 }
1442 // Anything below that is considered to be zero
1443 #define MIN_TIMER_GRANULARITY 0.0000001
1445 void G1CollectorPolicy::record_collection_pause_end(bool abandoned) {
1446 double end_time_sec = os::elapsedTime();
1447 double elapsed_ms = _last_pause_time_ms;
1448 bool parallel = ParallelGCThreads > 0;
1449 double evac_ms = (end_time_sec - _cur_G1_strong_roots_end_sec) * 1000.0;
1450 size_t rs_size =
1451 _cur_collection_pause_used_regions_at_start - collection_set_size();
1452 size_t cur_used_bytes = _g1->used();
1453 assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
1454 bool last_pause_included_initial_mark = false;
1455 bool update_stats = !abandoned && !_g1->evacuation_failed();
1457 #ifndef PRODUCT
1458 if (G1YoungSurvRateVerbose) {
1459 gclog_or_tty->print_cr("");
1460 _short_lived_surv_rate_group->print();
1461 // do that for any other surv rate groups too
1462 }
1463 #endif // PRODUCT
1465 if (in_young_gc_mode()) {
1466 last_pause_included_initial_mark = during_initial_mark_pause();
1467 if (last_pause_included_initial_mark)
1468 record_concurrent_mark_init_end_pre(0.0);
1470 size_t min_used_targ =
1471 (_g1->capacity() / 100) * InitiatingHeapOccupancyPercent;
1474 if (!_g1->mark_in_progress() && !_last_full_young_gc) {
1475 assert(!last_pause_included_initial_mark, "invariant");
1476 if (cur_used_bytes > min_used_targ &&
1477 cur_used_bytes > _prev_collection_pause_used_at_end_bytes) {
1478 assert(!during_initial_mark_pause(), "we should not see this here");
1480 // Note: this might have already been set, if during the last
1481 // pause we decided to start a cycle but at the beginning of
1482 // this pause we decided to postpone it. That's OK.
1483 set_initiate_conc_mark_if_possible();
1484 }
1485 }
1487 _prev_collection_pause_used_at_end_bytes = cur_used_bytes;
1488 }
1490 _mmu_tracker->add_pause(end_time_sec - elapsed_ms/1000.0,
1491 end_time_sec, false);
1493 guarantee(_cur_collection_pause_used_regions_at_start >=
1494 collection_set_size(),
1495 "Negative RS size?");
1497 // This assert is exempted when we're doing parallel collection pauses,
1498 // because the fragmentation caused by the parallel GC allocation buffers
1499 // can lead to more memory being used during collection than was used
1500 // before. Best leave this out until the fragmentation problem is fixed.
1501 // Pauses in which evacuation failed can also lead to negative
1502 // collections, since no space is reclaimed from a region containing an
1503 // object whose evacuation failed.
1504 // Further, we're now always doing parallel collection. But I'm still
1505 // leaving this here as a placeholder for a more precise assertion later.
1506 // (DLD, 10/05.)
1507 assert((true || parallel) // Always using GC LABs now.
1508 || _g1->evacuation_failed()
1509 || _cur_collection_pause_used_at_start_bytes >= cur_used_bytes,
1510 "Negative collection");
1512 size_t freed_bytes =
1513 _cur_collection_pause_used_at_start_bytes - cur_used_bytes;
1514 size_t surviving_bytes = _collection_set_bytes_used_before - freed_bytes;
1515 double survival_fraction =
1516 (double)surviving_bytes/
1517 (double)_collection_set_bytes_used_before;
1519 _n_pauses++;
1521 if (update_stats) {
1522 _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
1523 _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
1524 _recent_evac_times_ms->add(evac_ms);
1525 _recent_pause_times_ms->add(elapsed_ms);
1527 _recent_rs_sizes->add(rs_size);
1529 // We exempt parallel collection from this check because Alloc Buffer
1530 // fragmentation can produce negative collections. Same with evac
1531 // failure.
1532 // Further, we're now always doing parallel collection. But I'm still
1533 // leaving this here as a placeholder for a more precise assertion later.
1534 // (DLD, 10/05.
1535 assert((true || parallel)
1536 || _g1->evacuation_failed()
1537 || surviving_bytes <= _collection_set_bytes_used_before,
1538 "Or else negative collection!");
1539 _recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
1540 _recent_CS_bytes_surviving->add(surviving_bytes);
1542 // this is where we update the allocation rate of the application
1543 double app_time_ms =
1544 (_cur_collection_start_sec * 1000.0 - _prev_collection_pause_end_ms);
1545 if (app_time_ms < MIN_TIMER_GRANULARITY) {
1546 // This usually happens due to the timer not having the required
1547 // granularity. Some Linuxes are the usual culprits.
1548 // We'll just set it to something (arbitrarily) small.
1549 app_time_ms = 1.0;
1550 }
1551 size_t regions_allocated =
1552 (_region_num_young - _prev_region_num_young) +
1553 (_region_num_tenured - _prev_region_num_tenured);
1554 double alloc_rate_ms = (double) regions_allocated / app_time_ms;
1555 _alloc_rate_ms_seq->add(alloc_rate_ms);
1556 _prev_region_num_young = _region_num_young;
1557 _prev_region_num_tenured = _region_num_tenured;
1559 double interval_ms =
1560 (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
1561 update_recent_gc_times(end_time_sec, elapsed_ms);
1562 _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
1563 if (recent_avg_pause_time_ratio() < 0.0 ||
1564 (recent_avg_pause_time_ratio() - 1.0 > 0.0)) {
1565 #ifndef PRODUCT
1566 // Dump info to allow post-facto debugging
1567 gclog_or_tty->print_cr("recent_avg_pause_time_ratio() out of bounds");
1568 gclog_or_tty->print_cr("-------------------------------------------");
1569 gclog_or_tty->print_cr("Recent GC Times (ms):");
1570 _recent_gc_times_ms->dump();
1571 gclog_or_tty->print_cr("(End Time=%3.3f) Recent GC End Times (s):", end_time_sec);
1572 _recent_prev_end_times_for_all_gcs_sec->dump();
1573 gclog_or_tty->print_cr("GC = %3.3f, Interval = %3.3f, Ratio = %3.3f",
1574 _recent_gc_times_ms->sum(), interval_ms, recent_avg_pause_time_ratio());
1575 // In debug mode, terminate the JVM if the user wants to debug at this point.
1576 assert(!G1FailOnFPError, "Debugging data for CR 6898948 has been dumped above");
1577 #endif // !PRODUCT
1578 // Clip ratio between 0.0 and 1.0, and continue. This will be fixed in
1579 // CR 6902692 by redoing the manner in which the ratio is incrementally computed.
1580 if (_recent_avg_pause_time_ratio < 0.0) {
1581 _recent_avg_pause_time_ratio = 0.0;
1582 } else {
1583 assert(_recent_avg_pause_time_ratio - 1.0 > 0.0, "Ctl-point invariant");
1584 _recent_avg_pause_time_ratio = 1.0;
1585 }
1586 }
1587 }
1589 if (G1PolicyVerbose > 1) {
1590 gclog_or_tty->print_cr(" Recording collection pause(%d)", _n_pauses);
1591 }
1593 PauseSummary* summary;
1594 if (abandoned) {
1595 summary = _abandoned_summary;
1596 } else {
1597 summary = _summary;
1598 }
1600 double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
1601 double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
1602 double scan_only_time = avg_value(_par_last_scan_only_times_ms);
1603 double scan_only_regions_scanned =
1604 sum_of_values(_par_last_scan_only_regions_scanned);
1605 double update_rs_time = avg_value(_par_last_update_rs_times_ms);
1606 double update_rs_processed_buffers =
1607 sum_of_values(_par_last_update_rs_processed_buffers);
1608 double scan_rs_time = avg_value(_par_last_scan_rs_times_ms);
1609 double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
1610 double termination_time = avg_value(_par_last_termination_times_ms);
1612 double parallel_other_time = _cur_collection_par_time_ms -
1613 (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
1614 scan_only_time + scan_rs_time + obj_copy_time + termination_time);
1615 if (update_stats) {
1616 MainBodySummary* body_summary = summary->main_body_summary();
1617 guarantee(body_summary != NULL, "should not be null!");
1619 if (_satb_drain_time_set)
1620 body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
1621 else
1622 body_summary->record_satb_drain_time_ms(0.0);
1623 body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
1624 body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
1625 body_summary->record_scan_only_time_ms(scan_only_time);
1626 body_summary->record_update_rs_time_ms(update_rs_time);
1627 body_summary->record_scan_rs_time_ms(scan_rs_time);
1628 body_summary->record_obj_copy_time_ms(obj_copy_time);
1629 if (parallel) {
1630 body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
1631 body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
1632 body_summary->record_termination_time_ms(termination_time);
1633 body_summary->record_parallel_other_time_ms(parallel_other_time);
1634 }
1635 body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
1636 }
1638 if (G1PolicyVerbose > 1) {
1639 gclog_or_tty->print_cr(" ET: %10.6f ms (avg: %10.6f ms)\n"
1640 " CH Strong: %10.6f ms (avg: %10.6f ms)\n"
1641 " G1 Strong: %10.6f ms (avg: %10.6f ms)\n"
1642 " Evac: %10.6f ms (avg: %10.6f ms)\n"
1643 " ET-RS: %10.6f ms (avg: %10.6f ms)\n"
1644 " |RS|: " SIZE_FORMAT,
1645 elapsed_ms, recent_avg_time_for_pauses_ms(),
1646 _cur_CH_strong_roots_dur_ms, recent_avg_time_for_CH_strong_ms(),
1647 _cur_G1_strong_roots_dur_ms, recent_avg_time_for_G1_strong_ms(),
1648 evac_ms, recent_avg_time_for_evac_ms(),
1649 scan_rs_time,
1650 recent_avg_time_for_pauses_ms() -
1651 recent_avg_time_for_G1_strong_ms(),
1652 rs_size);
1654 gclog_or_tty->print_cr(" Used at start: " SIZE_FORMAT"K"
1655 " At end " SIZE_FORMAT "K\n"
1656 " garbage : " SIZE_FORMAT "K"
1657 " of " SIZE_FORMAT "K\n"
1658 " survival : %6.2f%% (%6.2f%% avg)",
1659 _cur_collection_pause_used_at_start_bytes/K,
1660 _g1->used()/K, freed_bytes/K,
1661 _collection_set_bytes_used_before/K,
1662 survival_fraction*100.0,
1663 recent_avg_survival_fraction()*100.0);
1664 gclog_or_tty->print_cr(" Recent %% gc pause time: %6.2f",
1665 recent_avg_pause_time_ratio() * 100.0);
1666 }
1668 double other_time_ms = elapsed_ms;
1670 if (!abandoned) {
1671 if (_satb_drain_time_set)
1672 other_time_ms -= _cur_satb_drain_time_ms;
1674 if (parallel)
1675 other_time_ms -= _cur_collection_par_time_ms + _cur_clear_ct_time_ms;
1676 else
1677 other_time_ms -=
1678 update_rs_time +
1679 ext_root_scan_time + mark_stack_scan_time + scan_only_time +
1680 scan_rs_time + obj_copy_time;
1681 }
1683 if (PrintGCDetails) {
1684 gclog_or_tty->print_cr("%s%s, %1.8lf secs]",
1685 abandoned ? " (abandoned)" : "",
1686 (last_pause_included_initial_mark) ? " (initial-mark)" : "",
1687 elapsed_ms / 1000.0);
1689 if (!abandoned) {
1690 if (_satb_drain_time_set) {
1691 print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
1692 }
1693 if (_last_satb_drain_processed_buffers >= 0) {
1694 print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
1695 }
1696 if (parallel) {
1697 print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
1698 print_par_stats(2, "Update RS (Start)", _par_last_update_rs_start_times_ms, false);
1699 print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
1700 print_par_buffers(3, "Processed Buffers",
1701 _par_last_update_rs_processed_buffers, true);
1702 print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
1703 print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
1704 print_par_stats(2, "Scan-Only Scanning", _par_last_scan_only_times_ms);
1705 print_par_buffers(3, "Scan-Only Regions",
1706 _par_last_scan_only_regions_scanned, true);
1707 print_par_stats(2, "Scan RS", _par_last_scan_rs_times_ms);
1708 print_par_stats(2, "Object Copy", _par_last_obj_copy_times_ms);
1709 print_par_stats(2, "Termination", _par_last_termination_times_ms);
1710 print_stats(2, "Other", parallel_other_time);
1711 print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
1712 } else {
1713 print_stats(1, "Update RS", update_rs_time);
1714 print_stats(2, "Processed Buffers",
1715 (int)update_rs_processed_buffers);
1716 print_stats(1, "Ext Root Scanning", ext_root_scan_time);
1717 print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
1718 print_stats(1, "Scan-Only Scanning", scan_only_time);
1719 print_stats(1, "Scan RS", scan_rs_time);
1720 print_stats(1, "Object Copying", obj_copy_time);
1721 }
1722 }
1723 #ifndef PRODUCT
1724 print_stats(1, "Cur Clear CC", _cur_clear_cc_time_ms);
1725 print_stats(1, "Cum Clear CC", _cum_clear_cc_time_ms);
1726 print_stats(1, "Min Clear CC", _min_clear_cc_time_ms);
1727 print_stats(1, "Max Clear CC", _max_clear_cc_time_ms);
1728 if (_num_cc_clears > 0) {
1729 print_stats(1, "Avg Clear CC", _cum_clear_cc_time_ms / ((double)_num_cc_clears));
1730 }
1731 #endif
1732 print_stats(1, "Other", other_time_ms);
1733 for (int i = 0; i < _aux_num; ++i) {
1734 if (_cur_aux_times_set[i]) {
1735 char buffer[96];
1736 sprintf(buffer, "Aux%d", i);
1737 print_stats(1, buffer, _cur_aux_times_ms[i]);
1738 }
1739 }
1740 }
1741 if (PrintGCDetails)
1742 gclog_or_tty->print(" [");
1743 if (PrintGC || PrintGCDetails)
1744 _g1->print_size_transition(gclog_or_tty,
1745 _cur_collection_pause_used_at_start_bytes,
1746 _g1->used(), _g1->capacity());
1747 if (PrintGCDetails)
1748 gclog_or_tty->print_cr("]");
1750 _all_pause_times_ms->add(elapsed_ms);
1751 if (update_stats) {
1752 summary->record_total_time_ms(elapsed_ms);
1753 summary->record_other_time_ms(other_time_ms);
1754 }
1755 for (int i = 0; i < _aux_num; ++i)
1756 if (_cur_aux_times_set[i])
1757 _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
1759 // Reset marks-between-pauses counter.
1760 _n_marks_since_last_pause = 0;
1762 // Update the efficiency-since-mark vars.
1763 double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
1764 if (elapsed_ms < MIN_TIMER_GRANULARITY) {
1765 // This usually happens due to the timer not having the required
1766 // granularity. Some Linuxes are the usual culprits.
1767 // We'll just set it to something (arbitrarily) small.
1768 proc_ms = 1.0;
1769 }
1770 double cur_efficiency = (double) freed_bytes / proc_ms;
1772 bool new_in_marking_window = _in_marking_window;
1773 bool new_in_marking_window_im = false;
1774 if (during_initial_mark_pause()) {
1775 new_in_marking_window = true;
1776 new_in_marking_window_im = true;
1777 }
1779 if (in_young_gc_mode()) {
1780 if (_last_full_young_gc) {
1781 set_full_young_gcs(false);
1782 _last_full_young_gc = false;
1783 }
1785 if ( !_last_young_gc_full ) {
1786 if ( _should_revert_to_full_young_gcs ||
1787 _known_garbage_ratio < 0.05 ||
1788 (adaptive_young_list_length() &&
1789 (get_gc_eff_factor() * cur_efficiency < predict_young_gc_eff())) ) {
1790 set_full_young_gcs(true);
1791 }
1792 }
1793 _should_revert_to_full_young_gcs = false;
1795 if (_last_young_gc_full && !_during_marking)
1796 _young_gc_eff_seq->add(cur_efficiency);
1797 }
1799 _short_lived_surv_rate_group->start_adding_regions();
1800 // do that for any other surv rate groupsx
1802 // <NEW PREDICTION>
1804 if (update_stats) {
1805 double pause_time_ms = elapsed_ms;
1807 size_t diff = 0;
1808 if (_max_pending_cards >= _pending_cards)
1809 diff = _max_pending_cards - _pending_cards;
1810 _pending_card_diff_seq->add((double) diff);
1812 double cost_per_card_ms = 0.0;
1813 if (_pending_cards > 0) {
1814 cost_per_card_ms = update_rs_time / (double) _pending_cards;
1815 _cost_per_card_ms_seq->add(cost_per_card_ms);
1816 }
1818 double cost_per_scan_only_region_ms = 0.0;
1819 if (scan_only_regions_scanned > 0.0) {
1820 cost_per_scan_only_region_ms =
1821 scan_only_time / scan_only_regions_scanned;
1822 if (_in_marking_window_im)
1823 _cost_per_scan_only_region_ms_during_cm_seq->add(cost_per_scan_only_region_ms);
1824 else
1825 _cost_per_scan_only_region_ms_seq->add(cost_per_scan_only_region_ms);
1826 }
1828 size_t cards_scanned = _g1->cards_scanned();
1830 double cost_per_entry_ms = 0.0;
1831 if (cards_scanned > 10) {
1832 cost_per_entry_ms = scan_rs_time / (double) cards_scanned;
1833 if (_last_young_gc_full)
1834 _cost_per_entry_ms_seq->add(cost_per_entry_ms);
1835 else
1836 _partially_young_cost_per_entry_ms_seq->add(cost_per_entry_ms);
1837 }
1839 if (_max_rs_lengths > 0) {
1840 double cards_per_entry_ratio =
1841 (double) cards_scanned / (double) _max_rs_lengths;
1842 if (_last_young_gc_full)
1843 _fully_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1844 else
1845 _partially_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1846 }
1848 size_t rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
1849 if (rs_length_diff >= 0)
1850 _rs_length_diff_seq->add((double) rs_length_diff);
1852 size_t copied_bytes = surviving_bytes;
1853 double cost_per_byte_ms = 0.0;
1854 if (copied_bytes > 0) {
1855 cost_per_byte_ms = obj_copy_time / (double) copied_bytes;
1856 if (_in_marking_window)
1857 _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
1858 else
1859 _cost_per_byte_ms_seq->add(cost_per_byte_ms);
1860 }
1862 double all_other_time_ms = pause_time_ms -
1863 (update_rs_time + scan_only_time + scan_rs_time + obj_copy_time +
1864 _mark_closure_time_ms + termination_time);
1866 double young_other_time_ms = 0.0;
1867 if (_recorded_young_regions > 0) {
1868 young_other_time_ms =
1869 _recorded_young_cset_choice_time_ms +
1870 _recorded_young_free_cset_time_ms;
1871 _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
1872 (double) _recorded_young_regions);
1873 }
1874 double non_young_other_time_ms = 0.0;
1875 if (_recorded_non_young_regions > 0) {
1876 non_young_other_time_ms =
1877 _recorded_non_young_cset_choice_time_ms +
1878 _recorded_non_young_free_cset_time_ms;
1880 _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
1881 (double) _recorded_non_young_regions);
1882 }
1884 double constant_other_time_ms = all_other_time_ms -
1885 (young_other_time_ms + non_young_other_time_ms);
1886 _constant_other_time_ms_seq->add(constant_other_time_ms);
1888 double survival_ratio = 0.0;
1889 if (_bytes_in_collection_set_before_gc > 0) {
1890 survival_ratio = (double) bytes_in_to_space_during_gc() /
1891 (double) _bytes_in_collection_set_before_gc;
1892 }
1894 _pending_cards_seq->add((double) _pending_cards);
1895 _scanned_cards_seq->add((double) cards_scanned);
1896 _rs_lengths_seq->add((double) _max_rs_lengths);
1898 double expensive_region_limit_ms =
1899 (double) MaxGCPauseMillis - predict_constant_other_time_ms();
1900 if (expensive_region_limit_ms < 0.0) {
1901 // this means that the other time was predicted to be longer than
1902 // than the max pause time
1903 expensive_region_limit_ms = (double) MaxGCPauseMillis;
1904 }
1905 _expensive_region_limit_ms = expensive_region_limit_ms;
1907 if (PREDICTIONS_VERBOSE) {
1908 gclog_or_tty->print_cr("");
1909 gclog_or_tty->print_cr("PREDICTIONS %1.4lf %d "
1910 "REGIONS %d %d %d %d "
1911 "PENDING_CARDS %d %d "
1912 "CARDS_SCANNED %d %d "
1913 "RS_LENGTHS %d %d "
1914 "SCAN_ONLY_SCAN %1.6lf %1.6lf "
1915 "RS_UPDATE %1.6lf %1.6lf RS_SCAN %1.6lf %1.6lf "
1916 "SURVIVAL_RATIO %1.6lf %1.6lf "
1917 "OBJECT_COPY %1.6lf %1.6lf OTHER_CONSTANT %1.6lf %1.6lf "
1918 "OTHER_YOUNG %1.6lf %1.6lf "
1919 "OTHER_NON_YOUNG %1.6lf %1.6lf "
1920 "VTIME_DIFF %1.6lf TERMINATION %1.6lf "
1921 "ELAPSED %1.6lf %1.6lf ",
1922 _cur_collection_start_sec,
1923 (!_last_young_gc_full) ? 2 :
1924 (last_pause_included_initial_mark) ? 1 : 0,
1925 _recorded_region_num,
1926 _recorded_young_regions,
1927 _recorded_scan_only_regions,
1928 _recorded_non_young_regions,
1929 _predicted_pending_cards, _pending_cards,
1930 _predicted_cards_scanned, cards_scanned,
1931 _predicted_rs_lengths, _max_rs_lengths,
1932 _predicted_scan_only_scan_time_ms, scan_only_time,
1933 _predicted_rs_update_time_ms, update_rs_time,
1934 _predicted_rs_scan_time_ms, scan_rs_time,
1935 _predicted_survival_ratio, survival_ratio,
1936 _predicted_object_copy_time_ms, obj_copy_time,
1937 _predicted_constant_other_time_ms, constant_other_time_ms,
1938 _predicted_young_other_time_ms, young_other_time_ms,
1939 _predicted_non_young_other_time_ms,
1940 non_young_other_time_ms,
1941 _vtime_diff_ms, termination_time,
1942 _predicted_pause_time_ms, elapsed_ms);
1943 }
1945 if (G1PolicyVerbose > 0) {
1946 gclog_or_tty->print_cr("Pause Time, predicted: %1.4lfms (predicted %s), actual: %1.4lfms",
1947 _predicted_pause_time_ms,
1948 (_within_target) ? "within" : "outside",
1949 elapsed_ms);
1950 }
1952 }
1954 _in_marking_window = new_in_marking_window;
1955 _in_marking_window_im = new_in_marking_window_im;
1956 _free_regions_at_end_of_collection = _g1->free_regions();
1957 _scan_only_regions_at_end_of_collection = _g1->young_list_length();
1958 calculate_young_list_min_length();
1959 calculate_young_list_target_config();
1961 // Note that _mmu_tracker->max_gc_time() returns the time in seconds.
1962 double update_rs_time_goal_ms = _mmu_tracker->max_gc_time() * MILLIUNITS * G1RSetUpdatingPauseTimePercent / 100.0;
1963 adjust_concurrent_refinement(update_rs_time, update_rs_processed_buffers, update_rs_time_goal_ms);
1965 // </NEW PREDICTION>
1967 _target_pause_time_ms = -1.0;
1968 }
1970 // <NEW PREDICTION>
1972 void G1CollectorPolicy::adjust_concurrent_refinement(double update_rs_time,
1973 double update_rs_processed_buffers,
1974 double goal_ms) {
1975 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
1976 ConcurrentG1Refine *cg1r = G1CollectedHeap::heap()->concurrent_g1_refine();
1978 if (G1UseAdaptiveConcRefinement) {
1979 const int k_gy = 3, k_gr = 6;
1980 const double inc_k = 1.1, dec_k = 0.9;
1982 int g = cg1r->green_zone();
1983 if (update_rs_time > goal_ms) {
1984 g = (int)(g * dec_k); // Can become 0, that's OK. That would mean a mutator-only processing.
1985 } else {
1986 if (update_rs_time < goal_ms && update_rs_processed_buffers > g) {
1987 g = (int)MAX2(g * inc_k, g + 1.0);
1988 }
1989 }
1990 // Change the refinement threads params
1991 cg1r->set_green_zone(g);
1992 cg1r->set_yellow_zone(g * k_gy);
1993 cg1r->set_red_zone(g * k_gr);
1994 cg1r->reinitialize_threads();
1996 int processing_threshold_delta = MAX2((int)(cg1r->green_zone() * sigma()), 1);
1997 int processing_threshold = MIN2(cg1r->green_zone() + processing_threshold_delta,
1998 cg1r->yellow_zone());
1999 // Change the barrier params
2000 dcqs.set_process_completed_threshold(processing_threshold);
2001 dcqs.set_max_completed_queue(cg1r->red_zone());
2002 }
2004 int curr_queue_size = dcqs.completed_buffers_num();
2005 if (curr_queue_size >= cg1r->yellow_zone()) {
2006 dcqs.set_completed_queue_padding(curr_queue_size);
2007 } else {
2008 dcqs.set_completed_queue_padding(0);
2009 }
2010 dcqs.notify_if_necessary();
2011 }
2013 double
2014 G1CollectorPolicy::
2015 predict_young_collection_elapsed_time_ms(size_t adjustment) {
2016 guarantee( adjustment == 0 || adjustment == 1, "invariant" );
2018 G1CollectedHeap* g1h = G1CollectedHeap::heap();
2019 size_t young_num = g1h->young_list_length();
2020 if (young_num == 0)
2021 return 0.0;
2023 young_num += adjustment;
2024 size_t pending_cards = predict_pending_cards();
2025 size_t rs_lengths = g1h->young_list_sampled_rs_lengths() +
2026 predict_rs_length_diff();
2027 size_t card_num;
2028 if (full_young_gcs())
2029 card_num = predict_young_card_num(rs_lengths);
2030 else
2031 card_num = predict_non_young_card_num(rs_lengths);
2032 size_t young_byte_size = young_num * HeapRegion::GrainBytes;
2033 double accum_yg_surv_rate =
2034 _short_lived_surv_rate_group->accum_surv_rate(adjustment);
2036 size_t bytes_to_copy =
2037 (size_t) (accum_yg_surv_rate * (double) HeapRegion::GrainBytes);
2039 return
2040 predict_rs_update_time_ms(pending_cards) +
2041 predict_rs_scan_time_ms(card_num) +
2042 predict_object_copy_time_ms(bytes_to_copy) +
2043 predict_young_other_time_ms(young_num) +
2044 predict_constant_other_time_ms();
2045 }
2047 double
2048 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
2049 size_t rs_length = predict_rs_length_diff();
2050 size_t card_num;
2051 if (full_young_gcs())
2052 card_num = predict_young_card_num(rs_length);
2053 else
2054 card_num = predict_non_young_card_num(rs_length);
2055 return predict_base_elapsed_time_ms(pending_cards, card_num);
2056 }
2058 double
2059 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
2060 size_t scanned_cards) {
2061 return
2062 predict_rs_update_time_ms(pending_cards) +
2063 predict_rs_scan_time_ms(scanned_cards) +
2064 predict_constant_other_time_ms();
2065 }
2067 double
2068 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
2069 bool young) {
2070 size_t rs_length = hr->rem_set()->occupied();
2071 size_t card_num;
2072 if (full_young_gcs())
2073 card_num = predict_young_card_num(rs_length);
2074 else
2075 card_num = predict_non_young_card_num(rs_length);
2076 size_t bytes_to_copy = predict_bytes_to_copy(hr);
2078 double region_elapsed_time_ms =
2079 predict_rs_scan_time_ms(card_num) +
2080 predict_object_copy_time_ms(bytes_to_copy);
2082 if (young)
2083 region_elapsed_time_ms += predict_young_other_time_ms(1);
2084 else
2085 region_elapsed_time_ms += predict_non_young_other_time_ms(1);
2087 return region_elapsed_time_ms;
2088 }
2090 size_t
2091 G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
2092 size_t bytes_to_copy;
2093 if (hr->is_marked())
2094 bytes_to_copy = hr->max_live_bytes();
2095 else {
2096 guarantee( hr->is_young() && hr->age_in_surv_rate_group() != -1,
2097 "invariant" );
2098 int age = hr->age_in_surv_rate_group();
2099 double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
2100 bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
2101 }
2103 return bytes_to_copy;
2104 }
2106 void
2107 G1CollectorPolicy::start_recording_regions() {
2108 _recorded_rs_lengths = 0;
2109 _recorded_scan_only_regions = 0;
2110 _recorded_young_regions = 0;
2111 _recorded_non_young_regions = 0;
2113 #if PREDICTIONS_VERBOSE
2114 _predicted_rs_lengths = 0;
2115 _predicted_cards_scanned = 0;
2117 _recorded_marked_bytes = 0;
2118 _recorded_young_bytes = 0;
2119 _predicted_bytes_to_copy = 0;
2120 #endif // PREDICTIONS_VERBOSE
2121 }
2123 void
2124 G1CollectorPolicy::record_cset_region(HeapRegion* hr, bool young) {
2125 if (young) {
2126 ++_recorded_young_regions;
2127 } else {
2128 ++_recorded_non_young_regions;
2129 }
2130 #if PREDICTIONS_VERBOSE
2131 if (young) {
2132 _recorded_young_bytes += hr->used();
2133 } else {
2134 _recorded_marked_bytes += hr->max_live_bytes();
2135 }
2136 _predicted_bytes_to_copy += predict_bytes_to_copy(hr);
2137 #endif // PREDICTIONS_VERBOSE
2139 size_t rs_length = hr->rem_set()->occupied();
2140 _recorded_rs_lengths += rs_length;
2141 }
2143 void
2144 G1CollectorPolicy::record_scan_only_regions(size_t scan_only_length) {
2145 _recorded_scan_only_regions = scan_only_length;
2146 }
2148 void
2149 G1CollectorPolicy::end_recording_regions() {
2150 #if PREDICTIONS_VERBOSE
2151 _predicted_pending_cards = predict_pending_cards();
2152 _predicted_rs_lengths = _recorded_rs_lengths + predict_rs_length_diff();
2153 if (full_young_gcs())
2154 _predicted_cards_scanned += predict_young_card_num(_predicted_rs_lengths);
2155 else
2156 _predicted_cards_scanned +=
2157 predict_non_young_card_num(_predicted_rs_lengths);
2158 _recorded_region_num = _recorded_young_regions + _recorded_non_young_regions;
2160 _predicted_scan_only_scan_time_ms =
2161 predict_scan_only_time_ms(_recorded_scan_only_regions);
2162 _predicted_rs_update_time_ms =
2163 predict_rs_update_time_ms(_g1->pending_card_num());
2164 _predicted_rs_scan_time_ms =
2165 predict_rs_scan_time_ms(_predicted_cards_scanned);
2166 _predicted_object_copy_time_ms =
2167 predict_object_copy_time_ms(_predicted_bytes_to_copy);
2168 _predicted_constant_other_time_ms =
2169 predict_constant_other_time_ms();
2170 _predicted_young_other_time_ms =
2171 predict_young_other_time_ms(_recorded_young_regions);
2172 _predicted_non_young_other_time_ms =
2173 predict_non_young_other_time_ms(_recorded_non_young_regions);
2175 _predicted_pause_time_ms =
2176 _predicted_scan_only_scan_time_ms +
2177 _predicted_rs_update_time_ms +
2178 _predicted_rs_scan_time_ms +
2179 _predicted_object_copy_time_ms +
2180 _predicted_constant_other_time_ms +
2181 _predicted_young_other_time_ms +
2182 _predicted_non_young_other_time_ms;
2183 #endif // PREDICTIONS_VERBOSE
2184 }
2186 void G1CollectorPolicy::check_if_region_is_too_expensive(double
2187 predicted_time_ms) {
2188 // I don't think we need to do this when in young GC mode since
2189 // marking will be initiated next time we hit the soft limit anyway...
2190 if (predicted_time_ms > _expensive_region_limit_ms) {
2191 if (!in_young_gc_mode()) {
2192 set_full_young_gcs(true);
2193 // We might want to do something different here. However,
2194 // right now we don't support the non-generational G1 mode
2195 // (and in fact we are planning to remove the associated code,
2196 // see CR 6814390). So, let's leave it as is and this will be
2197 // removed some time in the future
2198 ShouldNotReachHere();
2199 set_during_initial_mark_pause();
2200 } else
2201 // no point in doing another partial one
2202 _should_revert_to_full_young_gcs = true;
2203 }
2204 }
2206 // </NEW PREDICTION>
2209 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
2210 double elapsed_ms) {
2211 _recent_gc_times_ms->add(elapsed_ms);
2212 _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
2213 _prev_collection_pause_end_ms = end_time_sec * 1000.0;
2214 }
2216 double G1CollectorPolicy::recent_avg_time_for_pauses_ms() {
2217 if (_recent_pause_times_ms->num() == 0) return (double) MaxGCPauseMillis;
2218 else return _recent_pause_times_ms->avg();
2219 }
2221 double G1CollectorPolicy::recent_avg_time_for_CH_strong_ms() {
2222 if (_recent_CH_strong_roots_times_ms->num() == 0)
2223 return (double)MaxGCPauseMillis/3.0;
2224 else return _recent_CH_strong_roots_times_ms->avg();
2225 }
2227 double G1CollectorPolicy::recent_avg_time_for_G1_strong_ms() {
2228 if (_recent_G1_strong_roots_times_ms->num() == 0)
2229 return (double)MaxGCPauseMillis/3.0;
2230 else return _recent_G1_strong_roots_times_ms->avg();
2231 }
2233 double G1CollectorPolicy::recent_avg_time_for_evac_ms() {
2234 if (_recent_evac_times_ms->num() == 0) return (double)MaxGCPauseMillis/3.0;
2235 else return _recent_evac_times_ms->avg();
2236 }
2238 int G1CollectorPolicy::number_of_recent_gcs() {
2239 assert(_recent_CH_strong_roots_times_ms->num() ==
2240 _recent_G1_strong_roots_times_ms->num(), "Sequence out of sync");
2241 assert(_recent_G1_strong_roots_times_ms->num() ==
2242 _recent_evac_times_ms->num(), "Sequence out of sync");
2243 assert(_recent_evac_times_ms->num() ==
2244 _recent_pause_times_ms->num(), "Sequence out of sync");
2245 assert(_recent_pause_times_ms->num() ==
2246 _recent_CS_bytes_used_before->num(), "Sequence out of sync");
2247 assert(_recent_CS_bytes_used_before->num() ==
2248 _recent_CS_bytes_surviving->num(), "Sequence out of sync");
2249 return _recent_pause_times_ms->num();
2250 }
2252 double G1CollectorPolicy::recent_avg_survival_fraction() {
2253 return recent_avg_survival_fraction_work(_recent_CS_bytes_surviving,
2254 _recent_CS_bytes_used_before);
2255 }
2257 double G1CollectorPolicy::last_survival_fraction() {
2258 return last_survival_fraction_work(_recent_CS_bytes_surviving,
2259 _recent_CS_bytes_used_before);
2260 }
2262 double
2263 G1CollectorPolicy::recent_avg_survival_fraction_work(TruncatedSeq* surviving,
2264 TruncatedSeq* before) {
2265 assert(surviving->num() == before->num(), "Sequence out of sync");
2266 if (before->sum() > 0.0) {
2267 double recent_survival_rate = surviving->sum() / before->sum();
2268 // We exempt parallel collection from this check because Alloc Buffer
2269 // fragmentation can produce negative collections.
2270 // Further, we're now always doing parallel collection. But I'm still
2271 // leaving this here as a placeholder for a more precise assertion later.
2272 // (DLD, 10/05.)
2273 assert((true || ParallelGCThreads > 0) ||
2274 _g1->evacuation_failed() ||
2275 recent_survival_rate <= 1.0, "Or bad frac");
2276 return recent_survival_rate;
2277 } else {
2278 return 1.0; // Be conservative.
2279 }
2280 }
2282 double
2283 G1CollectorPolicy::last_survival_fraction_work(TruncatedSeq* surviving,
2284 TruncatedSeq* before) {
2285 assert(surviving->num() == before->num(), "Sequence out of sync");
2286 if (surviving->num() > 0 && before->last() > 0.0) {
2287 double last_survival_rate = surviving->last() / before->last();
2288 // We exempt parallel collection from this check because Alloc Buffer
2289 // fragmentation can produce negative collections.
2290 // Further, we're now always doing parallel collection. But I'm still
2291 // leaving this here as a placeholder for a more precise assertion later.
2292 // (DLD, 10/05.)
2293 assert((true || ParallelGCThreads > 0) ||
2294 last_survival_rate <= 1.0, "Or bad frac");
2295 return last_survival_rate;
2296 } else {
2297 return 1.0;
2298 }
2299 }
2301 static const int survival_min_obs = 5;
2302 static double survival_min_obs_limits[] = { 0.9, 0.7, 0.5, 0.3, 0.1 };
2303 static const double min_survival_rate = 0.1;
2305 double
2306 G1CollectorPolicy::conservative_avg_survival_fraction_work(double avg,
2307 double latest) {
2308 double res = avg;
2309 if (number_of_recent_gcs() < survival_min_obs) {
2310 res = MAX2(res, survival_min_obs_limits[number_of_recent_gcs()]);
2311 }
2312 res = MAX2(res, latest);
2313 res = MAX2(res, min_survival_rate);
2314 // In the parallel case, LAB fragmentation can produce "negative
2315 // collections"; so can evac failure. Cap at 1.0
2316 res = MIN2(res, 1.0);
2317 return res;
2318 }
2320 size_t G1CollectorPolicy::expansion_amount() {
2321 if ((recent_avg_pause_time_ratio() * 100.0) > _gc_overhead_perc) {
2322 // We will double the existing space, or take
2323 // G1ExpandByPercentOfAvailable % of the available expansion
2324 // space, whichever is smaller, bounded below by a minimum
2325 // expansion (unless that's all that's left.)
2326 const size_t min_expand_bytes = 1*M;
2327 size_t reserved_bytes = _g1->g1_reserved_obj_bytes();
2328 size_t committed_bytes = _g1->capacity();
2329 size_t uncommitted_bytes = reserved_bytes - committed_bytes;
2330 size_t expand_bytes;
2331 size_t expand_bytes_via_pct =
2332 uncommitted_bytes * G1ExpandByPercentOfAvailable / 100;
2333 expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
2334 expand_bytes = MAX2(expand_bytes, min_expand_bytes);
2335 expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
2336 if (G1PolicyVerbose > 1) {
2337 gclog_or_tty->print("Decided to expand: ratio = %5.2f, "
2338 "committed = %d%s, uncommited = %d%s, via pct = %d%s.\n"
2339 " Answer = %d.\n",
2340 recent_avg_pause_time_ratio(),
2341 byte_size_in_proper_unit(committed_bytes),
2342 proper_unit_for_byte_size(committed_bytes),
2343 byte_size_in_proper_unit(uncommitted_bytes),
2344 proper_unit_for_byte_size(uncommitted_bytes),
2345 byte_size_in_proper_unit(expand_bytes_via_pct),
2346 proper_unit_for_byte_size(expand_bytes_via_pct),
2347 byte_size_in_proper_unit(expand_bytes),
2348 proper_unit_for_byte_size(expand_bytes));
2349 }
2350 return expand_bytes;
2351 } else {
2352 return 0;
2353 }
2354 }
2356 void G1CollectorPolicy::note_start_of_mark_thread() {
2357 _mark_thread_startup_sec = os::elapsedTime();
2358 }
2360 class CountCSClosure: public HeapRegionClosure {
2361 G1CollectorPolicy* _g1_policy;
2362 public:
2363 CountCSClosure(G1CollectorPolicy* g1_policy) :
2364 _g1_policy(g1_policy) {}
2365 bool doHeapRegion(HeapRegion* r) {
2366 _g1_policy->_bytes_in_collection_set_before_gc += r->used();
2367 return false;
2368 }
2369 };
2371 void G1CollectorPolicy::count_CS_bytes_used() {
2372 CountCSClosure cs_closure(this);
2373 _g1->collection_set_iterate(&cs_closure);
2374 }
2376 static void print_indent(int level) {
2377 for (int j = 0; j < level+1; ++j)
2378 gclog_or_tty->print(" ");
2379 }
2381 void G1CollectorPolicy::print_summary (int level,
2382 const char* str,
2383 NumberSeq* seq) const {
2384 double sum = seq->sum();
2385 print_indent(level);
2386 gclog_or_tty->print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
2387 str, sum / 1000.0, seq->avg());
2388 }
2390 void G1CollectorPolicy::print_summary_sd (int level,
2391 const char* str,
2392 NumberSeq* seq) const {
2393 print_summary(level, str, seq);
2394 print_indent(level + 5);
2395 gclog_or_tty->print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
2396 seq->num(), seq->sd(), seq->maximum());
2397 }
2399 void G1CollectorPolicy::check_other_times(int level,
2400 NumberSeq* other_times_ms,
2401 NumberSeq* calc_other_times_ms) const {
2402 bool should_print = false;
2404 double max_sum = MAX2(fabs(other_times_ms->sum()),
2405 fabs(calc_other_times_ms->sum()));
2406 double min_sum = MIN2(fabs(other_times_ms->sum()),
2407 fabs(calc_other_times_ms->sum()));
2408 double sum_ratio = max_sum / min_sum;
2409 if (sum_ratio > 1.1) {
2410 should_print = true;
2411 print_indent(level + 1);
2412 gclog_or_tty->print_cr("## CALCULATED OTHER SUM DOESN'T MATCH RECORDED ###");
2413 }
2415 double max_avg = MAX2(fabs(other_times_ms->avg()),
2416 fabs(calc_other_times_ms->avg()));
2417 double min_avg = MIN2(fabs(other_times_ms->avg()),
2418 fabs(calc_other_times_ms->avg()));
2419 double avg_ratio = max_avg / min_avg;
2420 if (avg_ratio > 1.1) {
2421 should_print = true;
2422 print_indent(level + 1);
2423 gclog_or_tty->print_cr("## CALCULATED OTHER AVG DOESN'T MATCH RECORDED ###");
2424 }
2426 if (other_times_ms->sum() < -0.01) {
2427 print_indent(level + 1);
2428 gclog_or_tty->print_cr("## RECORDED OTHER SUM IS NEGATIVE ###");
2429 }
2431 if (other_times_ms->avg() < -0.01) {
2432 print_indent(level + 1);
2433 gclog_or_tty->print_cr("## RECORDED OTHER AVG IS NEGATIVE ###");
2434 }
2436 if (calc_other_times_ms->sum() < -0.01) {
2437 should_print = true;
2438 print_indent(level + 1);
2439 gclog_or_tty->print_cr("## CALCULATED OTHER SUM IS NEGATIVE ###");
2440 }
2442 if (calc_other_times_ms->avg() < -0.01) {
2443 should_print = true;
2444 print_indent(level + 1);
2445 gclog_or_tty->print_cr("## CALCULATED OTHER AVG IS NEGATIVE ###");
2446 }
2448 if (should_print)
2449 print_summary(level, "Other(Calc)", calc_other_times_ms);
2450 }
2452 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
2453 bool parallel = ParallelGCThreads > 0;
2454 MainBodySummary* body_summary = summary->main_body_summary();
2455 if (summary->get_total_seq()->num() > 0) {
2456 print_summary_sd(0, "Evacuation Pauses", summary->get_total_seq());
2457 if (body_summary != NULL) {
2458 print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
2459 if (parallel) {
2460 print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
2461 print_summary(2, "Update RS", body_summary->get_update_rs_seq());
2462 print_summary(2, "Ext Root Scanning",
2463 body_summary->get_ext_root_scan_seq());
2464 print_summary(2, "Mark Stack Scanning",
2465 body_summary->get_mark_stack_scan_seq());
2466 print_summary(2, "Scan-Only Scanning",
2467 body_summary->get_scan_only_seq());
2468 print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
2469 print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
2470 print_summary(2, "Termination", body_summary->get_termination_seq());
2471 print_summary(2, "Other", body_summary->get_parallel_other_seq());
2472 {
2473 NumberSeq* other_parts[] = {
2474 body_summary->get_update_rs_seq(),
2475 body_summary->get_ext_root_scan_seq(),
2476 body_summary->get_mark_stack_scan_seq(),
2477 body_summary->get_scan_only_seq(),
2478 body_summary->get_scan_rs_seq(),
2479 body_summary->get_obj_copy_seq(),
2480 body_summary->get_termination_seq()
2481 };
2482 NumberSeq calc_other_times_ms(body_summary->get_parallel_seq(),
2483 7, other_parts);
2484 check_other_times(2, body_summary->get_parallel_other_seq(),
2485 &calc_other_times_ms);
2486 }
2487 print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
2488 print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
2489 } else {
2490 print_summary(1, "Update RS", body_summary->get_update_rs_seq());
2491 print_summary(1, "Ext Root Scanning",
2492 body_summary->get_ext_root_scan_seq());
2493 print_summary(1, "Mark Stack Scanning",
2494 body_summary->get_mark_stack_scan_seq());
2495 print_summary(1, "Scan-Only Scanning",
2496 body_summary->get_scan_only_seq());
2497 print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
2498 print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
2499 }
2500 }
2501 print_summary(1, "Other", summary->get_other_seq());
2502 {
2503 NumberSeq calc_other_times_ms;
2504 if (body_summary != NULL) {
2505 // not abandoned
2506 if (parallel) {
2507 // parallel
2508 NumberSeq* other_parts[] = {
2509 body_summary->get_satb_drain_seq(),
2510 body_summary->get_parallel_seq(),
2511 body_summary->get_clear_ct_seq()
2512 };
2513 calc_other_times_ms = NumberSeq(summary->get_total_seq(),
2514 3, other_parts);
2515 } else {
2516 // serial
2517 NumberSeq* other_parts[] = {
2518 body_summary->get_satb_drain_seq(),
2519 body_summary->get_update_rs_seq(),
2520 body_summary->get_ext_root_scan_seq(),
2521 body_summary->get_mark_stack_scan_seq(),
2522 body_summary->get_scan_only_seq(),
2523 body_summary->get_scan_rs_seq(),
2524 body_summary->get_obj_copy_seq()
2525 };
2526 calc_other_times_ms = NumberSeq(summary->get_total_seq(),
2527 7, other_parts);
2528 }
2529 } else {
2530 // abandoned
2531 calc_other_times_ms = NumberSeq();
2532 }
2533 check_other_times(1, summary->get_other_seq(), &calc_other_times_ms);
2534 }
2535 } else {
2536 print_indent(0);
2537 gclog_or_tty->print_cr("none");
2538 }
2539 gclog_or_tty->print_cr("");
2540 }
2542 void
2543 G1CollectorPolicy::print_abandoned_summary(PauseSummary* summary) const {
2544 bool printed = false;
2545 if (summary->get_total_seq()->num() > 0) {
2546 printed = true;
2547 print_summary(summary);
2548 }
2549 if (!printed) {
2550 print_indent(0);
2551 gclog_or_tty->print_cr("none");
2552 gclog_or_tty->print_cr("");
2553 }
2554 }
2556 void G1CollectorPolicy::print_tracing_info() const {
2557 if (TraceGen0Time) {
2558 gclog_or_tty->print_cr("ALL PAUSES");
2559 print_summary_sd(0, "Total", _all_pause_times_ms);
2560 gclog_or_tty->print_cr("");
2561 gclog_or_tty->print_cr("");
2562 gclog_or_tty->print_cr(" Full Young GC Pauses: %8d", _full_young_pause_num);
2563 gclog_or_tty->print_cr(" Partial Young GC Pauses: %8d", _partial_young_pause_num);
2564 gclog_or_tty->print_cr("");
2566 gclog_or_tty->print_cr("EVACUATION PAUSES");
2567 print_summary(_summary);
2569 gclog_or_tty->print_cr("ABANDONED PAUSES");
2570 print_abandoned_summary(_abandoned_summary);
2572 gclog_or_tty->print_cr("MISC");
2573 print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
2574 print_summary_sd(0, "Yields", _all_yield_times_ms);
2575 for (int i = 0; i < _aux_num; ++i) {
2576 if (_all_aux_times_ms[i].num() > 0) {
2577 char buffer[96];
2578 sprintf(buffer, "Aux%d", i);
2579 print_summary_sd(0, buffer, &_all_aux_times_ms[i]);
2580 }
2581 }
2583 size_t all_region_num = _region_num_young + _region_num_tenured;
2584 gclog_or_tty->print_cr(" New Regions %8d, Young %8d (%6.2lf%%), "
2585 "Tenured %8d (%6.2lf%%)",
2586 all_region_num,
2587 _region_num_young,
2588 (double) _region_num_young / (double) all_region_num * 100.0,
2589 _region_num_tenured,
2590 (double) _region_num_tenured / (double) all_region_num * 100.0);
2591 }
2592 if (TraceGen1Time) {
2593 if (_all_full_gc_times_ms->num() > 0) {
2594 gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
2595 _all_full_gc_times_ms->num(),
2596 _all_full_gc_times_ms->sum() / 1000.0);
2597 gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times_ms->avg());
2598 gclog_or_tty->print_cr(" [std. dev = %8.2f ms, max = %8.2f ms]",
2599 _all_full_gc_times_ms->sd(),
2600 _all_full_gc_times_ms->maximum());
2601 }
2602 }
2603 }
2605 void G1CollectorPolicy::print_yg_surv_rate_info() const {
2606 #ifndef PRODUCT
2607 _short_lived_surv_rate_group->print_surv_rate_summary();
2608 // add this call for any other surv rate groups
2609 #endif // PRODUCT
2610 }
2612 bool
2613 G1CollectorPolicy::should_add_next_region_to_young_list() {
2614 assert(in_young_gc_mode(), "should be in young GC mode");
2615 bool ret;
2616 size_t young_list_length = _g1->young_list_length();
2617 size_t young_list_max_length = _young_list_target_length;
2618 if (G1FixedEdenSize) {
2619 young_list_max_length -= _max_survivor_regions;
2620 }
2621 if (young_list_length < young_list_max_length) {
2622 ret = true;
2623 ++_region_num_young;
2624 } else {
2625 ret = false;
2626 ++_region_num_tenured;
2627 }
2629 return ret;
2630 }
2632 #ifndef PRODUCT
2633 // for debugging, bit of a hack...
2634 static char*
2635 region_num_to_mbs(int length) {
2636 static char buffer[64];
2637 double bytes = (double) (length * HeapRegion::GrainBytes);
2638 double mbs = bytes / (double) (1024 * 1024);
2639 sprintf(buffer, "%7.2lfMB", mbs);
2640 return buffer;
2641 }
2642 #endif // PRODUCT
2644 size_t G1CollectorPolicy::max_regions(int purpose) {
2645 switch (purpose) {
2646 case GCAllocForSurvived:
2647 return _max_survivor_regions;
2648 case GCAllocForTenured:
2649 return REGIONS_UNLIMITED;
2650 default:
2651 ShouldNotReachHere();
2652 return REGIONS_UNLIMITED;
2653 };
2654 }
2656 // Calculates survivor space parameters.
2657 void G1CollectorPolicy::calculate_survivors_policy()
2658 {
2659 if (G1FixedSurvivorSpaceSize == 0) {
2660 _max_survivor_regions = _young_list_target_length / SurvivorRatio;
2661 } else {
2662 _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
2663 }
2665 if (G1FixedTenuringThreshold) {
2666 _tenuring_threshold = MaxTenuringThreshold;
2667 } else {
2668 _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
2669 HeapRegion::GrainWords * _max_survivor_regions);
2670 }
2671 }
2673 bool
2674 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
2675 word_size) {
2676 assert(_g1->regions_accounted_for(), "Region leakage!");
2677 double max_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
2679 size_t young_list_length = _g1->young_list_length();
2680 size_t young_list_max_length = _young_list_target_length;
2681 if (G1FixedEdenSize) {
2682 young_list_max_length -= _max_survivor_regions;
2683 }
2684 bool reached_target_length = young_list_length >= young_list_max_length;
2686 if (in_young_gc_mode()) {
2687 if (reached_target_length) {
2688 assert( young_list_length > 0 && _g1->young_list_length() > 0,
2689 "invariant" );
2690 _target_pause_time_ms = max_pause_time_ms;
2691 return true;
2692 }
2693 } else {
2694 guarantee( false, "should not reach here" );
2695 }
2697 return false;
2698 }
2700 #ifndef PRODUCT
2701 class HRSortIndexIsOKClosure: public HeapRegionClosure {
2702 CollectionSetChooser* _chooser;
2703 public:
2704 HRSortIndexIsOKClosure(CollectionSetChooser* chooser) :
2705 _chooser(chooser) {}
2707 bool doHeapRegion(HeapRegion* r) {
2708 if (!r->continuesHumongous()) {
2709 assert(_chooser->regionProperlyOrdered(r), "Ought to be.");
2710 }
2711 return false;
2712 }
2713 };
2715 bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() {
2716 HRSortIndexIsOKClosure cl(_collectionSetChooser);
2717 _g1->heap_region_iterate(&cl);
2718 return true;
2719 }
2720 #endif
2722 void
2723 G1CollectorPolicy::decide_on_conc_mark_initiation() {
2724 // We are about to decide on whether this pause will be an
2725 // initial-mark pause.
2727 // First, during_initial_mark_pause() should not be already set. We
2728 // will set it here if we have to. However, it should be cleared by
2729 // the end of the pause (it's only set for the duration of an
2730 // initial-mark pause).
2731 assert(!during_initial_mark_pause(), "pre-condition");
2733 if (initiate_conc_mark_if_possible()) {
2734 // We had noticed on a previous pause that the heap occupancy has
2735 // gone over the initiating threshold and we should start a
2736 // concurrent marking cycle. So we might initiate one.
2738 bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();
2739 if (!during_cycle) {
2740 // The concurrent marking thread is not "during a cycle", i.e.,
2741 // it has completed the last one. So we can go ahead and
2742 // initiate a new cycle.
2744 set_during_initial_mark_pause();
2746 // And we can now clear initiate_conc_mark_if_possible() as
2747 // we've already acted on it.
2748 clear_initiate_conc_mark_if_possible();
2749 } else {
2750 // The concurrent marking thread is still finishing up the
2751 // previous cycle. If we start one right now the two cycles
2752 // overlap. In particular, the concurrent marking thread might
2753 // be in the process of clearing the next marking bitmap (which
2754 // we will use for the next cycle if we start one). Starting a
2755 // cycle now will be bad given that parts of the marking
2756 // information might get cleared by the marking thread. And we
2757 // cannot wait for the marking thread to finish the cycle as it
2758 // periodically yields while clearing the next marking bitmap
2759 // and, if it's in a yield point, it's waiting for us to
2760 // finish. So, at this point we will not start a cycle and we'll
2761 // let the concurrent marking thread complete the last one.
2762 }
2763 }
2764 }
2766 void
2767 G1CollectorPolicy_BestRegionsFirst::
2768 record_collection_pause_start(double start_time_sec, size_t start_used) {
2769 G1CollectorPolicy::record_collection_pause_start(start_time_sec, start_used);
2770 }
2772 class NextNonCSElemFinder: public HeapRegionClosure {
2773 HeapRegion* _res;
2774 public:
2775 NextNonCSElemFinder(): _res(NULL) {}
2776 bool doHeapRegion(HeapRegion* r) {
2777 if (!r->in_collection_set()) {
2778 _res = r;
2779 return true;
2780 } else {
2781 return false;
2782 }
2783 }
2784 HeapRegion* res() { return _res; }
2785 };
2787 class KnownGarbageClosure: public HeapRegionClosure {
2788 CollectionSetChooser* _hrSorted;
2790 public:
2791 KnownGarbageClosure(CollectionSetChooser* hrSorted) :
2792 _hrSorted(hrSorted)
2793 {}
2795 bool doHeapRegion(HeapRegion* r) {
2796 // We only include humongous regions in collection
2797 // sets when concurrent mark shows that their contained object is
2798 // unreachable.
2800 // Do we have any marking information for this region?
2801 if (r->is_marked()) {
2802 // We don't include humongous regions in collection
2803 // sets because we collect them immediately at the end of a marking
2804 // cycle. We also don't include young regions because we *must*
2805 // include them in the next collection pause.
2806 if (!r->isHumongous() && !r->is_young()) {
2807 _hrSorted->addMarkedHeapRegion(r);
2808 }
2809 }
2810 return false;
2811 }
2812 };
2814 class ParKnownGarbageHRClosure: public HeapRegionClosure {
2815 CollectionSetChooser* _hrSorted;
2816 jint _marked_regions_added;
2817 jint _chunk_size;
2818 jint _cur_chunk_idx;
2819 jint _cur_chunk_end; // Cur chunk [_cur_chunk_idx, _cur_chunk_end)
2820 int _worker;
2821 int _invokes;
2823 void get_new_chunk() {
2824 _cur_chunk_idx = _hrSorted->getParMarkedHeapRegionChunk(_chunk_size);
2825 _cur_chunk_end = _cur_chunk_idx + _chunk_size;
2826 }
2827 void add_region(HeapRegion* r) {
2828 if (_cur_chunk_idx == _cur_chunk_end) {
2829 get_new_chunk();
2830 }
2831 assert(_cur_chunk_idx < _cur_chunk_end, "postcondition");
2832 _hrSorted->setMarkedHeapRegion(_cur_chunk_idx, r);
2833 _marked_regions_added++;
2834 _cur_chunk_idx++;
2835 }
2837 public:
2838 ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
2839 jint chunk_size,
2840 int worker) :
2841 _hrSorted(hrSorted), _chunk_size(chunk_size), _worker(worker),
2842 _marked_regions_added(0), _cur_chunk_idx(0), _cur_chunk_end(0),
2843 _invokes(0)
2844 {}
2846 bool doHeapRegion(HeapRegion* r) {
2847 // We only include humongous regions in collection
2848 // sets when concurrent mark shows that their contained object is
2849 // unreachable.
2850 _invokes++;
2852 // Do we have any marking information for this region?
2853 if (r->is_marked()) {
2854 // We don't include humongous regions in collection
2855 // sets because we collect them immediately at the end of a marking
2856 // cycle.
2857 // We also do not include young regions in collection sets
2858 if (!r->isHumongous() && !r->is_young()) {
2859 add_region(r);
2860 }
2861 }
2862 return false;
2863 }
2864 jint marked_regions_added() { return _marked_regions_added; }
2865 int invokes() { return _invokes; }
2866 };
2868 class ParKnownGarbageTask: public AbstractGangTask {
2869 CollectionSetChooser* _hrSorted;
2870 jint _chunk_size;
2871 G1CollectedHeap* _g1;
2872 public:
2873 ParKnownGarbageTask(CollectionSetChooser* hrSorted, jint chunk_size) :
2874 AbstractGangTask("ParKnownGarbageTask"),
2875 _hrSorted(hrSorted), _chunk_size(chunk_size),
2876 _g1(G1CollectedHeap::heap())
2877 {}
2879 void work(int i) {
2880 ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size, i);
2881 // Back to zero for the claim value.
2882 _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, i,
2883 HeapRegion::InitialClaimValue);
2884 jint regions_added = parKnownGarbageCl.marked_regions_added();
2885 _hrSorted->incNumMarkedHeapRegions(regions_added);
2886 if (G1PrintParCleanupStats) {
2887 gclog_or_tty->print(" Thread %d called %d times, added %d regions to list.\n",
2888 i, parKnownGarbageCl.invokes(), regions_added);
2889 }
2890 }
2891 };
2893 void
2894 G1CollectorPolicy_BestRegionsFirst::
2895 record_concurrent_mark_cleanup_end(size_t freed_bytes,
2896 size_t max_live_bytes) {
2897 double start;
2898 if (G1PrintParCleanupStats) start = os::elapsedTime();
2899 record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
2901 _collectionSetChooser->clearMarkedHeapRegions();
2902 double clear_marked_end;
2903 if (G1PrintParCleanupStats) {
2904 clear_marked_end = os::elapsedTime();
2905 gclog_or_tty->print_cr(" clear marked regions + work1: %8.3f ms.",
2906 (clear_marked_end - start)*1000.0);
2907 }
2908 if (ParallelGCThreads > 0) {
2909 const size_t OverpartitionFactor = 4;
2910 const size_t MinChunkSize = 8;
2911 const size_t ChunkSize =
2912 MAX2(_g1->n_regions() / (ParallelGCThreads * OverpartitionFactor),
2913 MinChunkSize);
2914 _collectionSetChooser->prepareForAddMarkedHeapRegionsPar(_g1->n_regions(),
2915 ChunkSize);
2916 ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
2917 (int) ChunkSize);
2918 _g1->workers()->run_task(&parKnownGarbageTask);
2920 assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2921 "sanity check");
2922 } else {
2923 KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
2924 _g1->heap_region_iterate(&knownGarbagecl);
2925 }
2926 double known_garbage_end;
2927 if (G1PrintParCleanupStats) {
2928 known_garbage_end = os::elapsedTime();
2929 gclog_or_tty->print_cr(" compute known garbage: %8.3f ms.",
2930 (known_garbage_end - clear_marked_end)*1000.0);
2931 }
2932 _collectionSetChooser->sortMarkedHeapRegions();
2933 double sort_end;
2934 if (G1PrintParCleanupStats) {
2935 sort_end = os::elapsedTime();
2936 gclog_or_tty->print_cr(" sorting: %8.3f ms.",
2937 (sort_end - known_garbage_end)*1000.0);
2938 }
2940 record_concurrent_mark_cleanup_end_work2();
2941 double work2_end;
2942 if (G1PrintParCleanupStats) {
2943 work2_end = os::elapsedTime();
2944 gclog_or_tty->print_cr(" work2: %8.3f ms.",
2945 (work2_end - sort_end)*1000.0);
2946 }
2947 }
2949 // Add the heap region to the collection set and return the conservative
2950 // estimate of the number of live bytes.
2951 void G1CollectorPolicy::
2952 add_to_collection_set(HeapRegion* hr) {
2953 if (G1PrintHeapRegions) {
2954 gclog_or_tty->print_cr("added region to cset "
2955 "%d:["PTR_FORMAT", "PTR_FORMAT"], "
2956 "top "PTR_FORMAT", %s",
2957 hr->hrs_index(), hr->bottom(), hr->end(),
2958 hr->top(), hr->is_young() ? "YOUNG" : "NOT_YOUNG");
2959 }
2961 if (_g1->mark_in_progress())
2962 _g1->concurrent_mark()->registerCSetRegion(hr);
2964 assert(!hr->in_collection_set(),
2965 "should not already be in the CSet");
2966 hr->set_in_collection_set(true);
2967 hr->set_next_in_collection_set(_collection_set);
2968 _collection_set = hr;
2969 _collection_set_size++;
2970 _collection_set_bytes_used_before += hr->used();
2971 _g1->register_region_with_in_cset_fast_test(hr);
2972 }
2974 void
2975 G1CollectorPolicy_BestRegionsFirst::
2976 choose_collection_set() {
2977 double non_young_start_time_sec;
2978 start_recording_regions();
2980 guarantee(_target_pause_time_ms > -1.0
2981 NOT_PRODUCT(|| Universe::heap()->gc_cause() == GCCause::_scavenge_alot),
2982 "_target_pause_time_ms should have been set!");
2983 #ifndef PRODUCT
2984 if (_target_pause_time_ms <= -1.0) {
2985 assert(ScavengeALot && Universe::heap()->gc_cause() == GCCause::_scavenge_alot, "Error");
2986 _target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
2987 }
2988 #endif
2989 assert(_collection_set == NULL, "Precondition");
2991 double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
2992 double predicted_pause_time_ms = base_time_ms;
2994 double target_time_ms = _target_pause_time_ms;
2995 double time_remaining_ms = target_time_ms - base_time_ms;
2997 // the 10% and 50% values are arbitrary...
2998 if (time_remaining_ms < 0.10*target_time_ms) {
2999 time_remaining_ms = 0.50 * target_time_ms;
3000 _within_target = false;
3001 } else {
3002 _within_target = true;
3003 }
3005 // We figure out the number of bytes available for future to-space.
3006 // For new regions without marking information, we must assume the
3007 // worst-case of complete survival. If we have marking information for a
3008 // region, we can bound the amount of live data. We can add a number of
3009 // such regions, as long as the sum of the live data bounds does not
3010 // exceed the available evacuation space.
3011 size_t max_live_bytes = _g1->free_regions() * HeapRegion::GrainBytes;
3013 size_t expansion_bytes =
3014 _g1->expansion_regions() * HeapRegion::GrainBytes;
3016 _collection_set_bytes_used_before = 0;
3017 _collection_set_size = 0;
3019 // Adjust for expansion and slop.
3020 max_live_bytes = max_live_bytes + expansion_bytes;
3022 assert(_g1->regions_accounted_for(), "Region leakage!");
3024 HeapRegion* hr;
3025 if (in_young_gc_mode()) {
3026 double young_start_time_sec = os::elapsedTime();
3028 if (G1PolicyVerbose > 0) {
3029 gclog_or_tty->print_cr("Adding %d young regions to the CSet",
3030 _g1->young_list_length());
3031 }
3032 _young_cset_length = 0;
3033 _last_young_gc_full = full_young_gcs() ? true : false;
3034 if (_last_young_gc_full)
3035 ++_full_young_pause_num;
3036 else
3037 ++_partial_young_pause_num;
3038 hr = _g1->pop_region_from_young_list();
3039 while (hr != NULL) {
3041 assert( hr->young_index_in_cset() == -1, "invariant" );
3042 assert( hr->age_in_surv_rate_group() != -1, "invariant" );
3043 hr->set_young_index_in_cset((int) _young_cset_length);
3045 ++_young_cset_length;
3046 double predicted_time_ms = predict_region_elapsed_time_ms(hr, true);
3047 time_remaining_ms -= predicted_time_ms;
3048 predicted_pause_time_ms += predicted_time_ms;
3049 assert(!hr->in_collection_set(), "invariant");
3050 add_to_collection_set(hr);
3051 record_cset_region(hr, true);
3052 max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
3053 if (G1PolicyVerbose > 0) {
3054 gclog_or_tty->print_cr(" Added [" PTR_FORMAT ", " PTR_FORMAT") to CS.",
3055 hr->bottom(), hr->end());
3056 gclog_or_tty->print_cr(" (" SIZE_FORMAT " KB left in heap.)",
3057 max_live_bytes/K);
3058 }
3059 hr = _g1->pop_region_from_young_list();
3060 }
3062 record_scan_only_regions(_g1->young_list_scan_only_length());
3064 double young_end_time_sec = os::elapsedTime();
3065 _recorded_young_cset_choice_time_ms =
3066 (young_end_time_sec - young_start_time_sec) * 1000.0;
3068 non_young_start_time_sec = os::elapsedTime();
3070 if (_young_cset_length > 0 && _last_young_gc_full) {
3071 // don't bother adding more regions...
3072 goto choose_collection_set_end;
3073 }
3074 }
3076 if (!in_young_gc_mode() || !full_young_gcs()) {
3077 bool should_continue = true;
3078 NumberSeq seq;
3079 double avg_prediction = 100000000000000000.0; // something very large
3080 do {
3081 hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
3082 avg_prediction);
3083 if (hr != NULL) {
3084 double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
3085 time_remaining_ms -= predicted_time_ms;
3086 predicted_pause_time_ms += predicted_time_ms;
3087 add_to_collection_set(hr);
3088 record_cset_region(hr, false);
3089 max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
3090 if (G1PolicyVerbose > 0) {
3091 gclog_or_tty->print_cr(" (" SIZE_FORMAT " KB left in heap.)",
3092 max_live_bytes/K);
3093 }
3094 seq.add(predicted_time_ms);
3095 avg_prediction = seq.avg() + seq.sd();
3096 }
3097 should_continue =
3098 ( hr != NULL) &&
3099 ( (adaptive_young_list_length()) ? time_remaining_ms > 0.0
3100 : _collection_set_size < _young_list_fixed_length );
3101 } while (should_continue);
3103 if (!adaptive_young_list_length() &&
3104 _collection_set_size < _young_list_fixed_length)
3105 _should_revert_to_full_young_gcs = true;
3106 }
3108 choose_collection_set_end:
3109 count_CS_bytes_used();
3111 end_recording_regions();
3113 double non_young_end_time_sec = os::elapsedTime();
3114 _recorded_non_young_cset_choice_time_ms =
3115 (non_young_end_time_sec - non_young_start_time_sec) * 1000.0;
3116 }
3118 void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() {
3119 G1CollectorPolicy::record_full_collection_end();
3120 _collectionSetChooser->updateAfterFullCollection();
3121 }
3123 void G1CollectorPolicy_BestRegionsFirst::
3124 expand_if_possible(size_t numRegions) {
3125 size_t expansion_bytes = numRegions * HeapRegion::GrainBytes;
3126 _g1->expand(expansion_bytes);
3127 }
3129 void G1CollectorPolicy_BestRegionsFirst::
3130 record_collection_pause_end(bool abandoned) {
3131 G1CollectorPolicy::record_collection_pause_end(abandoned);
3132 assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
3133 }