1 /*
2 * Copyright (c) 2016, 2018, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "gc/g1/g1CollectedHeap.hpp"
27 #include "gc/g1/g1CollectionSet.hpp"
28 #include "gc/g1/g1CollectorState.hpp"
29 #include "gc/g1/g1Policy.hpp"
30 #include "gc/g1/heapRegion.inline.hpp"
31 #include "gc/g1/heapRegionRemSet.hpp"
32 #include "gc/g1/heapRegionSet.hpp"
33 #include "logging/logStream.hpp"
34 #include "utilities/debug.hpp"
35 #include "utilities/quickSort.hpp"
36
collector_state()37 G1CollectorState* G1CollectionSet::collector_state() {
38 return _g1h->collector_state();
39 }
40
phase_times()41 G1GCPhaseTimes* G1CollectionSet::phase_times() {
42 return _policy->phase_times();
43 }
44
cset_chooser()45 CollectionSetChooser* G1CollectionSet::cset_chooser() {
46 return _cset_chooser;
47 }
48
predict_region_elapsed_time_ms(HeapRegion * hr)49 double G1CollectionSet::predict_region_elapsed_time_ms(HeapRegion* hr) {
50 return _policy->predict_region_elapsed_time_ms(hr, collector_state()->in_young_only_phase());
51 }
52
G1CollectionSet(G1CollectedHeap * g1h,G1Policy * policy)53 G1CollectionSet::G1CollectionSet(G1CollectedHeap* g1h, G1Policy* policy) :
54 _g1h(g1h),
55 _policy(policy),
56 _cset_chooser(new CollectionSetChooser()),
57 _eden_region_length(0),
58 _survivor_region_length(0),
59 _old_region_length(0),
60 _bytes_used_before(0),
61 _recorded_rs_lengths(0),
62 _collection_set_regions(NULL),
63 _collection_set_cur_length(0),
64 _collection_set_max_length(0),
65 // Incremental CSet attributes
66 _inc_build_state(Inactive),
67 _inc_bytes_used_before(0),
68 _inc_recorded_rs_lengths(0),
69 _inc_recorded_rs_lengths_diffs(0),
70 _inc_predicted_elapsed_time_ms(0.0),
71 _inc_predicted_elapsed_time_ms_diffs(0.0) {
72 }
73
~G1CollectionSet()74 G1CollectionSet::~G1CollectionSet() {
75 if (_collection_set_regions != NULL) {
76 FREE_C_HEAP_ARRAY(uint, _collection_set_regions);
77 }
78 delete _cset_chooser;
79 }
80
init_region_lengths(uint eden_cset_region_length,uint survivor_cset_region_length)81 void G1CollectionSet::init_region_lengths(uint eden_cset_region_length,
82 uint survivor_cset_region_length) {
83 assert_at_safepoint_on_vm_thread();
84
85 _eden_region_length = eden_cset_region_length;
86 _survivor_region_length = survivor_cset_region_length;
87
88 assert((size_t) young_region_length() == _collection_set_cur_length,
89 "Young region length %u should match collection set length " SIZE_FORMAT, young_region_length(), _collection_set_cur_length);
90
91 _old_region_length = 0;
92 }
93
initialize(uint max_region_length)94 void G1CollectionSet::initialize(uint max_region_length) {
95 guarantee(_collection_set_regions == NULL, "Must only initialize once.");
96 _collection_set_max_length = max_region_length;
97 _collection_set_regions = NEW_C_HEAP_ARRAY(uint, max_region_length, mtGC);
98 }
99
set_recorded_rs_lengths(size_t rs_lengths)100 void G1CollectionSet::set_recorded_rs_lengths(size_t rs_lengths) {
101 _recorded_rs_lengths = rs_lengths;
102 }
103
104 // Add the heap region at the head of the non-incremental collection set
add_old_region(HeapRegion * hr)105 void G1CollectionSet::add_old_region(HeapRegion* hr) {
106 assert_at_safepoint_on_vm_thread();
107
108 assert(_inc_build_state == Active, "Precondition");
109 assert(hr->is_old(), "the region should be old");
110
111 assert(!hr->in_collection_set(), "should not already be in the CSet");
112 _g1h->register_old_region_with_cset(hr);
113
114 _collection_set_regions[_collection_set_cur_length++] = hr->hrm_index();
115 assert(_collection_set_cur_length <= _collection_set_max_length, "Collection set now larger than maximum size.");
116
117 _bytes_used_before += hr->used();
118 size_t rs_length = hr->rem_set()->occupied();
119 _recorded_rs_lengths += rs_length;
120 _old_region_length += 1;
121 }
122
123 // Initialize the per-collection-set information
start_incremental_building()124 void G1CollectionSet::start_incremental_building() {
125 assert(_collection_set_cur_length == 0, "Collection set must be empty before starting a new collection set.");
126 assert(_inc_build_state == Inactive, "Precondition");
127
128 _inc_bytes_used_before = 0;
129
130 _inc_recorded_rs_lengths = 0;
131 _inc_recorded_rs_lengths_diffs = 0;
132 _inc_predicted_elapsed_time_ms = 0.0;
133 _inc_predicted_elapsed_time_ms_diffs = 0.0;
134 _inc_build_state = Active;
135 }
136
finalize_incremental_building()137 void G1CollectionSet::finalize_incremental_building() {
138 assert(_inc_build_state == Active, "Precondition");
139 assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");
140
141 // The two "main" fields, _inc_recorded_rs_lengths and
142 // _inc_predicted_elapsed_time_ms, are updated by the thread
143 // that adds a new region to the CSet. Further updates by the
144 // concurrent refinement thread that samples the young RSet lengths
145 // are accumulated in the *_diffs fields. Here we add the diffs to
146 // the "main" fields.
147
148 if (_inc_recorded_rs_lengths_diffs >= 0) {
149 _inc_recorded_rs_lengths += _inc_recorded_rs_lengths_diffs;
150 } else {
151 // This is defensive. The diff should in theory be always positive
152 // as RSets can only grow between GCs. However, given that we
153 // sample their size concurrently with other threads updating them
154 // it's possible that we might get the wrong size back, which
155 // could make the calculations somewhat inaccurate.
156 size_t diffs = (size_t) (-_inc_recorded_rs_lengths_diffs);
157 if (_inc_recorded_rs_lengths >= diffs) {
158 _inc_recorded_rs_lengths -= diffs;
159 } else {
160 _inc_recorded_rs_lengths = 0;
161 }
162 }
163 _inc_predicted_elapsed_time_ms += _inc_predicted_elapsed_time_ms_diffs;
164
165 _inc_recorded_rs_lengths_diffs = 0;
166 _inc_predicted_elapsed_time_ms_diffs = 0.0;
167 }
168
clear()169 void G1CollectionSet::clear() {
170 assert_at_safepoint_on_vm_thread();
171 _collection_set_cur_length = 0;
172 }
173
iterate(HeapRegionClosure * cl) const174 void G1CollectionSet::iterate(HeapRegionClosure* cl) const {
175 iterate_from(cl, 0, 1);
176 }
177
iterate_from(HeapRegionClosure * cl,uint worker_id,uint total_workers) const178 void G1CollectionSet::iterate_from(HeapRegionClosure* cl, uint worker_id, uint total_workers) const {
179 size_t len = _collection_set_cur_length;
180 OrderAccess::loadload();
181 if (len == 0) {
182 return;
183 }
184 size_t start_pos = (worker_id * len) / total_workers;
185 size_t cur_pos = start_pos;
186
187 do {
188 HeapRegion* r = _g1h->region_at(_collection_set_regions[cur_pos]);
189 bool result = cl->do_heap_region(r);
190 if (result) {
191 cl->set_incomplete();
192 return;
193 }
194 cur_pos++;
195 if (cur_pos == len) {
196 cur_pos = 0;
197 }
198 } while (cur_pos != start_pos);
199 }
200
update_young_region_prediction(HeapRegion * hr,size_t new_rs_length)201 void G1CollectionSet::update_young_region_prediction(HeapRegion* hr,
202 size_t new_rs_length) {
203 // Update the CSet information that is dependent on the new RS length
204 assert(hr->is_young(), "Precondition");
205 assert(!SafepointSynchronize::is_at_safepoint(), "should not be at a safepoint");
206
207 // We could have updated _inc_recorded_rs_lengths and
208 // _inc_predicted_elapsed_time_ms directly but we'd need to do
209 // that atomically, as this code is executed by a concurrent
210 // refinement thread, potentially concurrently with a mutator thread
211 // allocating a new region and also updating the same fields. To
212 // avoid the atomic operations we accumulate these updates on two
213 // separate fields (*_diffs) and we'll just add them to the "main"
214 // fields at the start of a GC.
215
216 ssize_t old_rs_length = (ssize_t) hr->recorded_rs_length();
217 ssize_t rs_lengths_diff = (ssize_t) new_rs_length - old_rs_length;
218 _inc_recorded_rs_lengths_diffs += rs_lengths_diff;
219
220 double old_elapsed_time_ms = hr->predicted_elapsed_time_ms();
221 double new_region_elapsed_time_ms = predict_region_elapsed_time_ms(hr);
222 double elapsed_ms_diff = new_region_elapsed_time_ms - old_elapsed_time_ms;
223 _inc_predicted_elapsed_time_ms_diffs += elapsed_ms_diff;
224
225 hr->set_recorded_rs_length(new_rs_length);
226 hr->set_predicted_elapsed_time_ms(new_region_elapsed_time_ms);
227 }
228
add_young_region_common(HeapRegion * hr)229 void G1CollectionSet::add_young_region_common(HeapRegion* hr) {
230 assert(hr->is_young(), "invariant");
231 assert(_inc_build_state == Active, "Precondition");
232
233 size_t collection_set_length = _collection_set_cur_length;
234 assert(collection_set_length <= INT_MAX, "Collection set is too large with %d entries", (int)collection_set_length);
235 hr->set_young_index_in_cset((int)collection_set_length);
236
237 _collection_set_regions[collection_set_length] = hr->hrm_index();
238 // Concurrent readers must observe the store of the value in the array before an
239 // update to the length field.
240 OrderAccess::storestore();
241 _collection_set_cur_length++;
242 assert(_collection_set_cur_length <= _collection_set_max_length, "Collection set larger than maximum allowed.");
243
244 // This routine is used when:
245 // * adding survivor regions to the incremental cset at the end of an
246 // evacuation pause or
247 // * adding the current allocation region to the incremental cset
248 // when it is retired.
249 // Therefore this routine may be called at a safepoint by the
250 // VM thread, or in-between safepoints by mutator threads (when
251 // retiring the current allocation region)
252 // We need to clear and set the cached recorded/cached collection set
253 // information in the heap region here (before the region gets added
254 // to the collection set). An individual heap region's cached values
255 // are calculated, aggregated with the policy collection set info,
256 // and cached in the heap region here (initially) and (subsequently)
257 // by the Young List sampling code.
258 // Ignore calls to this due to retirement during full gc.
259
260 if (!_g1h->collector_state()->in_full_gc()) {
261 size_t rs_length = hr->rem_set()->occupied();
262 double region_elapsed_time_ms = predict_region_elapsed_time_ms(hr);
263
264 // Cache the values we have added to the aggregated information
265 // in the heap region in case we have to remove this region from
266 // the incremental collection set, or it is updated by the
267 // rset sampling code
268 hr->set_recorded_rs_length(rs_length);
269 hr->set_predicted_elapsed_time_ms(region_elapsed_time_ms);
270
271 _inc_recorded_rs_lengths += rs_length;
272 _inc_predicted_elapsed_time_ms += region_elapsed_time_ms;
273 _inc_bytes_used_before += hr->used();
274 }
275
276 assert(!hr->in_collection_set(), "invariant");
277 _g1h->register_young_region_with_cset(hr);
278 }
279
add_survivor_regions(HeapRegion * hr)280 void G1CollectionSet::add_survivor_regions(HeapRegion* hr) {
281 assert(hr->is_survivor(), "Must only add survivor regions, but is %s", hr->get_type_str());
282 add_young_region_common(hr);
283 }
284
add_eden_region(HeapRegion * hr)285 void G1CollectionSet::add_eden_region(HeapRegion* hr) {
286 assert(hr->is_eden(), "Must only add eden regions, but is %s", hr->get_type_str());
287 add_young_region_common(hr);
288 }
289
290 #ifndef PRODUCT
291 class G1VerifyYoungAgesClosure : public HeapRegionClosure {
292 public:
293 bool _valid;
294 public:
G1VerifyYoungAgesClosure()295 G1VerifyYoungAgesClosure() : HeapRegionClosure(), _valid(true) { }
296
do_heap_region(HeapRegion * r)297 virtual bool do_heap_region(HeapRegion* r) {
298 guarantee(r->is_young(), "Region must be young but is %s", r->get_type_str());
299
300 SurvRateGroup* group = r->surv_rate_group();
301
302 if (group == NULL) {
303 log_error(gc, verify)("## encountered NULL surv_rate_group in young region");
304 _valid = false;
305 }
306
307 if (r->age_in_surv_rate_group() < 0) {
308 log_error(gc, verify)("## encountered negative age in young region");
309 _valid = false;
310 }
311
312 return false;
313 }
314
valid() const315 bool valid() const { return _valid; }
316 };
317
verify_young_ages()318 bool G1CollectionSet::verify_young_ages() {
319 assert_at_safepoint_on_vm_thread();
320
321 G1VerifyYoungAgesClosure cl;
322 iterate(&cl);
323
324 if (!cl.valid()) {
325 LogStreamHandle(Error, gc, verify) log;
326 print(&log);
327 }
328
329 return cl.valid();
330 }
331
332 class G1PrintCollectionSetDetailClosure : public HeapRegionClosure {
333 outputStream* _st;
334 public:
G1PrintCollectionSetDetailClosure(outputStream * st)335 G1PrintCollectionSetDetailClosure(outputStream* st) : HeapRegionClosure(), _st(st) { }
336
do_heap_region(HeapRegion * r)337 virtual bool do_heap_region(HeapRegion* r) {
338 assert(r->in_collection_set(), "Region %u should be in collection set", r->hrm_index());
339 _st->print_cr(" " HR_FORMAT ", P: " PTR_FORMAT "N: " PTR_FORMAT ", age: %4d",
340 HR_FORMAT_PARAMS(r),
341 p2i(r->prev_top_at_mark_start()),
342 p2i(r->next_top_at_mark_start()),
343 r->age_in_surv_rate_group_cond());
344 return false;
345 }
346 };
347
print(outputStream * st)348 void G1CollectionSet::print(outputStream* st) {
349 st->print_cr("\nCollection_set:");
350
351 G1PrintCollectionSetDetailClosure cl(st);
352 iterate(&cl);
353 }
354 #endif // !PRODUCT
355
finalize_young_part(double target_pause_time_ms,G1SurvivorRegions * survivors)356 double G1CollectionSet::finalize_young_part(double target_pause_time_ms, G1SurvivorRegions* survivors) {
357 double young_start_time_sec = os::elapsedTime();
358
359 finalize_incremental_building();
360
361 guarantee(target_pause_time_ms > 0.0,
362 "target_pause_time_ms = %1.6lf should be positive", target_pause_time_ms);
363
364 size_t pending_cards = _policy->pending_cards();
365 double base_time_ms = _policy->predict_base_elapsed_time_ms(pending_cards);
366 double time_remaining_ms = MAX2(target_pause_time_ms - base_time_ms, 0.0);
367
368 log_trace(gc, ergo, cset)("Start choosing CSet. pending cards: " SIZE_FORMAT " predicted base time: %1.2fms remaining time: %1.2fms target pause time: %1.2fms",
369 pending_cards, base_time_ms, time_remaining_ms, target_pause_time_ms);
370
371 // The young list is laid with the survivor regions from the previous
372 // pause are appended to the RHS of the young list, i.e.
373 // [Newly Young Regions ++ Survivors from last pause].
374
375 uint survivor_region_length = survivors->length();
376 uint eden_region_length = _g1h->eden_regions_count();
377 init_region_lengths(eden_region_length, survivor_region_length);
378
379 verify_young_cset_indices();
380
381 // Clear the fields that point to the survivor list - they are all young now.
382 survivors->convert_to_eden();
383
384 _bytes_used_before = _inc_bytes_used_before;
385 time_remaining_ms = MAX2(time_remaining_ms - _inc_predicted_elapsed_time_ms, 0.0);
386
387 log_trace(gc, ergo, cset)("Add young regions to CSet. eden: %u regions, survivors: %u regions, predicted young region time: %1.2fms, target pause time: %1.2fms",
388 eden_region_length, survivor_region_length, _inc_predicted_elapsed_time_ms, target_pause_time_ms);
389
390 // The number of recorded young regions is the incremental
391 // collection set's current size
392 set_recorded_rs_lengths(_inc_recorded_rs_lengths);
393
394 double young_end_time_sec = os::elapsedTime();
395 phase_times()->record_young_cset_choice_time_ms((young_end_time_sec - young_start_time_sec) * 1000.0);
396
397 return time_remaining_ms;
398 }
399
compare_region_idx(const uint a,const uint b)400 static int compare_region_idx(const uint a, const uint b) {
401 if (a > b) {
402 return 1;
403 } else if (a == b) {
404 return 0;
405 } else {
406 return -1;
407 }
408 }
409
finalize_old_part(double time_remaining_ms)410 void G1CollectionSet::finalize_old_part(double time_remaining_ms) {
411 double non_young_start_time_sec = os::elapsedTime();
412 double predicted_old_time_ms = 0.0;
413
414 if (collector_state()->in_mixed_phase()) {
415 cset_chooser()->verify();
416 const uint min_old_cset_length = _policy->calc_min_old_cset_length();
417 const uint max_old_cset_length = _policy->calc_max_old_cset_length();
418
419 uint expensive_region_num = 0;
420 bool check_time_remaining = _policy->adaptive_young_list_length();
421
422 HeapRegion* hr = cset_chooser()->peek();
423 while (hr != NULL) {
424 if (old_region_length() >= max_old_cset_length) {
425 // Added maximum number of old regions to the CSet.
426 log_debug(gc, ergo, cset)("Finish adding old regions to CSet (old CSet region num reached max). old %u regions, max %u regions",
427 old_region_length(), max_old_cset_length);
428 break;
429 }
430
431 // Stop adding regions if the remaining reclaimable space is
432 // not above G1HeapWastePercent.
433 size_t reclaimable_bytes = cset_chooser()->remaining_reclaimable_bytes();
434 double reclaimable_percent = _policy->reclaimable_bytes_percent(reclaimable_bytes);
435 double threshold = (double) G1HeapWastePercent;
436 if (reclaimable_percent <= threshold) {
437 // We've added enough old regions that the amount of uncollected
438 // reclaimable space is at or below the waste threshold. Stop
439 // adding old regions to the CSet.
440 log_debug(gc, ergo, cset)("Finish adding old regions to CSet (reclaimable percentage not over threshold). "
441 "old %u regions, max %u regions, reclaimable: " SIZE_FORMAT "B (%1.2f%%) threshold: " UINTX_FORMAT "%%",
442 old_region_length(), max_old_cset_length, reclaimable_bytes, reclaimable_percent, G1HeapWastePercent);
443 break;
444 }
445
446 double predicted_time_ms = predict_region_elapsed_time_ms(hr);
447 if (check_time_remaining) {
448 if (predicted_time_ms > time_remaining_ms) {
449 // Too expensive for the current CSet.
450
451 if (old_region_length() >= min_old_cset_length) {
452 // We have added the minimum number of old regions to the CSet,
453 // we are done with this CSet.
454 log_debug(gc, ergo, cset)("Finish adding old regions to CSet (predicted time is too high). "
455 "predicted time: %1.2fms, remaining time: %1.2fms old %u regions, min %u regions",
456 predicted_time_ms, time_remaining_ms, old_region_length(), min_old_cset_length);
457 break;
458 }
459
460 // We'll add it anyway given that we haven't reached the
461 // minimum number of old regions.
462 expensive_region_num += 1;
463 }
464 } else {
465 if (old_region_length() >= min_old_cset_length) {
466 // In the non-auto-tuning case, we'll finish adding regions
467 // to the CSet if we reach the minimum.
468
469 log_debug(gc, ergo, cset)("Finish adding old regions to CSet (old CSet region num reached min). old %u regions, min %u regions",
470 old_region_length(), min_old_cset_length);
471 break;
472 }
473 }
474
475 // We will add this region to the CSet.
476 time_remaining_ms = MAX2(time_remaining_ms - predicted_time_ms, 0.0);
477 predicted_old_time_ms += predicted_time_ms;
478 cset_chooser()->pop(); // already have region via peek()
479 _g1h->old_set_remove(hr);
480 add_old_region(hr);
481
482 hr = cset_chooser()->peek();
483 }
484 if (hr == NULL) {
485 log_debug(gc, ergo, cset)("Finish adding old regions to CSet (candidate old regions not available)");
486 }
487
488 if (expensive_region_num > 0) {
489 // We print the information once here at the end, predicated on
490 // whether we added any apparently expensive regions or not, to
491 // avoid generating output per region.
492 log_debug(gc, ergo, cset)("Added expensive regions to CSet (old CSet region num not reached min)."
493 "old: %u regions, expensive: %u regions, min: %u regions, remaining time: %1.2fms",
494 old_region_length(), expensive_region_num, min_old_cset_length, time_remaining_ms);
495 }
496
497 cset_chooser()->verify();
498 }
499
500 stop_incremental_building();
501
502 log_debug(gc, ergo, cset)("Finish choosing CSet. old: %u regions, predicted old region time: %1.2fms, time remaining: %1.2f",
503 old_region_length(), predicted_old_time_ms, time_remaining_ms);
504
505 double non_young_end_time_sec = os::elapsedTime();
506 phase_times()->record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);
507
508 QuickSort::sort(_collection_set_regions, _collection_set_cur_length, compare_region_idx, true);
509 }
510
511 #ifdef ASSERT
512 class G1VerifyYoungCSetIndicesClosure : public HeapRegionClosure {
513 private:
514 size_t _young_length;
515 int* _heap_region_indices;
516 public:
G1VerifyYoungCSetIndicesClosure(size_t young_length)517 G1VerifyYoungCSetIndicesClosure(size_t young_length) : HeapRegionClosure(), _young_length(young_length) {
518 _heap_region_indices = NEW_C_HEAP_ARRAY(int, young_length, mtGC);
519 for (size_t i = 0; i < young_length; i++) {
520 _heap_region_indices[i] = -1;
521 }
522 }
~G1VerifyYoungCSetIndicesClosure()523 ~G1VerifyYoungCSetIndicesClosure() {
524 FREE_C_HEAP_ARRAY(int, _heap_region_indices);
525 }
526
do_heap_region(HeapRegion * r)527 virtual bool do_heap_region(HeapRegion* r) {
528 const int idx = r->young_index_in_cset();
529
530 assert(idx > -1, "Young index must be set for all regions in the incremental collection set but is not for region %u.", r->hrm_index());
531 assert((size_t)idx < _young_length, "Young cset index too large for region %u", r->hrm_index());
532
533 assert(_heap_region_indices[idx] == -1,
534 "Index %d used by multiple regions, first use by region %u, second by region %u",
535 idx, _heap_region_indices[idx], r->hrm_index());
536
537 _heap_region_indices[idx] = r->hrm_index();
538
539 return false;
540 }
541 };
542
verify_young_cset_indices() const543 void G1CollectionSet::verify_young_cset_indices() const {
544 assert_at_safepoint_on_vm_thread();
545
546 G1VerifyYoungCSetIndicesClosure cl(_collection_set_cur_length);
547 iterate(&cl);
548 }
549 #endif
550