Print this page
G1: Use SoftMaxHeapSize to guide GC heuristics
Split |
Close |
Expand all |
Collapse all |
--- old/src/hotspot/share/gc/g1/g1CollectedHeap.cpp
+++ new/src/hotspot/share/gc/g1/g1CollectedHeap.cpp
1 1 /*
2 2 * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved.
3 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 4 *
5 5 * This code is free software; you can redistribute it and/or modify it
6 6 * under the terms of the GNU General Public License version 2 only, as
7 7 * published by the Free Software Foundation.
8 8 *
9 9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 12 * version 2 for more details (a copy is included in the LICENSE file that
13 13 * accompanied this code).
14 14 *
15 15 * You should have received a copy of the GNU General Public License version
16 16 * 2 along with this work; if not, write to the Free Software Foundation,
17 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 18 *
19 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 20 * or visit www.oracle.com if you need additional information or have any
21 21 * questions.
22 22 *
23 23 */
24 24
25 25 #include "precompiled.hpp"
26 26 #include "classfile/classLoaderDataGraph.hpp"
27 27 #include "classfile/metadataOnStackMark.hpp"
28 28 #include "classfile/stringTable.hpp"
29 29 #include "code/codeCache.hpp"
30 30 #include "code/icBuffer.hpp"
31 31 #include "gc/g1/g1Allocator.inline.hpp"
32 32 #include "gc/g1/g1Arguments.hpp"
33 33 #include "gc/g1/g1BarrierSet.hpp"
34 34 #include "gc/g1/g1CardTableEntryClosure.hpp"
35 35 #include "gc/g1/g1CollectedHeap.inline.hpp"
36 36 #include "gc/g1/g1CollectionSet.hpp"
37 37 #include "gc/g1/g1CollectorState.hpp"
38 38 #include "gc/g1/g1ConcurrentRefine.hpp"
39 39 #include "gc/g1/g1ConcurrentRefineThread.hpp"
40 40 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
41 41 #include "gc/g1/g1DirtyCardQueue.hpp"
42 42 #include "gc/g1/g1EvacStats.inline.hpp"
43 43 #include "gc/g1/g1FullCollector.hpp"
44 44 #include "gc/g1/g1GCPhaseTimes.hpp"
45 45 #include "gc/g1/g1HeapSizingPolicy.hpp"
46 46 #include "gc/g1/g1HeapTransition.hpp"
47 47 #include "gc/g1/g1HeapVerifier.hpp"
48 48 #include "gc/g1/g1HotCardCache.hpp"
49 49 #include "gc/g1/g1MemoryPool.hpp"
50 50 #include "gc/g1/g1OopClosures.inline.hpp"
51 51 #include "gc/g1/g1ParallelCleaning.hpp"
52 52 #include "gc/g1/g1ParScanThreadState.inline.hpp"
53 53 #include "gc/g1/g1Policy.hpp"
54 54 #include "gc/g1/g1RedirtyCardsQueue.hpp"
55 55 #include "gc/g1/g1RegionToSpaceMapper.hpp"
56 56 #include "gc/g1/g1RemSet.hpp"
57 57 #include "gc/g1/g1RootClosures.hpp"
58 58 #include "gc/g1/g1RootProcessor.hpp"
59 59 #include "gc/g1/g1SATBMarkQueueSet.hpp"
60 60 #include "gc/g1/g1StringDedup.hpp"
61 61 #include "gc/g1/g1ThreadLocalData.hpp"
62 62 #include "gc/g1/g1Trace.hpp"
63 63 #include "gc/g1/g1YCTypes.hpp"
64 64 #include "gc/g1/g1YoungRemSetSamplingThread.hpp"
65 65 #include "gc/g1/g1VMOperations.hpp"
66 66 #include "gc/g1/heapRegion.inline.hpp"
67 67 #include "gc/g1/heapRegionRemSet.hpp"
68 68 #include "gc/g1/heapRegionSet.inline.hpp"
69 69 #include "gc/shared/gcBehaviours.hpp"
70 70 #include "gc/shared/gcHeapSummary.hpp"
71 71 #include "gc/shared/gcId.hpp"
72 72 #include "gc/shared/gcLocker.hpp"
73 73 #include "gc/shared/gcTimer.hpp"
74 74 #include "gc/shared/gcTraceTime.inline.hpp"
75 75 #include "gc/shared/generationSpec.hpp"
76 76 #include "gc/shared/isGCActiveMark.hpp"
77 77 #include "gc/shared/locationPrinter.inline.hpp"
78 78 #include "gc/shared/oopStorageParState.hpp"
79 79 #include "gc/shared/preservedMarks.inline.hpp"
80 80 #include "gc/shared/suspendibleThreadSet.hpp"
81 81 #include "gc/shared/referenceProcessor.inline.hpp"
82 82 #include "gc/shared/taskqueue.inline.hpp"
83 83 #include "gc/shared/weakProcessor.inline.hpp"
84 84 #include "gc/shared/workerPolicy.hpp"
85 85 #include "logging/log.hpp"
86 86 #include "memory/allocation.hpp"
87 87 #include "memory/iterator.hpp"
88 88 #include "memory/resourceArea.hpp"
89 89 #include "memory/universe.hpp"
90 90 #include "oops/access.inline.hpp"
91 91 #include "oops/compressedOops.inline.hpp"
92 92 #include "oops/oop.inline.hpp"
93 93 #include "runtime/atomic.hpp"
94 94 #include "runtime/flags/flagSetting.hpp"
95 95 #include "runtime/handles.inline.hpp"
96 96 #include "runtime/init.hpp"
97 97 #include "runtime/orderAccess.hpp"
98 98 #include "runtime/threadSMR.hpp"
99 99 #include "runtime/vmThread.hpp"
100 100 #include "utilities/align.hpp"
101 101 #include "utilities/bitMap.inline.hpp"
102 102 #include "utilities/globalDefinitions.hpp"
103 103 #include "utilities/stack.inline.hpp"
104 104
105 105 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
106 106
107 107 // INVARIANTS/NOTES
108 108 //
109 109 // All allocation activity covered by the G1CollectedHeap interface is
110 110 // serialized by acquiring the HeapLock. This happens in mem_allocate
111 111 // and allocate_new_tlab, which are the "entry" points to the
112 112 // allocation code from the rest of the JVM. (Note that this does not
113 113 // apply to TLAB allocation, which is not part of this interface: it
114 114 // is done by clients of this interface.)
115 115
116 116 class RedirtyLoggedCardTableEntryClosure : public G1CardTableEntryClosure {
117 117 private:
118 118 size_t _num_dirtied;
119 119 G1CollectedHeap* _g1h;
120 120 G1CardTable* _g1_ct;
121 121
122 122 HeapRegion* region_for_card(CardValue* card_ptr) const {
123 123 return _g1h->heap_region_containing(_g1_ct->addr_for(card_ptr));
124 124 }
125 125
126 126 bool will_become_free(HeapRegion* hr) const {
127 127 // A region will be freed by free_collection_set if the region is in the
128 128 // collection set and has not had an evacuation failure.
129 129 return _g1h->is_in_cset(hr) && !hr->evacuation_failed();
130 130 }
131 131
132 132 public:
133 133 RedirtyLoggedCardTableEntryClosure(G1CollectedHeap* g1h) : G1CardTableEntryClosure(),
134 134 _num_dirtied(0), _g1h(g1h), _g1_ct(g1h->card_table()) { }
135 135
136 136 void do_card_ptr(CardValue* card_ptr, uint worker_id) {
137 137 HeapRegion* hr = region_for_card(card_ptr);
138 138
139 139 // Should only dirty cards in regions that won't be freed.
140 140 if (!will_become_free(hr)) {
141 141 *card_ptr = G1CardTable::dirty_card_val();
142 142 _num_dirtied++;
143 143 }
144 144 }
145 145
146 146 size_t num_dirtied() const { return _num_dirtied; }
147 147 };
148 148
149 149
150 150 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
151 151 HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);
152 152 }
153 153
154 154 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {
155 155 // The from card cache is not the memory that is actually committed. So we cannot
156 156 // take advantage of the zero_filled parameter.
157 157 reset_from_card_cache(start_idx, num_regions);
158 158 }
159 159
160 160 Tickspan G1CollectedHeap::run_task(AbstractGangTask* task) {
161 161 Ticks start = Ticks::now();
162 162 workers()->run_task(task, workers()->active_workers());
163 163 return Ticks::now() - start;
164 164 }
165 165
166 166 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
167 167 MemRegion mr) {
168 168 return new HeapRegion(hrs_index, bot(), mr);
169 169 }
170 170
171 171 // Private methods.
172 172
173 173 HeapRegion* G1CollectedHeap::new_region(size_t word_size,
174 174 HeapRegionType type,
175 175 bool do_expand,
176 176 uint node_index) {
177 177 assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords,
178 178 "the only time we use this to allocate a humongous region is "
179 179 "when we are allocating a single humongous region");
180 180
181 181 HeapRegion* res = _hrm->allocate_free_region(type, node_index);
182 182
183 183 if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
184 184 // Currently, only attempts to allocate GC alloc regions set
185 185 // do_expand to true. So, we should only reach here during a
186 186 // safepoint. If this assumption changes we might have to
187 187 // reconsider the use of _expand_heap_after_alloc_failure.
188 188 assert(SafepointSynchronize::is_at_safepoint(), "invariant");
189 189
190 190 log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B",
191 191 word_size * HeapWordSize);
192 192
193 193 assert(word_size * HeapWordSize < HeapRegion::GrainBytes,
194 194 "This kind of expansion should never be more than one region. Size: " SIZE_FORMAT,
195 195 word_size * HeapWordSize);
196 196 if (expand_single_region(node_index)) {
197 197 // Given that expand_single_region() succeeded in expanding the heap, and we
198 198 // always expand the heap by an amount aligned to the heap
199 199 // region size, the free list should in theory not be empty.
200 200 // In either case allocate_free_region() will check for NULL.
201 201 res = _hrm->allocate_free_region(type, node_index);
202 202 } else {
203 203 _expand_heap_after_alloc_failure = false;
204 204 }
205 205 }
206 206 return res;
207 207 }
208 208
209 209 HeapWord*
210 210 G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first,
211 211 uint num_regions,
212 212 size_t word_size) {
213 213 assert(first != G1_NO_HRM_INDEX, "pre-condition");
214 214 assert(is_humongous(word_size), "word_size should be humongous");
215 215 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
216 216
217 217 // Index of last region in the series.
218 218 uint last = first + num_regions - 1;
219 219
220 220 // We need to initialize the region(s) we just discovered. This is
221 221 // a bit tricky given that it can happen concurrently with
222 222 // refinement threads refining cards on these regions and
223 223 // potentially wanting to refine the BOT as they are scanning
224 224 // those cards (this can happen shortly after a cleanup; see CR
225 225 // 6991377). So we have to set up the region(s) carefully and in
226 226 // a specific order.
227 227
228 228 // The word size sum of all the regions we will allocate.
229 229 size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
230 230 assert(word_size <= word_size_sum, "sanity");
231 231
232 232 // This will be the "starts humongous" region.
233 233 HeapRegion* first_hr = region_at(first);
234 234 // The header of the new object will be placed at the bottom of
235 235 // the first region.
236 236 HeapWord* new_obj = first_hr->bottom();
237 237 // This will be the new top of the new object.
238 238 HeapWord* obj_top = new_obj + word_size;
239 239
240 240 // First, we need to zero the header of the space that we will be
241 241 // allocating. When we update top further down, some refinement
242 242 // threads might try to scan the region. By zeroing the header we
243 243 // ensure that any thread that will try to scan the region will
244 244 // come across the zero klass word and bail out.
245 245 //
246 246 // NOTE: It would not have been correct to have used
247 247 // CollectedHeap::fill_with_object() and make the space look like
248 248 // an int array. The thread that is doing the allocation will
249 249 // later update the object header to a potentially different array
250 250 // type and, for a very short period of time, the klass and length
251 251 // fields will be inconsistent. This could cause a refinement
252 252 // thread to calculate the object size incorrectly.
253 253 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
254 254
255 255 // Next, pad out the unused tail of the last region with filler
256 256 // objects, for improved usage accounting.
257 257 // How many words we use for filler objects.
258 258 size_t word_fill_size = word_size_sum - word_size;
259 259
260 260 // How many words memory we "waste" which cannot hold a filler object.
261 261 size_t words_not_fillable = 0;
262 262
263 263 if (word_fill_size >= min_fill_size()) {
264 264 fill_with_objects(obj_top, word_fill_size);
265 265 } else if (word_fill_size > 0) {
266 266 // We have space to fill, but we cannot fit an object there.
267 267 words_not_fillable = word_fill_size;
268 268 word_fill_size = 0;
269 269 }
270 270
271 271 // We will set up the first region as "starts humongous". This
272 272 // will also update the BOT covering all the regions to reflect
273 273 // that there is a single object that starts at the bottom of the
274 274 // first region.
275 275 first_hr->set_starts_humongous(obj_top, word_fill_size);
276 276 _policy->remset_tracker()->update_at_allocate(first_hr);
277 277 // Then, if there are any, we will set up the "continues
278 278 // humongous" regions.
279 279 HeapRegion* hr = NULL;
280 280 for (uint i = first + 1; i <= last; ++i) {
281 281 hr = region_at(i);
282 282 hr->set_continues_humongous(first_hr);
283 283 _policy->remset_tracker()->update_at_allocate(hr);
284 284 }
285 285
286 286 // Up to this point no concurrent thread would have been able to
287 287 // do any scanning on any region in this series. All the top
288 288 // fields still point to bottom, so the intersection between
289 289 // [bottom,top] and [card_start,card_end] will be empty. Before we
290 290 // update the top fields, we'll do a storestore to make sure that
291 291 // no thread sees the update to top before the zeroing of the
292 292 // object header and the BOT initialization.
293 293 OrderAccess::storestore();
294 294
295 295 // Now, we will update the top fields of the "continues humongous"
296 296 // regions except the last one.
297 297 for (uint i = first; i < last; ++i) {
298 298 hr = region_at(i);
299 299 hr->set_top(hr->end());
300 300 }
301 301
302 302 hr = region_at(last);
303 303 // If we cannot fit a filler object, we must set top to the end
304 304 // of the humongous object, otherwise we cannot iterate the heap
305 305 // and the BOT will not be complete.
306 306 hr->set_top(hr->end() - words_not_fillable);
307 307
308 308 assert(hr->bottom() < obj_top && obj_top <= hr->end(),
309 309 "obj_top should be in last region");
310 310
311 311 _verifier->check_bitmaps("Humongous Region Allocation", first_hr);
312 312
313 313 assert(words_not_fillable == 0 ||
314 314 first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(),
315 315 "Miscalculation in humongous allocation");
316 316
317 317 increase_used((word_size_sum - words_not_fillable) * HeapWordSize);
318 318
319 319 for (uint i = first; i <= last; ++i) {
320 320 hr = region_at(i);
321 321 _humongous_set.add(hr);
322 322 _hr_printer.alloc(hr);
323 323 }
324 324
325 325 return new_obj;
326 326 }
327 327
328 328 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) {
329 329 assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size);
330 330 return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
331 331 }
332 332
333 333 // If could fit into free regions w/o expansion, try.
334 334 // Otherwise, if can expand, do so.
335 335 // Otherwise, if using ex regions might help, try with ex given back.
336 336 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
337 337 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
338 338
339 339 _verifier->verify_region_sets_optional();
340 340
341 341 uint first = G1_NO_HRM_INDEX;
342 342 uint obj_regions = (uint) humongous_obj_size_in_regions(word_size);
343 343
344 344 if (obj_regions == 1) {
345 345 // Only one region to allocate, try to use a fast path by directly allocating
346 346 // from the free lists. Do not try to expand here, we will potentially do that
347 347 // later.
348 348 HeapRegion* hr = new_region(word_size, HeapRegionType::Humongous, false /* do_expand */);
349 349 if (hr != NULL) {
350 350 first = hr->hrm_index();
351 351 }
352 352 } else {
353 353 // Policy: Try only empty regions (i.e. already committed first). Maybe we
354 354 // are lucky enough to find some.
355 355 first = _hrm->find_contiguous_only_empty(obj_regions);
356 356 if (first != G1_NO_HRM_INDEX) {
357 357 _hrm->allocate_free_regions_starting_at(first, obj_regions);
358 358 }
359 359 }
360 360
361 361 if (first == G1_NO_HRM_INDEX) {
362 362 // Policy: We could not find enough regions for the humongous object in the
363 363 // free list. Look through the heap to find a mix of free and uncommitted regions.
364 364 // If so, try expansion.
365 365 first = _hrm->find_contiguous_empty_or_unavailable(obj_regions);
366 366 if (first != G1_NO_HRM_INDEX) {
367 367 // We found something. Make sure these regions are committed, i.e. expand
368 368 // the heap. Alternatively we could do a defragmentation GC.
369 369 log_debug(gc, ergo, heap)("Attempt heap expansion (humongous allocation request failed). Allocation request: " SIZE_FORMAT "B",
370 370 word_size * HeapWordSize);
371 371
372 372 _hrm->expand_at(first, obj_regions, workers());
373 373 policy()->record_new_heap_size(num_regions());
374 374
375 375 #ifdef ASSERT
376 376 for (uint i = first; i < first + obj_regions; ++i) {
377 377 HeapRegion* hr = region_at(i);
378 378 assert(hr->is_free(), "sanity");
379 379 assert(hr->is_empty(), "sanity");
380 380 assert(is_on_master_free_list(hr), "sanity");
381 381 }
382 382 #endif
383 383 _hrm->allocate_free_regions_starting_at(first, obj_regions);
384 384 } else {
385 385 // Policy: Potentially trigger a defragmentation GC.
386 386 }
387 387 }
388 388
389 389 HeapWord* result = NULL;
390 390 if (first != G1_NO_HRM_INDEX) {
391 391 result = humongous_obj_allocate_initialize_regions(first, obj_regions, word_size);
392 392 assert(result != NULL, "it should always return a valid result");
393 393
394 394 // A successful humongous object allocation changes the used space
395 395 // information of the old generation so we need to recalculate the
396 396 // sizes and update the jstat counters here.
397 397 g1mm()->update_sizes();
398 398 }
399 399
400 400 _verifier->verify_region_sets_optional();
401 401
402 402 return result;
403 403 }
404 404
405 405 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size,
406 406 size_t requested_size,
407 407 size_t* actual_size) {
408 408 assert_heap_not_locked_and_not_at_safepoint();
409 409 assert(!is_humongous(requested_size), "we do not allow humongous TLABs");
410 410
411 411 return attempt_allocation(min_size, requested_size, actual_size);
412 412 }
413 413
414 414 HeapWord*
415 415 G1CollectedHeap::mem_allocate(size_t word_size,
416 416 bool* gc_overhead_limit_was_exceeded) {
417 417 assert_heap_not_locked_and_not_at_safepoint();
418 418
419 419 if (is_humongous(word_size)) {
420 420 return attempt_allocation_humongous(word_size);
421 421 }
422 422 size_t dummy = 0;
423 423 return attempt_allocation(word_size, word_size, &dummy);
424 424 }
425 425
426 426 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) {
427 427 ResourceMark rm; // For retrieving the thread names in log messages.
428 428
429 429 // Make sure you read the note in attempt_allocation_humongous().
430 430
431 431 assert_heap_not_locked_and_not_at_safepoint();
432 432 assert(!is_humongous(word_size), "attempt_allocation_slow() should not "
433 433 "be called for humongous allocation requests");
434 434
435 435 // We should only get here after the first-level allocation attempt
436 436 // (attempt_allocation()) failed to allocate.
437 437
438 438 // We will loop until a) we manage to successfully perform the
439 439 // allocation or b) we successfully schedule a collection which
440 440 // fails to perform the allocation. b) is the only case when we'll
441 441 // return NULL.
442 442 HeapWord* result = NULL;
443 443 for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
444 444 bool should_try_gc;
445 445 uint gc_count_before;
446 446
447 447 {
448 448 MutexLocker x(Heap_lock);
449 449 result = _allocator->attempt_allocation_locked(word_size);
450 450 if (result != NULL) {
451 451 return result;
452 452 }
453 453
454 454 // If the GCLocker is active and we are bound for a GC, try expanding young gen.
455 455 // This is different to when only GCLocker::needs_gc() is set: try to avoid
456 456 // waiting because the GCLocker is active to not wait too long.
457 457 if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) {
458 458 // No need for an ergo message here, can_expand_young_list() does this when
459 459 // it returns true.
460 460 result = _allocator->attempt_allocation_force(word_size);
461 461 if (result != NULL) {
462 462 return result;
463 463 }
464 464 }
465 465 // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
466 466 // the GCLocker initiated GC has been performed and then retry. This includes
467 467 // the case when the GC Locker is not active but has not been performed.
468 468 should_try_gc = !GCLocker::needs_gc();
469 469 // Read the GC count while still holding the Heap_lock.
470 470 gc_count_before = total_collections();
471 471 }
472 472
473 473 if (should_try_gc) {
474 474 bool succeeded;
475 475 result = do_collection_pause(word_size, gc_count_before, &succeeded,
476 476 GCCause::_g1_inc_collection_pause);
477 477 if (result != NULL) {
478 478 assert(succeeded, "only way to get back a non-NULL result");
479 479 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
480 480 Thread::current()->name(), p2i(result));
481 481 return result;
482 482 }
483 483
484 484 if (succeeded) {
485 485 // We successfully scheduled a collection which failed to allocate. No
486 486 // point in trying to allocate further. We'll just return NULL.
487 487 log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
488 488 SIZE_FORMAT " words", Thread::current()->name(), word_size);
489 489 return NULL;
490 490 }
491 491 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",
492 492 Thread::current()->name(), word_size);
493 493 } else {
494 494 // Failed to schedule a collection.
495 495 if (gclocker_retry_count > GCLockerRetryAllocationCount) {
496 496 log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
497 497 SIZE_FORMAT " words", Thread::current()->name(), word_size);
498 498 return NULL;
499 499 }
500 500 log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
501 501 // The GCLocker is either active or the GCLocker initiated
502 502 // GC has not yet been performed. Stall until it is and
503 503 // then retry the allocation.
504 504 GCLocker::stall_until_clear();
505 505 gclocker_retry_count += 1;
506 506 }
507 507
508 508 // We can reach here if we were unsuccessful in scheduling a
509 509 // collection (because another thread beat us to it) or if we were
510 510 // stalled due to the GC locker. In either can we should retry the
511 511 // allocation attempt in case another thread successfully
512 512 // performed a collection and reclaimed enough space. We do the
513 513 // first attempt (without holding the Heap_lock) here and the
514 514 // follow-on attempt will be at the start of the next loop
515 515 // iteration (after taking the Heap_lock).
516 516 size_t dummy = 0;
517 517 result = _allocator->attempt_allocation(word_size, word_size, &dummy);
518 518 if (result != NULL) {
519 519 return result;
520 520 }
521 521
522 522 // Give a warning if we seem to be looping forever.
523 523 if ((QueuedAllocationWarningCount > 0) &&
524 524 (try_count % QueuedAllocationWarningCount == 0)) {
525 525 log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
526 526 Thread::current()->name(), try_count, word_size);
527 527 }
528 528 }
529 529
530 530 ShouldNotReachHere();
531 531 return NULL;
532 532 }
533 533
534 534 void G1CollectedHeap::begin_archive_alloc_range(bool open) {
535 535 assert_at_safepoint_on_vm_thread();
536 536 if (_archive_allocator == NULL) {
537 537 _archive_allocator = G1ArchiveAllocator::create_allocator(this, open);
538 538 }
539 539 }
540 540
541 541 bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {
542 542 // Allocations in archive regions cannot be of a size that would be considered
543 543 // humongous even for a minimum-sized region, because G1 region sizes/boundaries
544 544 // may be different at archive-restore time.
545 545 return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());
546 546 }
547 547
548 548 HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {
549 549 assert_at_safepoint_on_vm_thread();
550 550 assert(_archive_allocator != NULL, "_archive_allocator not initialized");
551 551 if (is_archive_alloc_too_large(word_size)) {
552 552 return NULL;
553 553 }
554 554 return _archive_allocator->archive_mem_allocate(word_size);
555 555 }
556 556
557 557 void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,
558 558 size_t end_alignment_in_bytes) {
559 559 assert_at_safepoint_on_vm_thread();
560 560 assert(_archive_allocator != NULL, "_archive_allocator not initialized");
561 561
562 562 // Call complete_archive to do the real work, filling in the MemRegion
563 563 // array with the archive regions.
564 564 _archive_allocator->complete_archive(ranges, end_alignment_in_bytes);
565 565 delete _archive_allocator;
566 566 _archive_allocator = NULL;
567 567 }
568 568
569 569 bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {
570 570 assert(ranges != NULL, "MemRegion array NULL");
571 571 assert(count != 0, "No MemRegions provided");
572 572 MemRegion reserved = _hrm->reserved();
573 573 for (size_t i = 0; i < count; i++) {
574 574 if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {
575 575 return false;
576 576 }
577 577 }
578 578 return true;
579 579 }
580 580
581 581 bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges,
582 582 size_t count,
583 583 bool open) {
584 584 assert(!is_init_completed(), "Expect to be called at JVM init time");
585 585 assert(ranges != NULL, "MemRegion array NULL");
586 586 assert(count != 0, "No MemRegions provided");
587 587 MutexLocker x(Heap_lock);
588 588
589 589 MemRegion reserved = _hrm->reserved();
590 590 HeapWord* prev_last_addr = NULL;
591 591 HeapRegion* prev_last_region = NULL;
592 592
593 593 // Temporarily disable pretouching of heap pages. This interface is used
594 594 // when mmap'ing archived heap data in, so pre-touching is wasted.
595 595 FlagSetting fs(AlwaysPreTouch, false);
596 596
597 597 // Enable archive object checking used by G1MarkSweep. We have to let it know
598 598 // about each archive range, so that objects in those ranges aren't marked.
599 599 G1ArchiveAllocator::enable_archive_object_check();
600 600
601 601 // For each specified MemRegion range, allocate the corresponding G1
602 602 // regions and mark them as archive regions. We expect the ranges
603 603 // in ascending starting address order, without overlap.
604 604 for (size_t i = 0; i < count; i++) {
605 605 MemRegion curr_range = ranges[i];
606 606 HeapWord* start_address = curr_range.start();
607 607 size_t word_size = curr_range.word_size();
608 608 HeapWord* last_address = curr_range.last();
609 609 size_t commits = 0;
610 610
611 611 guarantee(reserved.contains(start_address) && reserved.contains(last_address),
612 612 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
613 613 p2i(start_address), p2i(last_address));
614 614 guarantee(start_address > prev_last_addr,
615 615 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
616 616 p2i(start_address), p2i(prev_last_addr));
617 617 prev_last_addr = last_address;
618 618
619 619 // Check for ranges that start in the same G1 region in which the previous
620 620 // range ended, and adjust the start address so we don't try to allocate
621 621 // the same region again. If the current range is entirely within that
622 622 // region, skip it, just adjusting the recorded top.
623 623 HeapRegion* start_region = _hrm->addr_to_region(start_address);
624 624 if ((prev_last_region != NULL) && (start_region == prev_last_region)) {
625 625 start_address = start_region->end();
626 626 if (start_address > last_address) {
627 627 increase_used(word_size * HeapWordSize);
628 628 start_region->set_top(last_address + 1);
629 629 continue;
630 630 }
631 631 start_region->set_top(start_address);
632 632 curr_range = MemRegion(start_address, last_address + 1);
633 633 start_region = _hrm->addr_to_region(start_address);
634 634 }
635 635
636 636 // Perform the actual region allocation, exiting if it fails.
637 637 // Then note how much new space we have allocated.
638 638 if (!_hrm->allocate_containing_regions(curr_range, &commits, workers())) {
639 639 return false;
640 640 }
641 641 increase_used(word_size * HeapWordSize);
642 642 if (commits != 0) {
643 643 log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B",
644 644 HeapRegion::GrainWords * HeapWordSize * commits);
645 645
646 646 }
647 647
648 648 // Mark each G1 region touched by the range as archive, add it to
649 649 // the old set, and set top.
650 650 HeapRegion* curr_region = _hrm->addr_to_region(start_address);
651 651 HeapRegion* last_region = _hrm->addr_to_region(last_address);
652 652 prev_last_region = last_region;
653 653
654 654 while (curr_region != NULL) {
655 655 assert(curr_region->is_empty() && !curr_region->is_pinned(),
656 656 "Region already in use (index %u)", curr_region->hrm_index());
657 657 if (open) {
658 658 curr_region->set_open_archive();
659 659 } else {
660 660 curr_region->set_closed_archive();
661 661 }
662 662 _hr_printer.alloc(curr_region);
663 663 _archive_set.add(curr_region);
664 664 HeapWord* top;
665 665 HeapRegion* next_region;
666 666 if (curr_region != last_region) {
667 667 top = curr_region->end();
668 668 next_region = _hrm->next_region_in_heap(curr_region);
669 669 } else {
670 670 top = last_address + 1;
671 671 next_region = NULL;
672 672 }
673 673 curr_region->set_top(top);
674 674 curr_region = next_region;
675 675 }
676 676
677 677 // Notify mark-sweep of the archive
678 678 G1ArchiveAllocator::set_range_archive(curr_range, open);
679 679 }
680 680 return true;
681 681 }
682 682
683 683 void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {
684 684 assert(!is_init_completed(), "Expect to be called at JVM init time");
685 685 assert(ranges != NULL, "MemRegion array NULL");
686 686 assert(count != 0, "No MemRegions provided");
687 687 MemRegion reserved = _hrm->reserved();
688 688 HeapWord *prev_last_addr = NULL;
689 689 HeapRegion* prev_last_region = NULL;
690 690
691 691 // For each MemRegion, create filler objects, if needed, in the G1 regions
692 692 // that contain the address range. The address range actually within the
693 693 // MemRegion will not be modified. That is assumed to have been initialized
694 694 // elsewhere, probably via an mmap of archived heap data.
695 695 MutexLocker x(Heap_lock);
696 696 for (size_t i = 0; i < count; i++) {
697 697 HeapWord* start_address = ranges[i].start();
698 698 HeapWord* last_address = ranges[i].last();
699 699
700 700 assert(reserved.contains(start_address) && reserved.contains(last_address),
701 701 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
702 702 p2i(start_address), p2i(last_address));
703 703 assert(start_address > prev_last_addr,
704 704 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
705 705 p2i(start_address), p2i(prev_last_addr));
706 706
707 707 HeapRegion* start_region = _hrm->addr_to_region(start_address);
708 708 HeapRegion* last_region = _hrm->addr_to_region(last_address);
709 709 HeapWord* bottom_address = start_region->bottom();
710 710
711 711 // Check for a range beginning in the same region in which the
712 712 // previous one ended.
713 713 if (start_region == prev_last_region) {
714 714 bottom_address = prev_last_addr + 1;
715 715 }
716 716
717 717 // Verify that the regions were all marked as archive regions by
718 718 // alloc_archive_regions.
719 719 HeapRegion* curr_region = start_region;
720 720 while (curr_region != NULL) {
721 721 guarantee(curr_region->is_archive(),
722 722 "Expected archive region at index %u", curr_region->hrm_index());
723 723 if (curr_region != last_region) {
724 724 curr_region = _hrm->next_region_in_heap(curr_region);
725 725 } else {
726 726 curr_region = NULL;
727 727 }
728 728 }
729 729
730 730 prev_last_addr = last_address;
731 731 prev_last_region = last_region;
732 732
733 733 // Fill the memory below the allocated range with dummy object(s),
734 734 // if the region bottom does not match the range start, or if the previous
735 735 // range ended within the same G1 region, and there is a gap.
736 736 if (start_address != bottom_address) {
737 737 size_t fill_size = pointer_delta(start_address, bottom_address);
738 738 G1CollectedHeap::fill_with_objects(bottom_address, fill_size);
739 739 increase_used(fill_size * HeapWordSize);
740 740 }
741 741 }
742 742 }
743 743
744 744 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,
745 745 size_t desired_word_size,
746 746 size_t* actual_word_size) {
747 747 assert_heap_not_locked_and_not_at_safepoint();
748 748 assert(!is_humongous(desired_word_size), "attempt_allocation() should not "
749 749 "be called for humongous allocation requests");
750 750
751 751 HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size);
752 752
753 753 if (result == NULL) {
754 754 *actual_word_size = desired_word_size;
755 755 result = attempt_allocation_slow(desired_word_size);
756 756 }
757 757
758 758 assert_heap_not_locked();
759 759 if (result != NULL) {
760 760 assert(*actual_word_size != 0, "Actual size must have been set here");
761 761 dirty_young_block(result, *actual_word_size);
762 762 } else {
763 763 *actual_word_size = 0;
764 764 }
765 765
766 766 return result;
767 767 }
768 768
769 769 void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) {
770 770 assert(!is_init_completed(), "Expect to be called at JVM init time");
771 771 assert(ranges != NULL, "MemRegion array NULL");
772 772 assert(count != 0, "No MemRegions provided");
773 773 MemRegion reserved = _hrm->reserved();
774 774 HeapWord* prev_last_addr = NULL;
775 775 HeapRegion* prev_last_region = NULL;
776 776 size_t size_used = 0;
777 777 size_t uncommitted_regions = 0;
778 778
779 779 // For each Memregion, free the G1 regions that constitute it, and
780 780 // notify mark-sweep that the range is no longer to be considered 'archive.'
781 781 MutexLocker x(Heap_lock);
782 782 for (size_t i = 0; i < count; i++) {
783 783 HeapWord* start_address = ranges[i].start();
784 784 HeapWord* last_address = ranges[i].last();
785 785
786 786 assert(reserved.contains(start_address) && reserved.contains(last_address),
787 787 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
788 788 p2i(start_address), p2i(last_address));
789 789 assert(start_address > prev_last_addr,
790 790 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
791 791 p2i(start_address), p2i(prev_last_addr));
792 792 size_used += ranges[i].byte_size();
793 793 prev_last_addr = last_address;
794 794
795 795 HeapRegion* start_region = _hrm->addr_to_region(start_address);
796 796 HeapRegion* last_region = _hrm->addr_to_region(last_address);
797 797
798 798 // Check for ranges that start in the same G1 region in which the previous
799 799 // range ended, and adjust the start address so we don't try to free
800 800 // the same region again. If the current range is entirely within that
801 801 // region, skip it.
802 802 if (start_region == prev_last_region) {
803 803 start_address = start_region->end();
804 804 if (start_address > last_address) {
805 805 continue;
806 806 }
807 807 start_region = _hrm->addr_to_region(start_address);
808 808 }
809 809 prev_last_region = last_region;
810 810
811 811 // After verifying that each region was marked as an archive region by
812 812 // alloc_archive_regions, set it free and empty and uncommit it.
813 813 HeapRegion* curr_region = start_region;
814 814 while (curr_region != NULL) {
815 815 guarantee(curr_region->is_archive(),
816 816 "Expected archive region at index %u", curr_region->hrm_index());
817 817 uint curr_index = curr_region->hrm_index();
818 818 _archive_set.remove(curr_region);
819 819 curr_region->set_free();
820 820 curr_region->set_top(curr_region->bottom());
821 821 if (curr_region != last_region) {
822 822 curr_region = _hrm->next_region_in_heap(curr_region);
823 823 } else {
824 824 curr_region = NULL;
825 825 }
826 826 _hrm->shrink_at(curr_index, 1);
827 827 uncommitted_regions++;
828 828 }
829 829
830 830 // Notify mark-sweep that this is no longer an archive range.
831 831 G1ArchiveAllocator::clear_range_archive(ranges[i]);
832 832 }
833 833
834 834 if (uncommitted_regions != 0) {
835 835 log_debug(gc, ergo, heap)("Attempt heap shrinking (uncommitted archive regions). Total size: " SIZE_FORMAT "B",
836 836 HeapRegion::GrainWords * HeapWordSize * uncommitted_regions);
837 837 }
838 838 decrease_used(size_used);
839 839 }
840 840
841 841 oop G1CollectedHeap::materialize_archived_object(oop obj) {
842 842 assert(obj != NULL, "archived obj is NULL");
843 843 assert(G1ArchiveAllocator::is_archived_object(obj), "must be archived object");
844 844
845 845 // Loading an archived object makes it strongly reachable. If it is
846 846 // loaded during concurrent marking, it must be enqueued to the SATB
847 847 // queue, shading the previously white object gray.
848 848 G1BarrierSet::enqueue(obj);
849 849
850 850 return obj;
851 851 }
852 852
853 853 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
854 854 ResourceMark rm; // For retrieving the thread names in log messages.
855 855
856 856 // The structure of this method has a lot of similarities to
857 857 // attempt_allocation_slow(). The reason these two were not merged
858 858 // into a single one is that such a method would require several "if
859 859 // allocation is not humongous do this, otherwise do that"
860 860 // conditional paths which would obscure its flow. In fact, an early
861 861 // version of this code did use a unified method which was harder to
862 862 // follow and, as a result, it had subtle bugs that were hard to
863 863 // track down. So keeping these two methods separate allows each to
864 864 // be more readable. It will be good to keep these two in sync as
865 865 // much as possible.
866 866
867 867 assert_heap_not_locked_and_not_at_safepoint();
868 868 assert(is_humongous(word_size), "attempt_allocation_humongous() "
869 869 "should only be called for humongous allocations");
870 870
871 871 // Humongous objects can exhaust the heap quickly, so we should check if we
872 872 // need to start a marking cycle at each humongous object allocation. We do
873 873 // the check before we do the actual allocation. The reason for doing it
874 874 // before the allocation is that we avoid having to keep track of the newly
875 875 // allocated memory while we do a GC.
876 876 if (policy()->need_to_start_conc_mark("concurrent humongous allocation",
877 877 word_size)) {
878 878 collect(GCCause::_g1_humongous_allocation);
879 879 }
880 880
881 881 // We will loop until a) we manage to successfully perform the
882 882 // allocation or b) we successfully schedule a collection which
883 883 // fails to perform the allocation. b) is the only case when we'll
884 884 // return NULL.
885 885 HeapWord* result = NULL;
886 886 for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
887 887 bool should_try_gc;
888 888 uint gc_count_before;
889 889
890 890
891 891 {
892 892 MutexLocker x(Heap_lock);
893 893
894 894 // Given that humongous objects are not allocated in young
895 895 // regions, we'll first try to do the allocation without doing a
896 896 // collection hoping that there's enough space in the heap.
897 897 result = humongous_obj_allocate(word_size);
898 898 if (result != NULL) {
899 899 size_t size_in_regions = humongous_obj_size_in_regions(word_size);
900 900 policy()->add_bytes_allocated_in_old_since_last_gc(size_in_regions * HeapRegion::GrainBytes);
901 901 return result;
902 902 }
903 903
904 904 // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
905 905 // the GCLocker initiated GC has been performed and then retry. This includes
906 906 // the case when the GC Locker is not active but has not been performed.
907 907 should_try_gc = !GCLocker::needs_gc();
908 908 // Read the GC count while still holding the Heap_lock.
909 909 gc_count_before = total_collections();
910 910 }
911 911
912 912 if (should_try_gc) {
913 913 bool succeeded;
914 914 result = do_collection_pause(word_size, gc_count_before, &succeeded,
915 915 GCCause::_g1_humongous_allocation);
916 916 if (result != NULL) {
917 917 assert(succeeded, "only way to get back a non-NULL result");
918 918 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
919 919 Thread::current()->name(), p2i(result));
920 920 return result;
921 921 }
922 922
923 923 if (succeeded) {
924 924 // We successfully scheduled a collection which failed to allocate. No
925 925 // point in trying to allocate further. We'll just return NULL.
926 926 log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
927 927 SIZE_FORMAT " words", Thread::current()->name(), word_size);
928 928 return NULL;
929 929 }
930 930 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",
931 931 Thread::current()->name(), word_size);
932 932 } else {
933 933 // Failed to schedule a collection.
934 934 if (gclocker_retry_count > GCLockerRetryAllocationCount) {
935 935 log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
936 936 SIZE_FORMAT " words", Thread::current()->name(), word_size);
937 937 return NULL;
938 938 }
939 939 log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
940 940 // The GCLocker is either active or the GCLocker initiated
941 941 // GC has not yet been performed. Stall until it is and
942 942 // then retry the allocation.
943 943 GCLocker::stall_until_clear();
944 944 gclocker_retry_count += 1;
945 945 }
946 946
947 947
948 948 // We can reach here if we were unsuccessful in scheduling a
949 949 // collection (because another thread beat us to it) or if we were
950 950 // stalled due to the GC locker. In either can we should retry the
951 951 // allocation attempt in case another thread successfully
952 952 // performed a collection and reclaimed enough space.
953 953 // Humongous object allocation always needs a lock, so we wait for the retry
954 954 // in the next iteration of the loop, unlike for the regular iteration case.
955 955 // Give a warning if we seem to be looping forever.
956 956
957 957 if ((QueuedAllocationWarningCount > 0) &&
958 958 (try_count % QueuedAllocationWarningCount == 0)) {
959 959 log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
960 960 Thread::current()->name(), try_count, word_size);
961 961 }
962 962 }
963 963
964 964 ShouldNotReachHere();
965 965 return NULL;
966 966 }
967 967
968 968 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
969 969 bool expect_null_mutator_alloc_region) {
970 970 assert_at_safepoint_on_vm_thread();
971 971 assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,
972 972 "the current alloc region was unexpectedly found to be non-NULL");
973 973
974 974 if (!is_humongous(word_size)) {
975 975 return _allocator->attempt_allocation_locked(word_size);
976 976 } else {
977 977 HeapWord* result = humongous_obj_allocate(word_size);
978 978 if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) {
979 979 collector_state()->set_initiate_conc_mark_if_possible(true);
980 980 }
981 981 return result;
982 982 }
983 983
984 984 ShouldNotReachHere();
985 985 }
986 986
987 987 class PostCompactionPrinterClosure: public HeapRegionClosure {
988 988 private:
989 989 G1HRPrinter* _hr_printer;
990 990 public:
991 991 bool do_heap_region(HeapRegion* hr) {
992 992 assert(!hr->is_young(), "not expecting to find young regions");
993 993 _hr_printer->post_compaction(hr);
994 994 return false;
995 995 }
996 996
997 997 PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
998 998 : _hr_printer(hr_printer) { }
999 999 };
1000 1000
1001 1001 void G1CollectedHeap::print_hrm_post_compaction() {
1002 1002 if (_hr_printer.is_active()) {
1003 1003 PostCompactionPrinterClosure cl(hr_printer());
1004 1004 heap_region_iterate(&cl);
1005 1005 }
1006 1006 }
1007 1007
1008 1008 void G1CollectedHeap::abort_concurrent_cycle() {
1009 1009 // If we start the compaction before the CM threads finish
1010 1010 // scanning the root regions we might trip them over as we'll
1011 1011 // be moving objects / updating references. So let's wait until
1012 1012 // they are done. By telling them to abort, they should complete
1013 1013 // early.
1014 1014 _cm->root_regions()->abort();
1015 1015 _cm->root_regions()->wait_until_scan_finished();
1016 1016
1017 1017 // Disable discovery and empty the discovered lists
1018 1018 // for the CM ref processor.
1019 1019 _ref_processor_cm->disable_discovery();
1020 1020 _ref_processor_cm->abandon_partial_discovery();
1021 1021 _ref_processor_cm->verify_no_references_recorded();
1022 1022
1023 1023 // Abandon current iterations of concurrent marking and concurrent
1024 1024 // refinement, if any are in progress.
1025 1025 concurrent_mark()->concurrent_cycle_abort();
1026 1026 }
1027 1027
1028 1028 void G1CollectedHeap::prepare_heap_for_full_collection() {
1029 1029 // Make sure we'll choose a new allocation region afterwards.
1030 1030 _allocator->release_mutator_alloc_regions();
1031 1031 _allocator->abandon_gc_alloc_regions();
1032 1032
1033 1033 // We may have added regions to the current incremental collection
1034 1034 // set between the last GC or pause and now. We need to clear the
1035 1035 // incremental collection set and then start rebuilding it afresh
1036 1036 // after this full GC.
1037 1037 abandon_collection_set(collection_set());
1038 1038
1039 1039 tear_down_region_sets(false /* free_list_only */);
1040 1040
1041 1041 hrm()->prepare_for_full_collection_start();
1042 1042 }
1043 1043
1044 1044 void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) {
1045 1045 assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");
1046 1046 assert_used_and_recalculate_used_equal(this);
1047 1047 _verifier->verify_region_sets_optional();
1048 1048 _verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull);
1049 1049 _verifier->check_bitmaps("Full GC Start");
1050 1050 }
1051 1051
1052 1052 void G1CollectedHeap::prepare_heap_for_mutators() {
1053 1053 hrm()->prepare_for_full_collection_end();
1054 1054
1055 1055 // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1056 1056 ClassLoaderDataGraph::purge();
1057 1057 MetaspaceUtils::verify_metrics();
1058 1058
1059 1059 // Prepare heap for normal collections.
1060 1060 assert(num_free_regions() == 0, "we should not have added any free regions");
1061 1061 rebuild_region_sets(false /* free_list_only */);
1062 1062 abort_refinement();
1063 1063 resize_heap_if_necessary();
1064 1064
1065 1065 // Rebuild the strong code root lists for each region
1066 1066 rebuild_strong_code_roots();
1067 1067
1068 1068 // Purge code root memory
1069 1069 purge_code_root_memory();
1070 1070
1071 1071 // Start a new incremental collection set for the next pause
1072 1072 start_new_collection_set();
1073 1073
1074 1074 _allocator->init_mutator_alloc_regions();
1075 1075
1076 1076 // Post collection state updates.
1077 1077 MetaspaceGC::compute_new_size();
1078 1078 }
1079 1079
1080 1080 void G1CollectedHeap::abort_refinement() {
1081 1081 if (_hot_card_cache->use_cache()) {
1082 1082 _hot_card_cache->reset_hot_cache();
1083 1083 }
1084 1084
1085 1085 // Discard all remembered set updates.
1086 1086 G1BarrierSet::dirty_card_queue_set().abandon_logs();
1087 1087 assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0,
1088 1088 "DCQS should be empty");
1089 1089 }
1090 1090
1091 1091 void G1CollectedHeap::verify_after_full_collection() {
1092 1092 _hrm->verify_optional();
1093 1093 _verifier->verify_region_sets_optional();
1094 1094 _verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull);
1095 1095 // Clear the previous marking bitmap, if needed for bitmap verification.
1096 1096 // Note we cannot do this when we clear the next marking bitmap in
1097 1097 // G1ConcurrentMark::abort() above since VerifyDuringGC verifies the
1098 1098 // objects marked during a full GC against the previous bitmap.
1099 1099 // But we need to clear it before calling check_bitmaps below since
1100 1100 // the full GC has compacted objects and updated TAMS but not updated
1101 1101 // the prev bitmap.
1102 1102 if (G1VerifyBitmaps) {
1103 1103 GCTraceTime(Debug, gc) tm("Clear Prev Bitmap for Verification");
1104 1104 _cm->clear_prev_bitmap(workers());
1105 1105 }
1106 1106 // This call implicitly verifies that the next bitmap is clear after Full GC.
1107 1107 _verifier->check_bitmaps("Full GC End");
1108 1108
1109 1109 // At this point there should be no regions in the
1110 1110 // entire heap tagged as young.
1111 1111 assert(check_young_list_empty(), "young list should be empty at this point");
1112 1112
1113 1113 // Note: since we've just done a full GC, concurrent
1114 1114 // marking is no longer active. Therefore we need not
1115 1115 // re-enable reference discovery for the CM ref processor.
1116 1116 // That will be done at the start of the next marking cycle.
1117 1117 // We also know that the STW processor should no longer
1118 1118 // discover any new references.
1119 1119 assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
1120 1120 assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");
1121 1121 _ref_processor_stw->verify_no_references_recorded();
1122 1122 _ref_processor_cm->verify_no_references_recorded();
1123 1123 }
1124 1124
1125 1125 void G1CollectedHeap::print_heap_after_full_collection(G1HeapTransition* heap_transition) {
1126 1126 // Post collection logging.
1127 1127 // We should do this after we potentially resize the heap so
1128 1128 // that all the COMMIT / UNCOMMIT events are generated before
1129 1129 // the compaction events.
1130 1130 print_hrm_post_compaction();
1131 1131 heap_transition->print();
1132 1132 print_heap_after_gc();
1133 1133 print_heap_regions();
1134 1134 #ifdef TRACESPINNING
1135 1135 ParallelTaskTerminator::print_termination_counts();
1136 1136 #endif
1137 1137 }
1138 1138
1139 1139 bool G1CollectedHeap::do_full_collection(bool explicit_gc,
1140 1140 bool clear_all_soft_refs) {
1141 1141 assert_at_safepoint_on_vm_thread();
1142 1142
1143 1143 if (GCLocker::check_active_before_gc()) {
1144 1144 // Full GC was not completed.
1145 1145 return false;
1146 1146 }
1147 1147
1148 1148 const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1149 1149 soft_ref_policy()->should_clear_all_soft_refs();
1150 1150
1151 1151 G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs);
1152 1152 GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true);
1153 1153
1154 1154 collector.prepare_collection();
1155 1155 collector.collect();
1156 1156 collector.complete_collection();
1157 1157
1158 1158 // Full collection was successfully completed.
1159 1159 return true;
1160 1160 }
1161 1161
1162 1162 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1163 1163 // Currently, there is no facility in the do_full_collection(bool) API to notify
1164 1164 // the caller that the collection did not succeed (e.g., because it was locked
1165 1165 // out by the GC locker). So, right now, we'll ignore the return value.
1166 1166 bool dummy = do_full_collection(true, /* explicit_gc */
1167 1167 clear_all_soft_refs);
1168 1168 }
1169 1169
1170 1170 void G1CollectedHeap::resize_heap_if_necessary() {
1171 1171 assert_at_safepoint_on_vm_thread();
1172 1172
1173 1173 // Capacity, free and used after the GC counted as full regions to
1174 1174 // include the waste in the following calculations.
1175 1175 const size_t capacity_after_gc = capacity();
1176 1176 const size_t used_after_gc = capacity_after_gc - unused_committed_regions_in_bytes();
1177 1177
1178 1178 // This is enforced in arguments.cpp.
1179 1179 assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
1180 1180 "otherwise the code below doesn't make sense");
1181 1181
1182 1182 // We don't have floating point command-line arguments
1183 1183 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
1184 1184 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1185 1185 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
1186 1186 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1187 1187
1188 1188 // We have to be careful here as these two calculations can overflow
1189 1189 // 32-bit size_t's.
1190 1190 double used_after_gc_d = (double) used_after_gc;
1191 1191 double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
1192 1192 double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
1193 1193
1194 1194 // Let's make sure that they are both under the max heap size, which
1195 1195 // by default will make them fit into a size_t.
1196 1196 double desired_capacity_upper_bound = (double) MaxHeapSize;
1197 1197 minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
1198 1198 desired_capacity_upper_bound);
1199 1199 maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
1200 1200 desired_capacity_upper_bound);
1201 1201
1202 1202 // We can now safely turn them into size_t's.
1203 1203 size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
1204 1204 size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
1205 1205
1206 1206 // This assert only makes sense here, before we adjust them
1207 1207 // with respect to the min and max heap size.
1208 1208 assert(minimum_desired_capacity <= maximum_desired_capacity,
1209 1209 "minimum_desired_capacity = " SIZE_FORMAT ", "
1210 1210 "maximum_desired_capacity = " SIZE_FORMAT,
1211 1211 minimum_desired_capacity, maximum_desired_capacity);
1212 1212
1213 1213 // Should not be greater than the heap max size. No need to adjust
1214 1214 // it with respect to the heap min size as it's a lower bound (i.e.,
1215 1215 // we'll try to make the capacity larger than it, not smaller).
1216 1216 minimum_desired_capacity = MIN2(minimum_desired_capacity, MaxHeapSize);
1217 1217 // Should not be less than the heap min size. No need to adjust it
1218 1218 // with respect to the heap max size as it's an upper bound (i.e.,
1219 1219 // we'll try to make the capacity smaller than it, not greater).
1220 1220 maximum_desired_capacity = MAX2(maximum_desired_capacity, MinHeapSize);
1221 1221
1222 1222 if (capacity_after_gc < minimum_desired_capacity) {
1223 1223 // Don't expand unless it's significant
1224 1224 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1225 1225
1226 1226 log_debug(gc, ergo, heap)("Attempt heap expansion (capacity lower than min desired capacity). "
1227 1227 "Capacity: " SIZE_FORMAT "B occupancy: " SIZE_FORMAT "B live: " SIZE_FORMAT "B "
1228 1228 "min_desired_capacity: " SIZE_FORMAT "B (" UINTX_FORMAT " %%)",
1229 1229 capacity_after_gc, used_after_gc, used(), minimum_desired_capacity, MinHeapFreeRatio);
1230 1230
1231 1231 expand(expand_bytes, _workers);
1232 1232
1233 1233 // No expansion, now see if we want to shrink
1234 1234 } else if (capacity_after_gc > maximum_desired_capacity) {
1235 1235 // Capacity too large, compute shrinking size
1236 1236 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1237 1237
1238 1238 log_debug(gc, ergo, heap)("Attempt heap shrinking (capacity higher than max desired capacity). "
1239 1239 "Capacity: " SIZE_FORMAT "B occupancy: " SIZE_FORMAT "B live: " SIZE_FORMAT "B "
1240 1240 "maximum_desired_capacity: " SIZE_FORMAT "B (" UINTX_FORMAT " %%)",
1241 1241 capacity_after_gc, used_after_gc, used(), maximum_desired_capacity, MaxHeapFreeRatio);
1242 1242
1243 1243 shrink(shrink_bytes);
1244 1244 }
1245 1245 }
1246 1246
1247 1247 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,
1248 1248 bool do_gc,
1249 1249 bool clear_all_soft_refs,
1250 1250 bool expect_null_mutator_alloc_region,
1251 1251 bool* gc_succeeded) {
1252 1252 *gc_succeeded = true;
1253 1253 // Let's attempt the allocation first.
1254 1254 HeapWord* result =
1255 1255 attempt_allocation_at_safepoint(word_size,
1256 1256 expect_null_mutator_alloc_region);
1257 1257 if (result != NULL) {
1258 1258 return result;
1259 1259 }
1260 1260
1261 1261 // In a G1 heap, we're supposed to keep allocation from failing by
1262 1262 // incremental pauses. Therefore, at least for now, we'll favor
1263 1263 // expansion over collection. (This might change in the future if we can
1264 1264 // do something smarter than full collection to satisfy a failed alloc.)
1265 1265 result = expand_and_allocate(word_size);
1266 1266 if (result != NULL) {
1267 1267 return result;
1268 1268 }
1269 1269
1270 1270 if (do_gc) {
1271 1271 // Expansion didn't work, we'll try to do a Full GC.
1272 1272 *gc_succeeded = do_full_collection(false, /* explicit_gc */
1273 1273 clear_all_soft_refs);
1274 1274 }
1275 1275
1276 1276 return NULL;
1277 1277 }
1278 1278
1279 1279 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1280 1280 bool* succeeded) {
1281 1281 assert_at_safepoint_on_vm_thread();
1282 1282
1283 1283 // Attempts to allocate followed by Full GC.
1284 1284 HeapWord* result =
1285 1285 satisfy_failed_allocation_helper(word_size,
1286 1286 true, /* do_gc */
1287 1287 false, /* clear_all_soft_refs */
1288 1288 false, /* expect_null_mutator_alloc_region */
1289 1289 succeeded);
1290 1290
1291 1291 if (result != NULL || !*succeeded) {
1292 1292 return result;
1293 1293 }
1294 1294
1295 1295 // Attempts to allocate followed by Full GC that will collect all soft references.
1296 1296 result = satisfy_failed_allocation_helper(word_size,
1297 1297 true, /* do_gc */
1298 1298 true, /* clear_all_soft_refs */
1299 1299 true, /* expect_null_mutator_alloc_region */
1300 1300 succeeded);
1301 1301
1302 1302 if (result != NULL || !*succeeded) {
1303 1303 return result;
1304 1304 }
1305 1305
1306 1306 // Attempts to allocate, no GC
1307 1307 result = satisfy_failed_allocation_helper(word_size,
1308 1308 false, /* do_gc */
1309 1309 false, /* clear_all_soft_refs */
1310 1310 true, /* expect_null_mutator_alloc_region */
1311 1311 succeeded);
1312 1312
1313 1313 if (result != NULL) {
1314 1314 return result;
1315 1315 }
1316 1316
1317 1317 assert(!soft_ref_policy()->should_clear_all_soft_refs(),
1318 1318 "Flag should have been handled and cleared prior to this point");
1319 1319
1320 1320 // What else? We might try synchronous finalization later. If the total
1321 1321 // space available is large enough for the allocation, then a more
1322 1322 // complete compaction phase than we've tried so far might be
1323 1323 // appropriate.
1324 1324 return NULL;
1325 1325 }
1326 1326
1327 1327 // Attempting to expand the heap sufficiently
1328 1328 // to support an allocation of the given "word_size". If
1329 1329 // successful, perform the allocation and return the address of the
1330 1330 // allocated block, or else "NULL".
1331 1331
1332 1332 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1333 1333 assert_at_safepoint_on_vm_thread();
1334 1334
1335 1335 _verifier->verify_region_sets_optional();
1336 1336
1337 1337 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1338 1338 log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B",
1339 1339 word_size * HeapWordSize);
1340 1340
1341 1341
1342 1342 if (expand(expand_bytes, _workers)) {
1343 1343 _hrm->verify_optional();
1344 1344 _verifier->verify_region_sets_optional();
1345 1345 return attempt_allocation_at_safepoint(word_size,
1346 1346 false /* expect_null_mutator_alloc_region */);
1347 1347 }
1348 1348 return NULL;
1349 1349 }
1350 1350
1351 1351 bool G1CollectedHeap::expand(size_t expand_bytes, WorkGang* pretouch_workers, double* expand_time_ms) {
1352 1352 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1353 1353 aligned_expand_bytes = align_up(aligned_expand_bytes,
1354 1354 HeapRegion::GrainBytes);
1355 1355
1356 1356 log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B",
1357 1357 expand_bytes, aligned_expand_bytes);
1358 1358
1359 1359 if (is_maximal_no_gc()) {
1360 1360 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1361 1361 return false;
1362 1362 }
1363 1363
1364 1364 double expand_heap_start_time_sec = os::elapsedTime();
1365 1365 uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);
1366 1366 assert(regions_to_expand > 0, "Must expand by at least one region");
1367 1367
1368 1368 uint expanded_by = _hrm->expand_by(regions_to_expand, pretouch_workers);
1369 1369 if (expand_time_ms != NULL) {
1370 1370 *expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS;
1371 1371 }
1372 1372
1373 1373 if (expanded_by > 0) {
1374 1374 size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;
1375 1375 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1376 1376 policy()->record_new_heap_size(num_regions());
1377 1377 } else {
1378 1378 log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)");
1379 1379
1380 1380 // The expansion of the virtual storage space was unsuccessful.
1381 1381 // Let's see if it was because we ran out of swap.
1382 1382 if (G1ExitOnExpansionFailure &&
1383 1383 _hrm->available() >= regions_to_expand) {
1384 1384 // We had head room...
1385 1385 vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
1386 1386 }
1387 1387 }
1388 1388 return regions_to_expand > 0;
1389 1389 }
1390 1390
1391 1391 bool G1CollectedHeap::expand_single_region(uint node_index) {
1392 1392 uint expanded_by = _hrm->expand_on_preferred_node(node_index);
1393 1393
1394 1394 if (expanded_by == 0) {
1395 1395 assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm->available());
1396 1396 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1397 1397 return false;
1398 1398 }
1399 1399
1400 1400 policy()->record_new_heap_size(num_regions());
1401 1401 return true;
1402 1402 }
1403 1403
1404 1404 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1405 1405 size_t aligned_shrink_bytes =
1406 1406 ReservedSpace::page_align_size_down(shrink_bytes);
1407 1407 aligned_shrink_bytes = align_down(aligned_shrink_bytes,
1408 1408 HeapRegion::GrainBytes);
1409 1409 uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
1410 1410
1411 1411 uint num_regions_removed = _hrm->shrink_by(num_regions_to_remove);
1412 1412 size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
1413 1413
1414 1414 log_debug(gc, ergo, heap)("Shrink the heap. requested shrinking amount: " SIZE_FORMAT "B aligned shrinking amount: " SIZE_FORMAT "B attempted shrinking amount: " SIZE_FORMAT "B",
1415 1415 shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
1416 1416 if (num_regions_removed > 0) {
1417 1417 policy()->record_new_heap_size(num_regions());
1418 1418 } else {
1419 1419 log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)");
1420 1420 }
1421 1421 }
1422 1422
1423 1423 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1424 1424 _verifier->verify_region_sets_optional();
1425 1425
1426 1426 // We should only reach here at the end of a Full GC or during Remark which
1427 1427 // means we should not not be holding to any GC alloc regions. The method
1428 1428 // below will make sure of that and do any remaining clean up.
1429 1429 _allocator->abandon_gc_alloc_regions();
1430 1430
1431 1431 // Instead of tearing down / rebuilding the free lists here, we
1432 1432 // could instead use the remove_all_pending() method on free_list to
1433 1433 // remove only the ones that we need to remove.
1434 1434 tear_down_region_sets(true /* free_list_only */);
1435 1435 shrink_helper(shrink_bytes);
1436 1436 rebuild_region_sets(true /* free_list_only */);
1437 1437
1438 1438 _hrm->verify_optional();
1439 1439 _verifier->verify_region_sets_optional();
1440 1440 }
1441 1441
1442 1442 class OldRegionSetChecker : public HeapRegionSetChecker {
1443 1443 public:
1444 1444 void check_mt_safety() {
1445 1445 // Master Old Set MT safety protocol:
1446 1446 // (a) If we're at a safepoint, operations on the master old set
1447 1447 // should be invoked:
1448 1448 // - by the VM thread (which will serialize them), or
1449 1449 // - by the GC workers while holding the FreeList_lock, if we're
1450 1450 // at a safepoint for an evacuation pause (this lock is taken
1451 1451 // anyway when an GC alloc region is retired so that a new one
1452 1452 // is allocated from the free list), or
1453 1453 // - by the GC workers while holding the OldSets_lock, if we're at a
1454 1454 // safepoint for a cleanup pause.
1455 1455 // (b) If we're not at a safepoint, operations on the master old set
1456 1456 // should be invoked while holding the Heap_lock.
1457 1457
1458 1458 if (SafepointSynchronize::is_at_safepoint()) {
1459 1459 guarantee(Thread::current()->is_VM_thread() ||
1460 1460 FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(),
1461 1461 "master old set MT safety protocol at a safepoint");
1462 1462 } else {
1463 1463 guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");
1464 1464 }
1465 1465 }
1466 1466 bool is_correct_type(HeapRegion* hr) { return hr->is_old(); }
1467 1467 const char* get_description() { return "Old Regions"; }
1468 1468 };
1469 1469
1470 1470 class ArchiveRegionSetChecker : public HeapRegionSetChecker {
1471 1471 public:
1472 1472 void check_mt_safety() {
1473 1473 guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(),
1474 1474 "May only change archive regions during initialization or safepoint.");
1475 1475 }
1476 1476 bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); }
1477 1477 const char* get_description() { return "Archive Regions"; }
1478 1478 };
1479 1479
1480 1480 class HumongousRegionSetChecker : public HeapRegionSetChecker {
1481 1481 public:
1482 1482 void check_mt_safety() {
1483 1483 // Humongous Set MT safety protocol:
1484 1484 // (a) If we're at a safepoint, operations on the master humongous
1485 1485 // set should be invoked by either the VM thread (which will
1486 1486 // serialize them) or by the GC workers while holding the
1487 1487 // OldSets_lock.
1488 1488 // (b) If we're not at a safepoint, operations on the master
1489 1489 // humongous set should be invoked while holding the Heap_lock.
1490 1490
1491 1491 if (SafepointSynchronize::is_at_safepoint()) {
1492 1492 guarantee(Thread::current()->is_VM_thread() ||
1493 1493 OldSets_lock->owned_by_self(),
1494 1494 "master humongous set MT safety protocol at a safepoint");
1495 1495 } else {
1496 1496 guarantee(Heap_lock->owned_by_self(),
1497 1497 "master humongous set MT safety protocol outside a safepoint");
1498 1498 }
1499 1499 }
1500 1500 bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); }
1501 1501 const char* get_description() { return "Humongous Regions"; }
1502 1502 };
1503 1503
1504 1504 G1CollectedHeap::G1CollectedHeap() :
1505 1505 CollectedHeap(),
1506 1506 _young_gen_sampling_thread(NULL),
1507 1507 _workers(NULL),
1508 1508 _card_table(NULL),
1509 1509 _soft_ref_policy(),
1510 1510 _old_set("Old Region Set", new OldRegionSetChecker()),
1511 1511 _archive_set("Archive Region Set", new ArchiveRegionSetChecker()),
1512 1512 _humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),
1513 1513 _bot(NULL),
1514 1514 _listener(),
1515 1515 _numa(G1NUMA::create()),
1516 1516 _hrm(NULL),
1517 1517 _allocator(NULL),
1518 1518 _verifier(NULL),
1519 1519 _summary_bytes_used(0),
1520 1520 _bytes_used_during_gc(0),
1521 1521 _archive_allocator(NULL),
1522 1522 _survivor_evac_stats("Young", YoungPLABSize, PLABWeight),
1523 1523 _old_evac_stats("Old", OldPLABSize, PLABWeight),
1524 1524 _expand_heap_after_alloc_failure(true),
1525 1525 _g1mm(NULL),
1526 1526 _humongous_reclaim_candidates(),
1527 1527 _has_humongous_reclaim_candidates(false),
1528 1528 _hr_printer(),
1529 1529 _collector_state(),
1530 1530 _old_marking_cycles_started(0),
1531 1531 _old_marking_cycles_completed(0),
1532 1532 _eden(),
1533 1533 _survivor(),
1534 1534 _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1535 1535 _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1536 1536 _policy(G1Policy::create_policy(_gc_timer_stw)),
1537 1537 _heap_sizing_policy(NULL),
1538 1538 _collection_set(this, _policy),
1539 1539 _hot_card_cache(NULL),
1540 1540 _rem_set(NULL),
1541 1541 _cm(NULL),
1542 1542 _cm_thread(NULL),
1543 1543 _cr(NULL),
1544 1544 _task_queues(NULL),
1545 1545 _evacuation_failed(false),
1546 1546 _evacuation_failed_info_array(NULL),
1547 1547 _preserved_marks_set(true /* in_c_heap */),
1548 1548 #ifndef PRODUCT
1549 1549 _evacuation_failure_alot_for_current_gc(false),
1550 1550 _evacuation_failure_alot_gc_number(0),
1551 1551 _evacuation_failure_alot_count(0),
1552 1552 #endif
1553 1553 _ref_processor_stw(NULL),
1554 1554 _is_alive_closure_stw(this),
1555 1555 _is_subject_to_discovery_stw(this),
1556 1556 _ref_processor_cm(NULL),
1557 1557 _is_alive_closure_cm(this),
1558 1558 _is_subject_to_discovery_cm(this),
1559 1559 _region_attr() {
1560 1560
1561 1561 _verifier = new G1HeapVerifier(this);
1562 1562
1563 1563 _allocator = new G1Allocator(this);
1564 1564
1565 1565 _heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());
1566 1566
1567 1567 _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);
1568 1568
1569 1569 // Override the default _filler_array_max_size so that no humongous filler
1570 1570 // objects are created.
1571 1571 _filler_array_max_size = _humongous_object_threshold_in_words;
1572 1572
1573 1573 uint n_queues = ParallelGCThreads;
1574 1574 _task_queues = new RefToScanQueueSet(n_queues);
1575 1575
1576 1576 _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
1577 1577
1578 1578 for (uint i = 0; i < n_queues; i++) {
1579 1579 RefToScanQueue* q = new RefToScanQueue();
1580 1580 q->initialize();
1581 1581 _task_queues->register_queue(i, q);
1582 1582 ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
1583 1583 }
1584 1584
1585 1585 // Initialize the G1EvacuationFailureALot counters and flags.
1586 1586 NOT_PRODUCT(reset_evacuation_should_fail();)
1587 1587 _gc_tracer_stw->initialize();
1588 1588
1589 1589 guarantee(_task_queues != NULL, "task_queues allocation failure.");
1590 1590 }
1591 1591
1592 1592 static size_t actual_reserved_page_size(ReservedSpace rs) {
1593 1593 size_t page_size = os::vm_page_size();
1594 1594 if (UseLargePages) {
1595 1595 // There are two ways to manage large page memory.
1596 1596 // 1. OS supports committing large page memory.
1597 1597 // 2. OS doesn't support committing large page memory so ReservedSpace manages it.
1598 1598 // And ReservedSpace calls it 'special'. If we failed to set 'special',
1599 1599 // we reserved memory without large page.
1600 1600 if (os::can_commit_large_page_memory() || rs.special()) {
1601 1601 // An alignment at ReservedSpace comes from preferred page size or
1602 1602 // heap alignment, and if the alignment came from heap alignment, it could be
1603 1603 // larger than large pages size. So need to cap with the large page size.
1604 1604 page_size = MIN2(rs.alignment(), os::large_page_size());
1605 1605 }
1606 1606 }
1607 1607
1608 1608 return page_size;
1609 1609 }
1610 1610
1611 1611 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,
1612 1612 size_t size,
1613 1613 size_t translation_factor) {
1614 1614 size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);
1615 1615 // Allocate a new reserved space, preferring to use large pages.
1616 1616 ReservedSpace rs(size, preferred_page_size);
1617 1617 size_t page_size = actual_reserved_page_size(rs);
1618 1618 G1RegionToSpaceMapper* result =
1619 1619 G1RegionToSpaceMapper::create_mapper(rs,
1620 1620 size,
1621 1621 page_size,
1622 1622 HeapRegion::GrainBytes,
1623 1623 translation_factor,
1624 1624 mtGC);
1625 1625
1626 1626 os::trace_page_sizes_for_requested_size(description,
1627 1627 size,
1628 1628 preferred_page_size,
1629 1629 page_size,
1630 1630 rs.base(),
1631 1631 rs.size());
1632 1632
1633 1633 return result;
1634 1634 }
1635 1635
1636 1636 jint G1CollectedHeap::initialize_concurrent_refinement() {
1637 1637 jint ecode = JNI_OK;
1638 1638 _cr = G1ConcurrentRefine::create(&ecode);
1639 1639 return ecode;
1640 1640 }
1641 1641
1642 1642 jint G1CollectedHeap::initialize_young_gen_sampling_thread() {
1643 1643 _young_gen_sampling_thread = new G1YoungRemSetSamplingThread();
1644 1644 if (_young_gen_sampling_thread->osthread() == NULL) {
1645 1645 vm_shutdown_during_initialization("Could not create G1YoungRemSetSamplingThread");
1646 1646 return JNI_ENOMEM;
1647 1647 }
1648 1648 return JNI_OK;
1649 1649 }
1650 1650
1651 1651 jint G1CollectedHeap::initialize() {
1652 1652
1653 1653 // Necessary to satisfy locking discipline assertions.
1654 1654
1655 1655 MutexLocker x(Heap_lock);
1656 1656
1657 1657 // While there are no constraints in the GC code that HeapWordSize
1658 1658 // be any particular value, there are multiple other areas in the
1659 1659 // system which believe this to be true (e.g. oop->object_size in some
1660 1660 // cases incorrectly returns the size in wordSize units rather than
1661 1661 // HeapWordSize).
1662 1662 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1663 1663
1664 1664 size_t init_byte_size = InitialHeapSize;
1665 1665 size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();
1666 1666
1667 1667 // Ensure that the sizes are properly aligned.
1668 1668 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1669 1669 Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap");
1670 1670 Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");
1671 1671
1672 1672 // Reserve the maximum.
1673 1673
1674 1674 // When compressed oops are enabled, the preferred heap base
1675 1675 // is calculated by subtracting the requested size from the
1676 1676 // 32Gb boundary and using the result as the base address for
1677 1677 // heap reservation. If the requested size is not aligned to
1678 1678 // HeapRegion::GrainBytes (i.e. the alignment that is passed
1679 1679 // into the ReservedHeapSpace constructor) then the actual
1680 1680 // base of the reserved heap may end up differing from the
1681 1681 // address that was requested (i.e. the preferred heap base).
1682 1682 // If this happens then we could end up using a non-optimal
1683 1683 // compressed oops mode.
1684 1684
1685 1685 ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,
1686 1686 HeapAlignment);
1687 1687
1688 1688 initialize_reserved_region(heap_rs);
1689 1689
1690 1690 // Create the barrier set for the entire reserved region.
1691 1691 G1CardTable* ct = new G1CardTable(heap_rs.region());
1692 1692 ct->initialize();
1693 1693 G1BarrierSet* bs = new G1BarrierSet(ct);
1694 1694 bs->initialize();
1695 1695 assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");
1696 1696 BarrierSet::set_barrier_set(bs);
1697 1697 _card_table = ct;
1698 1698
1699 1699 {
1700 1700 G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();
1701 1701 satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);
1702 1702 satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);
1703 1703 }
1704 1704
1705 1705 // Create the hot card cache.
1706 1706 _hot_card_cache = new G1HotCardCache(this);
1707 1707
1708 1708 // Carve out the G1 part of the heap.
1709 1709 ReservedSpace g1_rs = heap_rs.first_part(reserved_byte_size);
1710 1710 size_t page_size = actual_reserved_page_size(heap_rs);
1711 1711 G1RegionToSpaceMapper* heap_storage =
1712 1712 G1RegionToSpaceMapper::create_heap_mapper(g1_rs,
1713 1713 g1_rs.size(),
1714 1714 page_size,
1715 1715 HeapRegion::GrainBytes,
1716 1716 1,
1717 1717 mtJavaHeap);
1718 1718 if(heap_storage == NULL) {
1719 1719 vm_shutdown_during_initialization("Could not initialize G1 heap");
1720 1720 return JNI_ERR;
1721 1721 }
1722 1722
1723 1723 os::trace_page_sizes("Heap",
1724 1724 MinHeapSize,
1725 1725 reserved_byte_size,
1726 1726 page_size,
1727 1727 heap_rs.base(),
1728 1728 heap_rs.size());
1729 1729 heap_storage->set_mapping_changed_listener(&_listener);
1730 1730
1731 1731 // Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.
1732 1732 G1RegionToSpaceMapper* bot_storage =
1733 1733 create_aux_memory_mapper("Block Offset Table",
1734 1734 G1BlockOffsetTable::compute_size(g1_rs.size() / HeapWordSize),
1735 1735 G1BlockOffsetTable::heap_map_factor());
1736 1736
1737 1737 G1RegionToSpaceMapper* cardtable_storage =
1738 1738 create_aux_memory_mapper("Card Table",
1739 1739 G1CardTable::compute_size(g1_rs.size() / HeapWordSize),
1740 1740 G1CardTable::heap_map_factor());
1741 1741
1742 1742 G1RegionToSpaceMapper* card_counts_storage =
1743 1743 create_aux_memory_mapper("Card Counts Table",
1744 1744 G1CardCounts::compute_size(g1_rs.size() / HeapWordSize),
1745 1745 G1CardCounts::heap_map_factor());
1746 1746
1747 1747 size_t bitmap_size = G1CMBitMap::compute_size(g1_rs.size());
1748 1748 G1RegionToSpaceMapper* prev_bitmap_storage =
1749 1749 create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1750 1750 G1RegionToSpaceMapper* next_bitmap_storage =
1751 1751 create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1752 1752
1753 1753 _hrm = HeapRegionManager::create_manager(this);
1754 1754
1755 1755 _hrm->initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);
1756 1756 _card_table->initialize(cardtable_storage);
1757 1757
1758 1758 // Do later initialization work for concurrent refinement.
1759 1759 _hot_card_cache->initialize(card_counts_storage);
1760 1760
1761 1761 // 6843694 - ensure that the maximum region index can fit
1762 1762 // in the remembered set structures.
1763 1763 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1764 1764 guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
1765 1765
1766 1766 // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not
1767 1767 // start within the first card.
1768 1768 guarantee(g1_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card.");
1769 1769 // Also create a G1 rem set.
1770 1770 _rem_set = new G1RemSet(this, _card_table, _hot_card_cache);
1771 1771 _rem_set->initialize(max_reserved_capacity(), max_regions());
1772 1772
1773 1773 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1774 1774 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1775 1775 guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
1776 1776 "too many cards per region");
1777 1777
1778 1778 FreeRegionList::set_unrealistically_long_length(max_expandable_regions() + 1);
1779 1779
1780 1780 _bot = new G1BlockOffsetTable(reserved_region(), bot_storage);
1781 1781
1782 1782 {
1783 1783 HeapWord* start = _hrm->reserved().start();
1784 1784 HeapWord* end = _hrm->reserved().end();
1785 1785 size_t granularity = HeapRegion::GrainBytes;
1786 1786
1787 1787 _region_attr.initialize(start, end, granularity);
1788 1788 _humongous_reclaim_candidates.initialize(start, end, granularity);
1789 1789 }
1790 1790
1791 1791 _workers = new WorkGang("GC Thread", ParallelGCThreads,
1792 1792 true /* are_GC_task_threads */,
1793 1793 false /* are_ConcurrentGC_threads */);
1794 1794 if (_workers == NULL) {
1795 1795 return JNI_ENOMEM;
1796 1796 }
1797 1797 _workers->initialize_workers();
1798 1798
1799 1799 _numa->set_region_info(HeapRegion::GrainBytes, page_size);
1800 1800
1801 1801 // Create the G1ConcurrentMark data structure and thread.
1802 1802 // (Must do this late, so that "max_regions" is defined.)
1803 1803 _cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);
1804 1804 if (_cm == NULL || !_cm->completed_initialization()) {
1805 1805 vm_shutdown_during_initialization("Could not create/initialize G1ConcurrentMark");
1806 1806 return JNI_ENOMEM;
1807 1807 }
1808 1808 _cm_thread = _cm->cm_thread();
1809 1809
1810 1810 // Now expand into the initial heap size.
1811 1811 if (!expand(init_byte_size, _workers)) {
1812 1812 vm_shutdown_during_initialization("Failed to allocate initial heap.");
1813 1813 return JNI_ENOMEM;
1814 1814 }
1815 1815
1816 1816 // Perform any initialization actions delegated to the policy.
1817 1817 policy()->init(this, &_collection_set);
1818 1818
1819 1819 jint ecode = initialize_concurrent_refinement();
1820 1820 if (ecode != JNI_OK) {
1821 1821 return ecode;
1822 1822 }
1823 1823
1824 1824 ecode = initialize_young_gen_sampling_thread();
1825 1825 if (ecode != JNI_OK) {
1826 1826 return ecode;
1827 1827 }
1828 1828
1829 1829 {
1830 1830 G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();
1831 1831 dcqs.set_process_cards_threshold(concurrent_refine()->yellow_zone());
1832 1832 dcqs.set_max_cards(concurrent_refine()->red_zone());
1833 1833 }
1834 1834
1835 1835 // Here we allocate the dummy HeapRegion that is required by the
1836 1836 // G1AllocRegion class.
1837 1837 HeapRegion* dummy_region = _hrm->get_dummy_region();
1838 1838
1839 1839 // We'll re-use the same region whether the alloc region will
1840 1840 // require BOT updates or not and, if it doesn't, then a non-young
1841 1841 // region will complain that it cannot support allocations without
1842 1842 // BOT updates. So we'll tag the dummy region as eden to avoid that.
1843 1843 dummy_region->set_eden();
1844 1844 // Make sure it's full.
1845 1845 dummy_region->set_top(dummy_region->end());
1846 1846 G1AllocRegion::setup(this, dummy_region);
1847 1847
1848 1848 _allocator->init_mutator_alloc_regions();
1849 1849
1850 1850 // Do create of the monitoring and management support so that
1851 1851 // values in the heap have been properly initialized.
1852 1852 _g1mm = new G1MonitoringSupport(this);
1853 1853
1854 1854 G1StringDedup::initialize();
1855 1855
1856 1856 _preserved_marks_set.init(ParallelGCThreads);
1857 1857
1858 1858 _collection_set.initialize(max_regions());
1859 1859
1860 1860 return JNI_OK;
1861 1861 }
1862 1862
1863 1863 void G1CollectedHeap::stop() {
1864 1864 // Stop all concurrent threads. We do this to make sure these threads
1865 1865 // do not continue to execute and access resources (e.g. logging)
1866 1866 // that are destroyed during shutdown.
1867 1867 _cr->stop();
1868 1868 _young_gen_sampling_thread->stop();
1869 1869 _cm_thread->stop();
1870 1870 if (G1StringDedup::is_enabled()) {
1871 1871 G1StringDedup::stop();
1872 1872 }
1873 1873 }
1874 1874
1875 1875 void G1CollectedHeap::safepoint_synchronize_begin() {
1876 1876 SuspendibleThreadSet::synchronize();
1877 1877 }
1878 1878
1879 1879 void G1CollectedHeap::safepoint_synchronize_end() {
1880 1880 SuspendibleThreadSet::desynchronize();
1881 1881 }
1882 1882
1883 1883 void G1CollectedHeap::post_initialize() {
1884 1884 CollectedHeap::post_initialize();
1885 1885 ref_processing_init();
1886 1886 }
1887 1887
1888 1888 void G1CollectedHeap::ref_processing_init() {
1889 1889 // Reference processing in G1 currently works as follows:
1890 1890 //
1891 1891 // * There are two reference processor instances. One is
1892 1892 // used to record and process discovered references
1893 1893 // during concurrent marking; the other is used to
1894 1894 // record and process references during STW pauses
1895 1895 // (both full and incremental).
1896 1896 // * Both ref processors need to 'span' the entire heap as
1897 1897 // the regions in the collection set may be dotted around.
1898 1898 //
1899 1899 // * For the concurrent marking ref processor:
1900 1900 // * Reference discovery is enabled at initial marking.
1901 1901 // * Reference discovery is disabled and the discovered
1902 1902 // references processed etc during remarking.
1903 1903 // * Reference discovery is MT (see below).
1904 1904 // * Reference discovery requires a barrier (see below).
1905 1905 // * Reference processing may or may not be MT
1906 1906 // (depending on the value of ParallelRefProcEnabled
1907 1907 // and ParallelGCThreads).
1908 1908 // * A full GC disables reference discovery by the CM
1909 1909 // ref processor and abandons any entries on it's
1910 1910 // discovered lists.
1911 1911 //
1912 1912 // * For the STW processor:
1913 1913 // * Non MT discovery is enabled at the start of a full GC.
1914 1914 // * Processing and enqueueing during a full GC is non-MT.
1915 1915 // * During a full GC, references are processed after marking.
1916 1916 //
1917 1917 // * Discovery (may or may not be MT) is enabled at the start
1918 1918 // of an incremental evacuation pause.
1919 1919 // * References are processed near the end of a STW evacuation pause.
1920 1920 // * For both types of GC:
1921 1921 // * Discovery is atomic - i.e. not concurrent.
1922 1922 // * Reference discovery will not need a barrier.
1923 1923
1924 1924 bool mt_processing = ParallelRefProcEnabled && (ParallelGCThreads > 1);
1925 1925
1926 1926 // Concurrent Mark ref processor
1927 1927 _ref_processor_cm =
1928 1928 new ReferenceProcessor(&_is_subject_to_discovery_cm,
1929 1929 mt_processing, // mt processing
1930 1930 ParallelGCThreads, // degree of mt processing
1931 1931 (ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery
1932 1932 MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery
1933 1933 false, // Reference discovery is not atomic
1934 1934 &_is_alive_closure_cm, // is alive closure
1935 1935 true); // allow changes to number of processing threads
1936 1936
1937 1937 // STW ref processor
1938 1938 _ref_processor_stw =
1939 1939 new ReferenceProcessor(&_is_subject_to_discovery_stw,
1940 1940 mt_processing, // mt processing
1941 1941 ParallelGCThreads, // degree of mt processing
1942 1942 (ParallelGCThreads > 1), // mt discovery
1943 1943 ParallelGCThreads, // degree of mt discovery
1944 1944 true, // Reference discovery is atomic
1945 1945 &_is_alive_closure_stw, // is alive closure
1946 1946 true); // allow changes to number of processing threads
1947 1947 }
1948 1948
1949 1949 SoftRefPolicy* G1CollectedHeap::soft_ref_policy() {
1950 1950 return &_soft_ref_policy;
1951 1951 }
1952 1952
1953 1953 size_t G1CollectedHeap::capacity() const {
1954 1954 return _hrm->length() * HeapRegion::GrainBytes;
1955 1955 }
1956 1956
1957 1957 size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {
1958 1958 return _hrm->total_free_bytes();
1959 1959 }
1960 1960
1961 1961 void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) {
1962 1962 _hot_card_cache->drain(cl, worker_id);
1963 1963 }
1964 1964
1965 1965 // Computes the sum of the storage used by the various regions.
1966 1966 size_t G1CollectedHeap::used() const {
1967 1967 size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();
1968 1968 if (_archive_allocator != NULL) {
1969 1969 result += _archive_allocator->used();
1970 1970 }
1971 1971 return result;
1972 1972 }
1973 1973
1974 1974 size_t G1CollectedHeap::used_unlocked() const {
1975 1975 return _summary_bytes_used;
1976 1976 }
1977 1977
1978 1978 class SumUsedClosure: public HeapRegionClosure {
1979 1979 size_t _used;
1980 1980 public:
1981 1981 SumUsedClosure() : _used(0) {}
1982 1982 bool do_heap_region(HeapRegion* r) {
1983 1983 _used += r->used();
1984 1984 return false;
1985 1985 }
1986 1986 size_t result() { return _used; }
1987 1987 };
1988 1988
1989 1989 size_t G1CollectedHeap::recalculate_used() const {
1990 1990 SumUsedClosure blk;
1991 1991 heap_region_iterate(&blk);
1992 1992 return blk.result();
1993 1993 }
1994 1994
1995 1995 bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {
1996 1996 switch (cause) {
1997 1997 case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;
1998 1998 case GCCause::_dcmd_gc_run: return ExplicitGCInvokesConcurrent;
1999 1999 case GCCause::_wb_conc_mark: return true;
2000 2000 default : return false;
2001 2001 }
2002 2002 }
2003 2003
2004 2004 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
2005 2005 switch (cause) {
2006 2006 case GCCause::_g1_humongous_allocation: return true;
2007 2007 case GCCause::_g1_periodic_collection: return G1PeriodicGCInvokesConcurrent;
2008 2008 default: return is_user_requested_concurrent_full_gc(cause);
2009 2009 }
2010 2010 }
2011 2011
2012 2012 bool G1CollectedHeap::should_upgrade_to_full_gc(GCCause::Cause cause) {
2013 2013 if (policy()->force_upgrade_to_full()) {
2014 2014 return true;
2015 2015 } else if (should_do_concurrent_full_gc(_gc_cause)) {
2016 2016 return false;
2017 2017 } else if (has_regions_left_for_allocation()) {
2018 2018 return false;
2019 2019 } else {
2020 2020 return true;
2021 2021 }
2022 2022 }
2023 2023
2024 2024 #ifndef PRODUCT
2025 2025 void G1CollectedHeap::allocate_dummy_regions() {
2026 2026 // Let's fill up most of the region
2027 2027 size_t word_size = HeapRegion::GrainWords - 1024;
2028 2028 // And as a result the region we'll allocate will be humongous.
2029 2029 guarantee(is_humongous(word_size), "sanity");
2030 2030
2031 2031 // _filler_array_max_size is set to humongous object threshold
2032 2032 // but temporarily change it to use CollectedHeap::fill_with_object().
2033 2033 SizeTFlagSetting fs(_filler_array_max_size, word_size);
2034 2034
2035 2035 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
2036 2036 // Let's use the existing mechanism for the allocation
2037 2037 HeapWord* dummy_obj = humongous_obj_allocate(word_size);
2038 2038 if (dummy_obj != NULL) {
2039 2039 MemRegion mr(dummy_obj, word_size);
2040 2040 CollectedHeap::fill_with_object(mr);
2041 2041 } else {
2042 2042 // If we can't allocate once, we probably cannot allocate
2043 2043 // again. Let's get out of the loop.
2044 2044 break;
2045 2045 }
2046 2046 }
2047 2047 }
2048 2048 #endif // !PRODUCT
2049 2049
2050 2050 void G1CollectedHeap::increment_old_marking_cycles_started() {
2051 2051 assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
2052 2052 _old_marking_cycles_started == _old_marking_cycles_completed + 1,
2053 2053 "Wrong marking cycle count (started: %d, completed: %d)",
2054 2054 _old_marking_cycles_started, _old_marking_cycles_completed);
2055 2055
2056 2056 _old_marking_cycles_started++;
2057 2057 }
2058 2058
2059 2059 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) {
2060 2060 MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);
2061 2061
2062 2062 // We assume that if concurrent == true, then the caller is a
2063 2063 // concurrent thread that was joined the Suspendible Thread
2064 2064 // Set. If there's ever a cheap way to check this, we should add an
2065 2065 // assert here.
2066 2066
2067 2067 // Given that this method is called at the end of a Full GC or of a
2068 2068 // concurrent cycle, and those can be nested (i.e., a Full GC can
2069 2069 // interrupt a concurrent cycle), the number of full collections
2070 2070 // completed should be either one (in the case where there was no
2071 2071 // nesting) or two (when a Full GC interrupted a concurrent cycle)
2072 2072 // behind the number of full collections started.
2073 2073
2074 2074 // This is the case for the inner caller, i.e. a Full GC.
2075 2075 assert(concurrent ||
2076 2076 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
2077 2077 (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
2078 2078 "for inner caller (Full GC): _old_marking_cycles_started = %u "
2079 2079 "is inconsistent with _old_marking_cycles_completed = %u",
2080 2080 _old_marking_cycles_started, _old_marking_cycles_completed);
2081 2081
2082 2082 // This is the case for the outer caller, i.e. the concurrent cycle.
2083 2083 assert(!concurrent ||
2084 2084 (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
2085 2085 "for outer caller (concurrent cycle): "
2086 2086 "_old_marking_cycles_started = %u "
2087 2087 "is inconsistent with _old_marking_cycles_completed = %u",
2088 2088 _old_marking_cycles_started, _old_marking_cycles_completed);
2089 2089
2090 2090 _old_marking_cycles_completed += 1;
2091 2091
2092 2092 // We need to clear the "in_progress" flag in the CM thread before
2093 2093 // we wake up any waiters (especially when ExplicitInvokesConcurrent
2094 2094 // is set) so that if a waiter requests another System.gc() it doesn't
2095 2095 // incorrectly see that a marking cycle is still in progress.
2096 2096 if (concurrent) {
2097 2097 _cm_thread->set_idle();
2098 2098 }
2099 2099
2100 2100 // Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)
2101 2101 // for a full GC to finish that their wait is over.
2102 2102 ml.notify_all();
2103 2103 }
2104 2104
2105 2105 void G1CollectedHeap::collect(GCCause::Cause cause) {
2106 2106 try_collect(cause);
2107 2107 }
2108 2108
2109 2109 // Return true if (x < y) with allowance for wraparound.
2110 2110 static bool gc_counter_less_than(uint x, uint y) {
2111 2111 return (x - y) > (UINT_MAX/2);
2112 2112 }
2113 2113
2114 2114 // LOG_COLLECT_CONCURRENTLY(cause, msg, args...)
2115 2115 // Macro so msg printing is format-checked.
2116 2116 #define LOG_COLLECT_CONCURRENTLY(cause, ...) \
2117 2117 do { \
2118 2118 LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt; \
2119 2119 if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) { \
2120 2120 ResourceMark rm; /* For thread name. */ \
2121 2121 LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \
2122 2122 LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \
2123 2123 Thread::current()->name(), \
2124 2124 GCCause::to_string(cause)); \
2125 2125 LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__); \
2126 2126 } \
2127 2127 } while (0)
2128 2128
2129 2129 #define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \
2130 2130 LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))
2131 2131
2132 2132 bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause,
2133 2133 uint gc_counter,
2134 2134 uint old_marking_started_before) {
2135 2135 assert_heap_not_locked();
2136 2136 assert(should_do_concurrent_full_gc(cause),
2137 2137 "Non-concurrent cause %s", GCCause::to_string(cause));
2138 2138
2139 2139 for (uint i = 1; true; ++i) {
2140 2140 // Try to schedule an initial-mark evacuation pause that will
2141 2141 // start a concurrent cycle.
2142 2142 LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);
2143 2143 VM_G1TryInitiateConcMark op(gc_counter,
2144 2144 cause,
2145 2145 policy()->max_pause_time_ms());
2146 2146 VMThread::execute(&op);
2147 2147
2148 2148 // Request is trivially finished.
2149 2149 if (cause == GCCause::_g1_periodic_collection) {
2150 2150 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());
2151 2151 return op.gc_succeeded();
2152 2152 }
2153 2153
2154 2154 // If VMOp skipped initiating concurrent marking cycle because
2155 2155 // we're terminating, then we're done.
2156 2156 if (op.terminating()) {
2157 2157 LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");
2158 2158 return false;
2159 2159 }
2160 2160
2161 2161 // Lock to get consistent set of values.
2162 2162 uint old_marking_started_after;
2163 2163 uint old_marking_completed_after;
2164 2164 {
2165 2165 MutexLocker ml(Heap_lock);
2166 2166 // Update gc_counter for retrying VMOp if needed. Captured here to be
2167 2167 // consistent with the values we use below for termination tests. If
2168 2168 // a retry is needed after a possible wait, and another collection
2169 2169 // occurs in the meantime, it will cause our retry to be skipped and
2170 2170 // we'll recheck for termination with updated conditions from that
2171 2171 // more recent collection. That's what we want, rather than having
2172 2172 // our retry possibly perform an unnecessary collection.
2173 2173 gc_counter = total_collections();
2174 2174 old_marking_started_after = _old_marking_cycles_started;
2175 2175 old_marking_completed_after = _old_marking_cycles_completed;
2176 2176 }
2177 2177
2178 2178 if (!GCCause::is_user_requested_gc(cause)) {
2179 2179 // For an "automatic" (not user-requested) collection, we just need to
2180 2180 // ensure that progress is made.
2181 2181 //
2182 2182 // Request is finished if any of
2183 2183 // (1) the VMOp successfully performed a GC,
2184 2184 // (2) a concurrent cycle was already in progress,
2185 2185 // (3) a new cycle was started (by this thread or some other), or
2186 2186 // (4) a Full GC was performed.
2187 2187 // Cases (3) and (4) are detected together by a change to
2188 2188 // _old_marking_cycles_started.
2189 2189 //
2190 2190 // Note that (1) does not imply (3). If we're still in the mixed
2191 2191 // phase of an earlier concurrent collection, the request to make the
2192 2192 // collection an initial-mark won't be honored. If we don't check for
2193 2193 // both conditions we'll spin doing back-to-back collections.
2194 2194 if (op.gc_succeeded() ||
2195 2195 op.cycle_already_in_progress() ||
2196 2196 (old_marking_started_before != old_marking_started_after)) {
2197 2197 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2198 2198 return true;
2199 2199 }
2200 2200 } else { // User-requested GC.
2201 2201 // For a user-requested collection, we want to ensure that a complete
2202 2202 // full collection has been performed before returning, but without
2203 2203 // waiting for more than needed.
2204 2204
2205 2205 // For user-requested GCs (unlike non-UR), a successful VMOp implies a
2206 2206 // new cycle was started. That's good, because it's not clear what we
2207 2207 // should do otherwise. Trying again just does back to back GCs.
2208 2208 // Can't wait for someone else to start a cycle. And returning fails
2209 2209 // to meet the goal of ensuring a full collection was performed.
2210 2210 assert(!op.gc_succeeded() ||
2211 2211 (old_marking_started_before != old_marking_started_after),
2212 2212 "invariant: succeeded %s, started before %u, started after %u",
2213 2213 BOOL_TO_STR(op.gc_succeeded()),
2214 2214 old_marking_started_before, old_marking_started_after);
2215 2215
2216 2216 // Request is finished if a full collection (concurrent or stw)
2217 2217 // was started after this request and has completed, e.g.
2218 2218 // started_before < completed_after.
2219 2219 if (gc_counter_less_than(old_marking_started_before,
2220 2220 old_marking_completed_after)) {
2221 2221 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2222 2222 return true;
2223 2223 }
2224 2224
2225 2225 if (old_marking_started_after != old_marking_completed_after) {
2226 2226 // If there is an in-progress cycle (possibly started by us), then
2227 2227 // wait for that cycle to complete, e.g.
2228 2228 // while completed_now < started_after.
2229 2229 LOG_COLLECT_CONCURRENTLY(cause, "wait");
2230 2230 MonitorLocker ml(G1OldGCCount_lock);
2231 2231 while (gc_counter_less_than(_old_marking_cycles_completed,
2232 2232 old_marking_started_after)) {
2233 2233 ml.wait();
2234 2234 }
2235 2235 // Request is finished if the collection we just waited for was
2236 2236 // started after this request.
2237 2237 if (old_marking_started_before != old_marking_started_after) {
2238 2238 LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");
2239 2239 return true;
2240 2240 }
2241 2241 }
2242 2242
2243 2243 // If VMOp was successful then it started a new cycle that the above
2244 2244 // wait &etc should have recognized as finishing this request. This
2245 2245 // differs from a non-user-request, where gc_succeeded does not imply
2246 2246 // a new cycle was started.
2247 2247 assert(!op.gc_succeeded(), "invariant");
2248 2248
2249 2249 // If VMOp failed because a cycle was already in progress, it is now
2250 2250 // complete. But it didn't finish this user-requested GC, so try
2251 2251 // again.
2252 2252 if (op.cycle_already_in_progress()) {
2253 2253 LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");
2254 2254 continue;
2255 2255 }
2256 2256 }
2257 2257
2258 2258 // Collection failed and should be retried.
2259 2259 assert(op.transient_failure(), "invariant");
2260 2260
2261 2261 // If GCLocker is active, wait until clear before retrying.
2262 2262 if (GCLocker::is_active_and_needs_gc()) {
2263 2263 LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall");
2264 2264 GCLocker::stall_until_clear();
2265 2265 }
2266 2266
2267 2267 LOG_COLLECT_CONCURRENTLY(cause, "retry");
2268 2268 }
2269 2269 }
2270 2270
2271 2271 bool G1CollectedHeap::try_collect(GCCause::Cause cause) {
2272 2272 assert_heap_not_locked();
2273 2273
2274 2274 // Lock to get consistent set of values.
2275 2275 uint gc_count_before;
2276 2276 uint full_gc_count_before;
2277 2277 uint old_marking_started_before;
2278 2278 {
2279 2279 MutexLocker ml(Heap_lock);
2280 2280 gc_count_before = total_collections();
2281 2281 full_gc_count_before = total_full_collections();
2282 2282 old_marking_started_before = _old_marking_cycles_started;
2283 2283 }
2284 2284
2285 2285 if (should_do_concurrent_full_gc(cause)) {
2286 2286 return try_collect_concurrently(cause,
2287 2287 gc_count_before,
2288 2288 old_marking_started_before);
2289 2289 } else if (GCLocker::should_discard(cause, gc_count_before)) {
2290 2290 // Indicate failure to be consistent with VMOp failure due to
2291 2291 // another collection slipping in after our gc_count but before
2292 2292 // our request is processed.
2293 2293 return false;
2294 2294 } else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc
2295 2295 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2296 2296
2297 2297 // Schedule a standard evacuation pause. We're setting word_size
2298 2298 // to 0 which means that we are not requesting a post-GC allocation.
2299 2299 VM_G1CollectForAllocation op(0, /* word_size */
2300 2300 gc_count_before,
2301 2301 cause,
2302 2302 policy()->max_pause_time_ms());
2303 2303 VMThread::execute(&op);
2304 2304 return op.gc_succeeded();
2305 2305 } else {
2306 2306 // Schedule a Full GC.
2307 2307 VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);
2308 2308 VMThread::execute(&op);
2309 2309 return op.gc_succeeded();
2310 2310 }
2311 2311 }
2312 2312
2313 2313 bool G1CollectedHeap::is_in(const void* p) const {
2314 2314 if (_hrm->reserved().contains(p)) {
2315 2315 // Given that we know that p is in the reserved space,
2316 2316 // heap_region_containing() should successfully
2317 2317 // return the containing region.
2318 2318 HeapRegion* hr = heap_region_containing(p);
2319 2319 return hr->is_in(p);
2320 2320 } else {
2321 2321 return false;
2322 2322 }
2323 2323 }
2324 2324
2325 2325 #ifdef ASSERT
2326 2326 bool G1CollectedHeap::is_in_exact(const void* p) const {
2327 2327 bool contains = reserved_region().contains(p);
2328 2328 bool available = _hrm->is_available(addr_to_region((HeapWord*)p));
2329 2329 if (contains && available) {
2330 2330 return true;
2331 2331 } else {
2332 2332 return false;
2333 2333 }
2334 2334 }
2335 2335 #endif
2336 2336
2337 2337 // Iteration functions.
2338 2338
2339 2339 // Iterates an ObjectClosure over all objects within a HeapRegion.
2340 2340
2341 2341 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2342 2342 ObjectClosure* _cl;
2343 2343 public:
2344 2344 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2345 2345 bool do_heap_region(HeapRegion* r) {
2346 2346 if (!r->is_continues_humongous()) {
2347 2347 r->object_iterate(_cl);
2348 2348 }
2349 2349 return false;
2350 2350 }
2351 2351 };
2352 2352
2353 2353 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2354 2354 IterateObjectClosureRegionClosure blk(cl);
2355 2355 heap_region_iterate(&blk);
2356 2356 }
2357 2357
2358 2358 void G1CollectedHeap::keep_alive(oop obj) {
2359 2359 G1BarrierSet::enqueue(obj);
2360 2360 }
2361 2361
2362 2362 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2363 2363 _hrm->iterate(cl);
2364 2364 }
2365 2365
2366 2366 void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,
2367 2367 HeapRegionClaimer *hrclaimer,
2368 2368 uint worker_id) const {
2369 2369 _hrm->par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));
2370 2370 }
2371 2371
2372 2372 void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl,
2373 2373 HeapRegionClaimer *hrclaimer) const {
2374 2374 _hrm->par_iterate(cl, hrclaimer, 0);
2375 2375 }
2376 2376
2377 2377 void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) {
2378 2378 _collection_set.iterate(cl);
2379 2379 }
2380 2380
2381 2381 void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2382 2382 _collection_set.par_iterate(cl, hr_claimer, worker_id, workers()->active_workers());
2383 2383 }
2384 2384
2385 2385 void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2386 2386 _collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id, workers()->active_workers());
2387 2387 }
2388 2388
2389 2389 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2390 2390 HeapRegion* hr = heap_region_containing(addr);
2391 2391 return hr->block_start(addr);
2392 2392 }
2393 2393
2394 2394 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2395 2395 HeapRegion* hr = heap_region_containing(addr);
2396 2396 return hr->block_is_obj(addr);
2397 2397 }
2398 2398
2399 2399 bool G1CollectedHeap::supports_tlab_allocation() const {
2400 2400 return true;
2401 2401 }
2402 2402
2403 2403 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2404 2404 return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes;
2405 2405 }
2406 2406
2407 2407 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
2408 2408 return _eden.length() * HeapRegion::GrainBytes;
2409 2409 }
2410 2410
2411 2411 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2412 2412 // must be equal to the humongous object limit.
2413 2413 size_t G1CollectedHeap::max_tlab_size() const {
2414 2414 return align_down(_humongous_object_threshold_in_words, MinObjAlignment);
2415 2415 }
2416 2416
2417 2417 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2418 2418 return _allocator->unsafe_max_tlab_alloc();
↓ open down ↓ |
2418 lines elided |
↑ open up ↑ |
2419 2419 }
2420 2420
2421 2421 size_t G1CollectedHeap::max_capacity() const {
2422 2422 return _hrm->max_expandable_length() * HeapRegion::GrainBytes;
2423 2423 }
2424 2424
2425 2425 size_t G1CollectedHeap::max_reserved_capacity() const {
2426 2426 return _hrm->max_length() * HeapRegion::GrainBytes;
2427 2427 }
2428 2428
2429 +size_t G1CollectedHeap::soft_max_capacity() const {
2430 + return clamp(align_up(SoftMaxHeapSize, HeapAlignment), MinHeapSize, max_capacity());
2431 +}
2432 +
2429 2433 jlong G1CollectedHeap::millis_since_last_gc() {
2430 2434 // See the notes in GenCollectedHeap::millis_since_last_gc()
2431 2435 // for more information about the implementation.
2432 2436 jlong ret_val = (os::javaTimeNanos() / NANOSECS_PER_MILLISEC) -
2433 2437 _policy->collection_pause_end_millis();
2434 2438 if (ret_val < 0) {
2435 2439 log_warning(gc)("millis_since_last_gc() would return : " JLONG_FORMAT
2436 2440 ". returning zero instead.", ret_val);
2437 2441 return 0;
2438 2442 }
2439 2443 return ret_val;
2440 2444 }
2441 2445
2442 2446 void G1CollectedHeap::deduplicate_string(oop str) {
2443 2447 assert(java_lang_String::is_instance(str), "invariant");
2444 2448
2445 2449 if (G1StringDedup::is_enabled()) {
2446 2450 G1StringDedup::deduplicate(str);
2447 2451 }
2448 2452 }
2449 2453
2450 2454 void G1CollectedHeap::prepare_for_verify() {
2451 2455 _verifier->prepare_for_verify();
2452 2456 }
2453 2457
2454 2458 void G1CollectedHeap::verify(VerifyOption vo) {
2455 2459 _verifier->verify(vo);
2456 2460 }
2457 2461
2458 2462 bool G1CollectedHeap::supports_concurrent_phase_control() const {
2459 2463 return true;
2460 2464 }
2461 2465
2462 2466 bool G1CollectedHeap::request_concurrent_phase(const char* phase) {
2463 2467 return _cm_thread->request_concurrent_phase(phase);
2464 2468 }
2465 2469
2466 2470 bool G1CollectedHeap::is_heterogeneous_heap() const {
2467 2471 return G1Arguments::is_heterogeneous_heap();
2468 2472 }
2469 2473
2470 2474 class PrintRegionClosure: public HeapRegionClosure {
2471 2475 outputStream* _st;
2472 2476 public:
2473 2477 PrintRegionClosure(outputStream* st) : _st(st) {}
2474 2478 bool do_heap_region(HeapRegion* r) {
2475 2479 r->print_on(_st);
2476 2480 return false;
2477 2481 }
2478 2482 };
2479 2483
2480 2484 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2481 2485 const HeapRegion* hr,
2482 2486 const VerifyOption vo) const {
2483 2487 switch (vo) {
2484 2488 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
2485 2489 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
2486 2490 case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr);
2487 2491 default: ShouldNotReachHere();
2488 2492 }
2489 2493 return false; // keep some compilers happy
2490 2494 }
2491 2495
2492 2496 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2493 2497 const VerifyOption vo) const {
2494 2498 switch (vo) {
2495 2499 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
2496 2500 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
2497 2501 case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj);
2498 2502 default: ShouldNotReachHere();
2499 2503 }
2500 2504 return false; // keep some compilers happy
2501 2505 }
2502 2506
2503 2507 void G1CollectedHeap::print_heap_regions() const {
2504 2508 LogTarget(Trace, gc, heap, region) lt;
2505 2509 if (lt.is_enabled()) {
2506 2510 LogStream ls(lt);
2507 2511 print_regions_on(&ls);
2508 2512 }
2509 2513 }
2510 2514
2511 2515 void G1CollectedHeap::print_on(outputStream* st) const {
2512 2516 st->print(" %-20s", "garbage-first heap");
2513 2517 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
2514 2518 capacity()/K, used_unlocked()/K);
2515 2519 st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",
2516 2520 p2i(_hrm->reserved().start()),
2517 2521 p2i(_hrm->reserved().end()));
2518 2522 st->cr();
2519 2523 st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
2520 2524 uint young_regions = young_regions_count();
2521 2525 st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
2522 2526 (size_t) young_regions * HeapRegion::GrainBytes / K);
2523 2527 uint survivor_regions = survivor_regions_count();
2524 2528 st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
2525 2529 (size_t) survivor_regions * HeapRegion::GrainBytes / K);
2526 2530 st->cr();
2527 2531 if (_numa->is_enabled()) {
2528 2532 uint num_nodes = _numa->num_active_nodes();
2529 2533 st->print(" remaining free region(s) on each NUMA node: ");
2530 2534 const int* node_ids = _numa->node_ids();
2531 2535 for (uint node_index = 0; node_index < num_nodes; node_index++) {
2532 2536 st->print("%d=%u ", node_ids[node_index], _hrm->num_free_regions(node_index));
2533 2537 }
2534 2538 st->cr();
2535 2539 }
2536 2540 MetaspaceUtils::print_on(st);
2537 2541 }
2538 2542
2539 2543 void G1CollectedHeap::print_regions_on(outputStream* st) const {
2540 2544 st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "
2541 2545 "HS=humongous(starts), HC=humongous(continues), "
2542 2546 "CS=collection set, F=free, "
2543 2547 "OA=open archive, CA=closed archive, "
2544 2548 "TAMS=top-at-mark-start (previous, next)");
2545 2549 PrintRegionClosure blk(st);
2546 2550 heap_region_iterate(&blk);
2547 2551 }
2548 2552
2549 2553 void G1CollectedHeap::print_extended_on(outputStream* st) const {
2550 2554 print_on(st);
2551 2555
2552 2556 // Print the per-region information.
2553 2557 print_regions_on(st);
2554 2558 }
2555 2559
2556 2560 void G1CollectedHeap::print_on_error(outputStream* st) const {
2557 2561 this->CollectedHeap::print_on_error(st);
2558 2562
2559 2563 if (_cm != NULL) {
2560 2564 st->cr();
2561 2565 _cm->print_on_error(st);
2562 2566 }
2563 2567 }
2564 2568
2565 2569 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
2566 2570 workers()->print_worker_threads_on(st);
2567 2571 _cm_thread->print_on(st);
2568 2572 st->cr();
2569 2573 _cm->print_worker_threads_on(st);
2570 2574 _cr->print_threads_on(st);
2571 2575 _young_gen_sampling_thread->print_on(st);
2572 2576 if (G1StringDedup::is_enabled()) {
2573 2577 G1StringDedup::print_worker_threads_on(st);
2574 2578 }
2575 2579 }
2576 2580
2577 2581 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2578 2582 workers()->threads_do(tc);
2579 2583 tc->do_thread(_cm_thread);
2580 2584 _cm->threads_do(tc);
2581 2585 _cr->threads_do(tc);
2582 2586 tc->do_thread(_young_gen_sampling_thread);
2583 2587 if (G1StringDedup::is_enabled()) {
2584 2588 G1StringDedup::threads_do(tc);
2585 2589 }
2586 2590 }
2587 2591
2588 2592 void G1CollectedHeap::print_tracing_info() const {
2589 2593 rem_set()->print_summary_info();
2590 2594 concurrent_mark()->print_summary_info();
2591 2595 }
2592 2596
2593 2597 #ifndef PRODUCT
2594 2598 // Helpful for debugging RSet issues.
2595 2599
2596 2600 class PrintRSetsClosure : public HeapRegionClosure {
2597 2601 private:
2598 2602 const char* _msg;
2599 2603 size_t _occupied_sum;
2600 2604
2601 2605 public:
2602 2606 bool do_heap_region(HeapRegion* r) {
2603 2607 HeapRegionRemSet* hrrs = r->rem_set();
2604 2608 size_t occupied = hrrs->occupied();
2605 2609 _occupied_sum += occupied;
2606 2610
2607 2611 tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r));
2608 2612 if (occupied == 0) {
2609 2613 tty->print_cr(" RSet is empty");
2610 2614 } else {
2611 2615 hrrs->print();
2612 2616 }
2613 2617 tty->print_cr("----------");
2614 2618 return false;
2615 2619 }
2616 2620
2617 2621 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
2618 2622 tty->cr();
2619 2623 tty->print_cr("========================================");
2620 2624 tty->print_cr("%s", msg);
2621 2625 tty->cr();
2622 2626 }
2623 2627
2624 2628 ~PrintRSetsClosure() {
2625 2629 tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);
2626 2630 tty->print_cr("========================================");
2627 2631 tty->cr();
2628 2632 }
2629 2633 };
2630 2634
2631 2635 void G1CollectedHeap::print_cset_rsets() {
2632 2636 PrintRSetsClosure cl("Printing CSet RSets");
2633 2637 collection_set_iterate_all(&cl);
2634 2638 }
2635 2639
2636 2640 void G1CollectedHeap::print_all_rsets() {
2637 2641 PrintRSetsClosure cl("Printing All RSets");;
2638 2642 heap_region_iterate(&cl);
2639 2643 }
2640 2644 #endif // PRODUCT
2641 2645
2642 2646 bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {
2643 2647 return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);
2644 2648 }
2645 2649
2646 2650 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {
2647 2651
2648 2652 size_t eden_used_bytes = _eden.used_bytes();
2649 2653 size_t survivor_used_bytes = _survivor.used_bytes();
2650 2654 size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2651 2655
2652 2656 size_t eden_capacity_bytes =
2653 2657 (policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;
2654 2658
2655 2659 VirtualSpaceSummary heap_summary = create_heap_space_summary();
2656 2660 return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,
2657 2661 eden_capacity_bytes, survivor_used_bytes, num_regions());
2658 2662 }
2659 2663
2660 2664 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {
2661 2665 return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),
2662 2666 stats->unused(), stats->used(), stats->region_end_waste(),
2663 2667 stats->regions_filled(), stats->direct_allocated(),
2664 2668 stats->failure_used(), stats->failure_waste());
2665 2669 }
2666 2670
2667 2671 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
2668 2672 const G1HeapSummary& heap_summary = create_g1_heap_summary();
2669 2673 gc_tracer->report_gc_heap_summary(when, heap_summary);
2670 2674
2671 2675 const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
2672 2676 gc_tracer->report_metaspace_summary(when, metaspace_summary);
2673 2677 }
2674 2678
2675 2679 G1CollectedHeap* G1CollectedHeap::heap() {
2676 2680 CollectedHeap* heap = Universe::heap();
2677 2681 assert(heap != NULL, "Uninitialized access to G1CollectedHeap::heap()");
2678 2682 assert(heap->kind() == CollectedHeap::G1, "Invalid name");
2679 2683 return (G1CollectedHeap*)heap;
2680 2684 }
2681 2685
2682 2686 void G1CollectedHeap::gc_prologue(bool full) {
2683 2687 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2684 2688
2685 2689 // This summary needs to be printed before incrementing total collections.
2686 2690 rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections());
2687 2691
2688 2692 // Update common counters.
2689 2693 increment_total_collections(full /* full gc */);
2690 2694 if (full || collector_state()->in_initial_mark_gc()) {
2691 2695 increment_old_marking_cycles_started();
2692 2696 }
2693 2697
2694 2698 // Fill TLAB's and such
2695 2699 double start = os::elapsedTime();
2696 2700 ensure_parsability(true);
2697 2701 phase_times()->record_prepare_tlab_time_ms((os::elapsedTime() - start) * 1000.0);
2698 2702 }
2699 2703
2700 2704 void G1CollectedHeap::gc_epilogue(bool full) {
2701 2705 // Update common counters.
2702 2706 if (full) {
2703 2707 // Update the number of full collections that have been completed.
2704 2708 increment_old_marking_cycles_completed(false /* concurrent */);
2705 2709 }
2706 2710
2707 2711 // We are at the end of the GC. Total collections has already been increased.
2708 2712 rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1);
2709 2713
2710 2714 // FIXME: what is this about?
2711 2715 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
2712 2716 // is set.
2713 2717 #if COMPILER2_OR_JVMCI
2714 2718 assert(DerivedPointerTable::is_empty(), "derived pointer present");
2715 2719 #endif
2716 2720
2717 2721 double start = os::elapsedTime();
2718 2722 resize_all_tlabs();
2719 2723 phase_times()->record_resize_tlab_time_ms((os::elapsedTime() - start) * 1000.0);
2720 2724
2721 2725 MemoryService::track_memory_usage();
2722 2726 // We have just completed a GC. Update the soft reference
2723 2727 // policy with the new heap occupancy
2724 2728 Universe::update_heap_info_at_gc();
2725 2729
2726 2730 // Print NUMA statistics.
2727 2731 _numa->print_statistics();
2728 2732 }
2729 2733
2730 2734 void G1CollectedHeap::verify_numa_regions(const char* desc) {
2731 2735 LogTarget(Trace, gc, heap, verify) lt;
2732 2736
2733 2737 if (lt.is_enabled()) {
2734 2738 LogStream ls(lt);
2735 2739 // Iterate all heap regions to print matching between preferred numa id and actual numa id.
2736 2740 G1NodeIndexCheckClosure cl(desc, _numa, &ls);
2737 2741 heap_region_iterate(&cl);
2738 2742 }
2739 2743 }
2740 2744
2741 2745 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
2742 2746 uint gc_count_before,
2743 2747 bool* succeeded,
2744 2748 GCCause::Cause gc_cause) {
2745 2749 assert_heap_not_locked_and_not_at_safepoint();
2746 2750 VM_G1CollectForAllocation op(word_size,
2747 2751 gc_count_before,
2748 2752 gc_cause,
2749 2753 policy()->max_pause_time_ms());
2750 2754 VMThread::execute(&op);
2751 2755
2752 2756 HeapWord* result = op.result();
2753 2757 bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded();
2754 2758 assert(result == NULL || ret_succeeded,
2755 2759 "the result should be NULL if the VM did not succeed");
2756 2760 *succeeded = ret_succeeded;
2757 2761
2758 2762 assert_heap_not_locked();
2759 2763 return result;
2760 2764 }
2761 2765
2762 2766 void G1CollectedHeap::do_concurrent_mark() {
2763 2767 MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag);
2764 2768 if (!_cm_thread->in_progress()) {
2765 2769 _cm_thread->set_started();
2766 2770 CGC_lock->notify();
2767 2771 }
2768 2772 }
2769 2773
2770 2774 size_t G1CollectedHeap::pending_card_num() {
2771 2775 struct CountCardsClosure : public ThreadClosure {
2772 2776 size_t _cards;
2773 2777 CountCardsClosure() : _cards(0) {}
2774 2778 virtual void do_thread(Thread* t) {
2775 2779 _cards += G1ThreadLocalData::dirty_card_queue(t).size();
2776 2780 }
2777 2781 } count_from_threads;
2778 2782 Threads::threads_do(&count_from_threads);
2779 2783
2780 2784 G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();
2781 2785 dcqs.verify_num_cards();
2782 2786
2783 2787 return dcqs.num_cards() + count_from_threads._cards;
2784 2788 }
2785 2789
2786 2790 bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const {
2787 2791 // We don't nominate objects with many remembered set entries, on
2788 2792 // the assumption that such objects are likely still live.
2789 2793 HeapRegionRemSet* rem_set = r->rem_set();
2790 2794
2791 2795 return G1EagerReclaimHumongousObjectsWithStaleRefs ?
2792 2796 rem_set->occupancy_less_or_equal_than(G1RSetSparseRegionEntries) :
2793 2797 G1EagerReclaimHumongousObjects && rem_set->is_empty();
2794 2798 }
2795 2799
2796 2800 #ifndef PRODUCT
2797 2801 void G1CollectedHeap::verify_region_attr_remset_update() {
2798 2802 class VerifyRegionAttrRemSet : public HeapRegionClosure {
2799 2803 public:
2800 2804 virtual bool do_heap_region(HeapRegion* r) {
2801 2805 G1CollectedHeap* g1h = G1CollectedHeap::heap();
2802 2806 bool const needs_remset_update = g1h->region_attr(r->bottom()).needs_remset_update();
2803 2807 assert(r->rem_set()->is_tracked() == needs_remset_update,
2804 2808 "Region %u remset tracking status (%s) different to region attribute (%s)",
2805 2809 r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(needs_remset_update));
2806 2810 return false;
2807 2811 }
2808 2812 } cl;
2809 2813 heap_region_iterate(&cl);
2810 2814 }
2811 2815 #endif
2812 2816
2813 2817 class VerifyRegionRemSetClosure : public HeapRegionClosure {
2814 2818 public:
2815 2819 bool do_heap_region(HeapRegion* hr) {
2816 2820 if (!hr->is_archive() && !hr->is_continues_humongous()) {
2817 2821 hr->verify_rem_set();
2818 2822 }
2819 2823 return false;
2820 2824 }
2821 2825 };
2822 2826
2823 2827 uint G1CollectedHeap::num_task_queues() const {
2824 2828 return _task_queues->size();
2825 2829 }
2826 2830
2827 2831 #if TASKQUEUE_STATS
2828 2832 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
2829 2833 st->print_raw_cr("GC Task Stats");
2830 2834 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
2831 2835 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
2832 2836 }
2833 2837
2834 2838 void G1CollectedHeap::print_taskqueue_stats() const {
2835 2839 if (!log_is_enabled(Trace, gc, task, stats)) {
2836 2840 return;
2837 2841 }
2838 2842 Log(gc, task, stats) log;
2839 2843 ResourceMark rm;
2840 2844 LogStream ls(log.trace());
2841 2845 outputStream* st = &ls;
2842 2846
2843 2847 print_taskqueue_stats_hdr(st);
2844 2848
2845 2849 TaskQueueStats totals;
2846 2850 const uint n = num_task_queues();
2847 2851 for (uint i = 0; i < n; ++i) {
2848 2852 st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr();
2849 2853 totals += task_queue(i)->stats;
2850 2854 }
2851 2855 st->print_raw("tot "); totals.print(st); st->cr();
2852 2856
2853 2857 DEBUG_ONLY(totals.verify());
2854 2858 }
2855 2859
2856 2860 void G1CollectedHeap::reset_taskqueue_stats() {
2857 2861 const uint n = num_task_queues();
2858 2862 for (uint i = 0; i < n; ++i) {
2859 2863 task_queue(i)->stats.reset();
2860 2864 }
2861 2865 }
2862 2866 #endif // TASKQUEUE_STATS
2863 2867
2864 2868 void G1CollectedHeap::wait_for_root_region_scanning() {
2865 2869 double scan_wait_start = os::elapsedTime();
2866 2870 // We have to wait until the CM threads finish scanning the
2867 2871 // root regions as it's the only way to ensure that all the
2868 2872 // objects on them have been correctly scanned before we start
2869 2873 // moving them during the GC.
2870 2874 bool waited = _cm->root_regions()->wait_until_scan_finished();
2871 2875 double wait_time_ms = 0.0;
2872 2876 if (waited) {
2873 2877 double scan_wait_end = os::elapsedTime();
2874 2878 wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
2875 2879 }
2876 2880 phase_times()->record_root_region_scan_wait_time(wait_time_ms);
2877 2881 }
2878 2882
2879 2883 class G1PrintCollectionSetClosure : public HeapRegionClosure {
2880 2884 private:
2881 2885 G1HRPrinter* _hr_printer;
2882 2886 public:
2883 2887 G1PrintCollectionSetClosure(G1HRPrinter* hr_printer) : HeapRegionClosure(), _hr_printer(hr_printer) { }
2884 2888
2885 2889 virtual bool do_heap_region(HeapRegion* r) {
2886 2890 _hr_printer->cset(r);
2887 2891 return false;
2888 2892 }
2889 2893 };
2890 2894
2891 2895 void G1CollectedHeap::start_new_collection_set() {
2892 2896 double start = os::elapsedTime();
2893 2897
2894 2898 collection_set()->start_incremental_building();
2895 2899
2896 2900 clear_region_attr();
2897 2901
2898 2902 guarantee(_eden.length() == 0, "eden should have been cleared");
2899 2903 policy()->transfer_survivors_to_cset(survivor());
2900 2904
2901 2905 // We redo the verification but now wrt to the new CSet which
2902 2906 // has just got initialized after the previous CSet was freed.
2903 2907 _cm->verify_no_collection_set_oops();
2904 2908
2905 2909 phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
2906 2910 }
2907 2911
2908 2912 void G1CollectedHeap::calculate_collection_set(G1EvacuationInfo& evacuation_info, double target_pause_time_ms) {
2909 2913
2910 2914 _collection_set.finalize_initial_collection_set(target_pause_time_ms, &_survivor);
2911 2915 evacuation_info.set_collectionset_regions(collection_set()->region_length() +
2912 2916 collection_set()->optional_region_length());
2913 2917
2914 2918 _cm->verify_no_collection_set_oops();
2915 2919
2916 2920 if (_hr_printer.is_active()) {
2917 2921 G1PrintCollectionSetClosure cl(&_hr_printer);
2918 2922 _collection_set.iterate(&cl);
2919 2923 _collection_set.iterate_optional(&cl);
2920 2924 }
2921 2925 }
2922 2926
2923 2927 G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const {
2924 2928 if (collector_state()->in_initial_mark_gc()) {
2925 2929 return G1HeapVerifier::G1VerifyConcurrentStart;
2926 2930 } else if (collector_state()->in_young_only_phase()) {
2927 2931 return G1HeapVerifier::G1VerifyYoungNormal;
2928 2932 } else {
2929 2933 return G1HeapVerifier::G1VerifyMixed;
2930 2934 }
2931 2935 }
2932 2936
2933 2937 void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {
2934 2938 if (VerifyRememberedSets) {
2935 2939 log_info(gc, verify)("[Verifying RemSets before GC]");
2936 2940 VerifyRegionRemSetClosure v_cl;
2937 2941 heap_region_iterate(&v_cl);
2938 2942 }
2939 2943 _verifier->verify_before_gc(type);
2940 2944 _verifier->check_bitmaps("GC Start");
2941 2945 verify_numa_regions("GC Start");
2942 2946 }
2943 2947
2944 2948 void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {
↓ open down ↓ |
506 lines elided |
↑ open up ↑ |
2945 2949 if (VerifyRememberedSets) {
2946 2950 log_info(gc, verify)("[Verifying RemSets after GC]");
2947 2951 VerifyRegionRemSetClosure v_cl;
2948 2952 heap_region_iterate(&v_cl);
2949 2953 }
2950 2954 _verifier->verify_after_gc(type);
2951 2955 _verifier->check_bitmaps("GC End");
2952 2956 verify_numa_regions("GC End");
2953 2957 }
2954 2958
2955 -void G1CollectedHeap::expand_heap_after_young_collection(){
2956 - size_t expand_bytes = _heap_sizing_policy->expansion_amount();
2959 +void G1CollectedHeap::resize_heap_after_young_collection() {
2960 + Ticks start = Ticks::now();
2961 + if (!expand_heap_after_young_collection()) {
2962 + // If we don't attempt to expand heap, try if we need to shrink the heap
2963 + shrink_heap_after_young_collection();
2964 + }
2965 + phase_times()->record_resize_heap_time((Ticks::now() - start).seconds() * 1000.0);
2966 +}
2967 +
2968 +bool G1CollectedHeap::expand_heap_after_young_collection(){
2969 + size_t expand_bytes = _heap_sizing_policy->expansion_amount_after_young_collection();
2957 2970 if (expand_bytes > 0) {
2958 - // No need for an ergo logging here,
2959 - // expansion_amount() does this when it returns a value > 0.
2960 - double expand_ms;
2961 - if (!expand(expand_bytes, _workers, &expand_ms)) {
2971 + if (expand(expand_bytes, _workers, NULL)) {
2962 2972 // We failed to expand the heap. Cannot do anything about it.
2963 2973 }
2964 - phase_times()->record_expand_heap_time(expand_ms);
2974 + return true;
2975 + }
2976 + return false;
2977 +}
2978 +
2979 +void G1CollectedHeap::shrink_heap_after_young_collection() {
2980 + if (!collector_state()->finish_of_mixed_gc()) {
2981 + // Do the shrink only after finish of mixed gc
2982 + return;
2983 + }
2984 + size_t shrink_bytes = _heap_sizing_policy->shrink_amount_after_mixed_collections();
2985 + if (shrink_bytes > 0) {
2986 + shrink(shrink_bytes);
2987 + }
2988 +}
2989 +
2990 +void G1CollectedHeap::expand_heap_after_concurrent_mark() {
2991 + size_t expand_bytes = _heap_sizing_policy->expansion_amount_after_concurrent_mark();
2992 + if (expand_bytes > 0) {
2993 + expand(expand_bytes, _workers, NULL);
2965 2994 }
2966 2995 }
2967 2996
2968 2997 const char* G1CollectedHeap::young_gc_name() const {
2969 2998 if (collector_state()->in_initial_mark_gc()) {
2970 2999 return "Pause Young (Concurrent Start)";
2971 3000 } else if (collector_state()->in_young_only_phase()) {
2972 3001 if (collector_state()->in_young_gc_before_mixed()) {
2973 3002 return "Pause Young (Prepare Mixed)";
2974 3003 } else {
2975 3004 return "Pause Young (Normal)";
2976 3005 }
2977 3006 } else {
2978 3007 return "Pause Young (Mixed)";
2979 3008 }
2980 3009 }
2981 3010
2982 3011 bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
2983 3012 assert_at_safepoint_on_vm_thread();
2984 3013 guarantee(!is_gc_active(), "collection is not reentrant");
2985 3014
2986 3015 if (GCLocker::check_active_before_gc()) {
2987 3016 return false;
2988 3017 }
2989 3018
2990 3019 GCIdMark gc_id_mark;
2991 3020
2992 3021 SvcGCMarker sgcm(SvcGCMarker::MINOR);
2993 3022 ResourceMark rm;
2994 3023
2995 3024 policy()->note_gc_start();
2996 3025
2997 3026 _gc_timer_stw->register_gc_start();
2998 3027 _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
2999 3028
3000 3029 wait_for_root_region_scanning();
3001 3030
3002 3031 print_heap_before_gc();
3003 3032 print_heap_regions();
3004 3033 trace_heap_before_gc(_gc_tracer_stw);
3005 3034
3006 3035 _verifier->verify_region_sets_optional();
3007 3036 _verifier->verify_dirty_young_regions();
3008 3037
3009 3038 // We should not be doing initial mark unless the conc mark thread is running
3010 3039 if (!_cm_thread->should_terminate()) {
3011 3040 // This call will decide whether this pause is an initial-mark
3012 3041 // pause. If it is, in_initial_mark_gc() will return true
3013 3042 // for the duration of this pause.
3014 3043 policy()->decide_on_conc_mark_initiation();
3015 3044 }
3016 3045
3017 3046 // We do not allow initial-mark to be piggy-backed on a mixed GC.
3018 3047 assert(!collector_state()->in_initial_mark_gc() ||
3019 3048 collector_state()->in_young_only_phase(), "sanity");
3020 3049 // We also do not allow mixed GCs during marking.
3021 3050 assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
3022 3051
3023 3052 // Record whether this pause is an initial mark. When the current
3024 3053 // thread has completed its logging output and it's safe to signal
3025 3054 // the CM thread, the flag's value in the policy has been reset.
3026 3055 bool should_start_conc_mark = collector_state()->in_initial_mark_gc();
3027 3056 if (should_start_conc_mark) {
3028 3057 _cm->gc_tracer_cm()->set_gc_cause(gc_cause());
3029 3058 }
3030 3059
3031 3060 // Inner scope for scope based logging, timers, and stats collection
3032 3061 {
3033 3062 G1EvacuationInfo evacuation_info;
3034 3063
3035 3064 _gc_tracer_stw->report_yc_type(collector_state()->yc_type());
3036 3065
3037 3066 GCTraceCPUTime tcpu;
3038 3067
3039 3068 GCTraceTime(Info, gc) tm(young_gc_name(), NULL, gc_cause(), true);
3040 3069
3041 3070 uint active_workers = WorkerPolicy::calc_active_workers(workers()->total_workers(),
3042 3071 workers()->active_workers(),
3043 3072 Threads::number_of_non_daemon_threads());
3044 3073 active_workers = workers()->update_active_workers(active_workers);
3045 3074 log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
3046 3075
3047 3076 G1MonitoringScope ms(g1mm(),
3048 3077 false /* full_gc */,
3049 3078 collector_state()->yc_type() == Mixed /* all_memory_pools_affected */);
3050 3079
3051 3080 G1HeapTransition heap_transition(this);
3052 3081
3053 3082 {
3054 3083 IsGCActiveMark x;
3055 3084
3056 3085 gc_prologue(false);
3057 3086
3058 3087 G1HeapVerifier::G1VerifyType verify_type = young_collection_verify_type();
3059 3088 verify_before_young_collection(verify_type);
3060 3089
3061 3090 {
3062 3091 // The elapsed time induced by the start time below deliberately elides
3063 3092 // the possible verification above.
3064 3093 double sample_start_time_sec = os::elapsedTime();
3065 3094
3066 3095 // Please see comment in g1CollectedHeap.hpp and
3067 3096 // G1CollectedHeap::ref_processing_init() to see how
3068 3097 // reference processing currently works in G1.
3069 3098 _ref_processor_stw->enable_discovery();
3070 3099
3071 3100 // We want to temporarily turn off discovery by the
3072 3101 // CM ref processor, if necessary, and turn it back on
3073 3102 // on again later if we do. Using a scoped
3074 3103 // NoRefDiscovery object will do this.
3075 3104 NoRefDiscovery no_cm_discovery(_ref_processor_cm);
3076 3105
3077 3106 policy()->record_collection_pause_start(sample_start_time_sec);
3078 3107
3079 3108 // Forget the current allocation region (we might even choose it to be part
3080 3109 // of the collection set!).
3081 3110 _allocator->release_mutator_alloc_regions();
3082 3111
3083 3112 calculate_collection_set(evacuation_info, target_pause_time_ms);
3084 3113
3085 3114 G1RedirtyCardsQueueSet rdcqs(G1BarrierSet::dirty_card_queue_set().allocator());
3086 3115 G1ParScanThreadStateSet per_thread_states(this,
3087 3116 &rdcqs,
3088 3117 workers()->active_workers(),
3089 3118 collection_set()->young_region_length(),
3090 3119 collection_set()->optional_region_length());
3091 3120 pre_evacuate_collection_set(evacuation_info, &per_thread_states);
3092 3121
3093 3122 // Actually do the work...
3094 3123 evacuate_initial_collection_set(&per_thread_states);
3095 3124
3096 3125 if (_collection_set.optional_region_length() != 0) {
3097 3126 evacuate_optional_collection_set(&per_thread_states);
3098 3127 }
3099 3128 post_evacuate_collection_set(evacuation_info, &rdcqs, &per_thread_states);
3100 3129
3101 3130 start_new_collection_set();
3102 3131
3103 3132 _survivor_evac_stats.adjust_desired_plab_sz();
3104 3133 _old_evac_stats.adjust_desired_plab_sz();
3105 3134
3106 3135 if (should_start_conc_mark) {
3107 3136 // We have to do this before we notify the CM threads that
3108 3137 // they can start working to make sure that all the
3109 3138 // appropriate initialization is done on the CM object.
↓ open down ↓ |
135 lines elided |
↑ open up ↑ |
3110 3139 concurrent_mark()->post_initial_mark();
3111 3140 // Note that we don't actually trigger the CM thread at
3112 3141 // this point. We do that later when we're sure that
3113 3142 // the current thread has completed its logging output.
3114 3143 }
3115 3144
3116 3145 allocate_dummy_regions();
3117 3146
3118 3147 _allocator->init_mutator_alloc_regions();
3119 3148
3120 - expand_heap_after_young_collection();
3149 + resize_heap_after_young_collection();
3121 3150
3122 3151 double sample_end_time_sec = os::elapsedTime();
3123 3152 double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
3124 3153 policy()->record_collection_pause_end(pause_time_ms);
3125 3154 }
3126 3155
3127 3156 verify_after_young_collection(verify_type);
3128 3157
3129 3158 #ifdef TRACESPINNING
3130 3159 ParallelTaskTerminator::print_termination_counts();
3131 3160 #endif
3132 3161
3133 3162 gc_epilogue(false);
3134 3163 }
3135 3164
3136 3165 // Print the remainder of the GC log output.
3137 3166 if (evacuation_failed()) {
3138 3167 log_info(gc)("To-space exhausted");
3139 3168 }
3140 3169
3141 3170 policy()->print_phases();
3142 3171 heap_transition.print();
3143 3172
3144 3173 _hrm->verify_optional();
3145 3174 _verifier->verify_region_sets_optional();
3146 3175
3147 3176 TASKQUEUE_STATS_ONLY(print_taskqueue_stats());
3148 3177 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
3149 3178
3150 3179 print_heap_after_gc();
3151 3180 print_heap_regions();
3152 3181 trace_heap_after_gc(_gc_tracer_stw);
3153 3182
3154 3183 // We must call G1MonitoringSupport::update_sizes() in the same scoping level
3155 3184 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
3156 3185 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
3157 3186 // before any GC notifications are raised.
3158 3187 g1mm()->update_sizes();
3159 3188
3160 3189 _gc_tracer_stw->report_evacuation_info(&evacuation_info);
3161 3190 _gc_tracer_stw->report_tenuring_threshold(_policy->tenuring_threshold());
3162 3191 _gc_timer_stw->register_gc_end();
3163 3192 _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());
3164 3193 }
3165 3194 // It should now be safe to tell the concurrent mark thread to start
3166 3195 // without its logging output interfering with the logging output
3167 3196 // that came from the pause.
3168 3197
3169 3198 if (should_start_conc_mark) {
3170 3199 // CAUTION: after the doConcurrentMark() call below, the concurrent marking
3171 3200 // thread(s) could be running concurrently with us. Make sure that anything
3172 3201 // after this point does not assume that we are the only GC thread running.
3173 3202 // Note: of course, the actual marking work will not start until the safepoint
3174 3203 // itself is released in SuspendibleThreadSet::desynchronize().
3175 3204 do_concurrent_mark();
3176 3205 }
3177 3206
3178 3207 return true;
3179 3208 }
3180 3209
3181 3210 void G1CollectedHeap::remove_self_forwarding_pointers(G1RedirtyCardsQueueSet* rdcqs) {
3182 3211 G1ParRemoveSelfForwardPtrsTask rsfp_task(rdcqs);
3183 3212 workers()->run_task(&rsfp_task);
3184 3213 }
3185 3214
3186 3215 void G1CollectedHeap::restore_after_evac_failure(G1RedirtyCardsQueueSet* rdcqs) {
3187 3216 double remove_self_forwards_start = os::elapsedTime();
3188 3217
3189 3218 remove_self_forwarding_pointers(rdcqs);
3190 3219 _preserved_marks_set.restore(workers());
3191 3220
3192 3221 phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0);
3193 3222 }
3194 3223
3195 3224 void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markWord m) {
3196 3225 if (!_evacuation_failed) {
3197 3226 _evacuation_failed = true;
3198 3227 }
3199 3228
3200 3229 _evacuation_failed_info_array[worker_id].register_copy_failure(obj->size());
3201 3230 _preserved_marks_set.get(worker_id)->push_if_necessary(obj, m);
3202 3231 }
3203 3232
3204 3233 bool G1ParEvacuateFollowersClosure::offer_termination() {
3205 3234 EventGCPhaseParallel event;
3206 3235 G1ParScanThreadState* const pss = par_scan_state();
3207 3236 start_term_time();
3208 3237 const bool res = terminator()->offer_termination();
3209 3238 end_term_time();
3210 3239 event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));
3211 3240 return res;
3212 3241 }
3213 3242
3214 3243 void G1ParEvacuateFollowersClosure::do_void() {
3215 3244 EventGCPhaseParallel event;
3216 3245 G1ParScanThreadState* const pss = par_scan_state();
3217 3246 pss->trim_queue();
3218 3247 event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3219 3248 do {
3220 3249 EventGCPhaseParallel event;
3221 3250 pss->steal_and_trim_queue(queues());
3222 3251 event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3223 3252 } while (!offer_termination());
3224 3253 }
3225 3254
3226 3255 void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive,
3227 3256 bool class_unloading_occurred) {
3228 3257 uint num_workers = workers()->active_workers();
3229 3258 G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred, false);
3230 3259 workers()->run_task(&unlink_task);
3231 3260 }
3232 3261
3233 3262 // Clean string dedup data structures.
3234 3263 // Ideally we would prefer to use a StringDedupCleaningTask here, but we want to
3235 3264 // record the durations of the phases. Hence the almost-copy.
3236 3265 class G1StringDedupCleaningTask : public AbstractGangTask {
3237 3266 BoolObjectClosure* _is_alive;
3238 3267 OopClosure* _keep_alive;
3239 3268 G1GCPhaseTimes* _phase_times;
3240 3269
3241 3270 public:
3242 3271 G1StringDedupCleaningTask(BoolObjectClosure* is_alive,
3243 3272 OopClosure* keep_alive,
3244 3273 G1GCPhaseTimes* phase_times) :
3245 3274 AbstractGangTask("Partial Cleaning Task"),
3246 3275 _is_alive(is_alive),
3247 3276 _keep_alive(keep_alive),
3248 3277 _phase_times(phase_times)
3249 3278 {
3250 3279 assert(G1StringDedup::is_enabled(), "String deduplication disabled.");
3251 3280 StringDedup::gc_prologue(true);
3252 3281 }
3253 3282
3254 3283 ~G1StringDedupCleaningTask() {
3255 3284 StringDedup::gc_epilogue();
3256 3285 }
3257 3286
3258 3287 void work(uint worker_id) {
3259 3288 StringDedupUnlinkOrOopsDoClosure cl(_is_alive, _keep_alive);
3260 3289 {
3261 3290 G1GCParPhaseTimesTracker x(_phase_times, G1GCPhaseTimes::StringDedupQueueFixup, worker_id);
3262 3291 StringDedupQueue::unlink_or_oops_do(&cl);
3263 3292 }
3264 3293 {
3265 3294 G1GCParPhaseTimesTracker x(_phase_times, G1GCPhaseTimes::StringDedupTableFixup, worker_id);
3266 3295 StringDedupTable::unlink_or_oops_do(&cl, worker_id);
3267 3296 }
3268 3297 }
3269 3298 };
3270 3299
3271 3300 void G1CollectedHeap::string_dedup_cleaning(BoolObjectClosure* is_alive,
3272 3301 OopClosure* keep_alive,
3273 3302 G1GCPhaseTimes* phase_times) {
3274 3303 G1StringDedupCleaningTask cl(is_alive, keep_alive, phase_times);
3275 3304 workers()->run_task(&cl);
3276 3305 }
3277 3306
3278 3307 class G1RedirtyLoggedCardsTask : public AbstractGangTask {
3279 3308 private:
3280 3309 G1RedirtyCardsQueueSet* _qset;
3281 3310 G1CollectedHeap* _g1h;
3282 3311 BufferNode* volatile _nodes;
3283 3312
3284 3313 void par_apply(RedirtyLoggedCardTableEntryClosure* cl, uint worker_id) {
3285 3314 size_t buffer_size = _qset->buffer_size();
3286 3315 BufferNode* next = Atomic::load(&_nodes);
3287 3316 while (next != NULL) {
3288 3317 BufferNode* node = next;
3289 3318 next = Atomic::cmpxchg(&_nodes, node, node->next());
3290 3319 if (next == node) {
3291 3320 cl->apply_to_buffer(node, buffer_size, worker_id);
3292 3321 next = node->next();
3293 3322 }
3294 3323 }
3295 3324 }
3296 3325
3297 3326 public:
3298 3327 G1RedirtyLoggedCardsTask(G1RedirtyCardsQueueSet* qset, G1CollectedHeap* g1h) :
3299 3328 AbstractGangTask("Redirty Cards"),
3300 3329 _qset(qset), _g1h(g1h), _nodes(qset->all_completed_buffers()) { }
3301 3330
3302 3331 virtual void work(uint worker_id) {
3303 3332 G1GCPhaseTimes* p = _g1h->phase_times();
3304 3333 G1GCParPhaseTimesTracker x(p, G1GCPhaseTimes::RedirtyCards, worker_id);
3305 3334
3306 3335 RedirtyLoggedCardTableEntryClosure cl(_g1h);
3307 3336 par_apply(&cl, worker_id);
3308 3337
3309 3338 p->record_thread_work_item(G1GCPhaseTimes::RedirtyCards, worker_id, cl.num_dirtied());
3310 3339 }
3311 3340 };
3312 3341
3313 3342 void G1CollectedHeap::redirty_logged_cards(G1RedirtyCardsQueueSet* rdcqs) {
3314 3343 double redirty_logged_cards_start = os::elapsedTime();
3315 3344
3316 3345 G1RedirtyLoggedCardsTask redirty_task(rdcqs, this);
3317 3346 workers()->run_task(&redirty_task);
3318 3347
3319 3348 G1DirtyCardQueueSet& dcq = G1BarrierSet::dirty_card_queue_set();
3320 3349 dcq.merge_bufferlists(rdcqs);
3321 3350
3322 3351 phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0);
3323 3352 }
3324 3353
3325 3354 // Weak Reference Processing support
3326 3355
3327 3356 bool G1STWIsAliveClosure::do_object_b(oop p) {
3328 3357 // An object is reachable if it is outside the collection set,
3329 3358 // or is inside and copied.
3330 3359 return !_g1h->is_in_cset(p) || p->is_forwarded();
3331 3360 }
3332 3361
3333 3362 bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {
3334 3363 assert(obj != NULL, "must not be NULL");
3335 3364 assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));
3336 3365 // The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below
3337 3366 // may falsely indicate that this is not the case here: however the collection set only
3338 3367 // contains old regions when concurrent mark is not running.
3339 3368 return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();
3340 3369 }
3341 3370
3342 3371 // Non Copying Keep Alive closure
3343 3372 class G1KeepAliveClosure: public OopClosure {
3344 3373 G1CollectedHeap*_g1h;
3345 3374 public:
3346 3375 G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}
3347 3376 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
3348 3377 void do_oop(oop* p) {
3349 3378 oop obj = *p;
3350 3379 assert(obj != NULL, "the caller should have filtered out NULL values");
3351 3380
3352 3381 const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);
3353 3382 if (!region_attr.is_in_cset_or_humongous()) {
3354 3383 return;
3355 3384 }
3356 3385 if (region_attr.is_in_cset()) {
3357 3386 assert( obj->is_forwarded(), "invariant" );
3358 3387 *p = obj->forwardee();
3359 3388 } else {
3360 3389 assert(!obj->is_forwarded(), "invariant" );
3361 3390 assert(region_attr.is_humongous(),
3362 3391 "Only allowed G1HeapRegionAttr state is IsHumongous, but is %d", region_attr.type());
3363 3392 _g1h->set_humongous_is_live(obj);
3364 3393 }
3365 3394 }
3366 3395 };
3367 3396
3368 3397 // Copying Keep Alive closure - can be called from both
3369 3398 // serial and parallel code as long as different worker
3370 3399 // threads utilize different G1ParScanThreadState instances
3371 3400 // and different queues.
3372 3401
3373 3402 class G1CopyingKeepAliveClosure: public OopClosure {
3374 3403 G1CollectedHeap* _g1h;
3375 3404 G1ParScanThreadState* _par_scan_state;
3376 3405
3377 3406 public:
3378 3407 G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
3379 3408 G1ParScanThreadState* pss):
3380 3409 _g1h(g1h),
3381 3410 _par_scan_state(pss)
3382 3411 {}
3383 3412
3384 3413 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3385 3414 virtual void do_oop( oop* p) { do_oop_work(p); }
3386 3415
3387 3416 template <class T> void do_oop_work(T* p) {
3388 3417 oop obj = RawAccess<>::oop_load(p);
3389 3418
3390 3419 if (_g1h->is_in_cset_or_humongous(obj)) {
3391 3420 // If the referent object has been forwarded (either copied
3392 3421 // to a new location or to itself in the event of an
3393 3422 // evacuation failure) then we need to update the reference
3394 3423 // field and, if both reference and referent are in the G1
3395 3424 // heap, update the RSet for the referent.
3396 3425 //
3397 3426 // If the referent has not been forwarded then we have to keep
3398 3427 // it alive by policy. Therefore we have copy the referent.
3399 3428 //
3400 3429 // When the queue is drained (after each phase of reference processing)
3401 3430 // the object and it's followers will be copied, the reference field set
3402 3431 // to point to the new location, and the RSet updated.
3403 3432 _par_scan_state->push_on_queue(p);
3404 3433 }
3405 3434 }
3406 3435 };
3407 3436
3408 3437 // Serial drain queue closure. Called as the 'complete_gc'
3409 3438 // closure for each discovered list in some of the
3410 3439 // reference processing phases.
3411 3440
3412 3441 class G1STWDrainQueueClosure: public VoidClosure {
3413 3442 protected:
3414 3443 G1CollectedHeap* _g1h;
3415 3444 G1ParScanThreadState* _par_scan_state;
3416 3445
3417 3446 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
3418 3447
3419 3448 public:
3420 3449 G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
3421 3450 _g1h(g1h),
3422 3451 _par_scan_state(pss)
3423 3452 { }
3424 3453
3425 3454 void do_void() {
3426 3455 G1ParScanThreadState* const pss = par_scan_state();
3427 3456 pss->trim_queue();
3428 3457 }
3429 3458 };
3430 3459
3431 3460 // Parallel Reference Processing closures
3432 3461
3433 3462 // Implementation of AbstractRefProcTaskExecutor for parallel reference
3434 3463 // processing during G1 evacuation pauses.
3435 3464
3436 3465 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
3437 3466 private:
3438 3467 G1CollectedHeap* _g1h;
3439 3468 G1ParScanThreadStateSet* _pss;
3440 3469 RefToScanQueueSet* _queues;
3441 3470 WorkGang* _workers;
3442 3471
3443 3472 public:
3444 3473 G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
3445 3474 G1ParScanThreadStateSet* per_thread_states,
3446 3475 WorkGang* workers,
3447 3476 RefToScanQueueSet *task_queues) :
3448 3477 _g1h(g1h),
3449 3478 _pss(per_thread_states),
3450 3479 _queues(task_queues),
3451 3480 _workers(workers)
3452 3481 {
3453 3482 g1h->ref_processor_stw()->set_active_mt_degree(workers->active_workers());
3454 3483 }
3455 3484
3456 3485 // Executes the given task using concurrent marking worker threads.
3457 3486 virtual void execute(ProcessTask& task, uint ergo_workers);
3458 3487 };
3459 3488
3460 3489 // Gang task for possibly parallel reference processing
3461 3490
3462 3491 class G1STWRefProcTaskProxy: public AbstractGangTask {
3463 3492 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
3464 3493 ProcessTask& _proc_task;
3465 3494 G1CollectedHeap* _g1h;
3466 3495 G1ParScanThreadStateSet* _pss;
3467 3496 RefToScanQueueSet* _task_queues;
3468 3497 ParallelTaskTerminator* _terminator;
3469 3498
3470 3499 public:
3471 3500 G1STWRefProcTaskProxy(ProcessTask& proc_task,
3472 3501 G1CollectedHeap* g1h,
3473 3502 G1ParScanThreadStateSet* per_thread_states,
3474 3503 RefToScanQueueSet *task_queues,
3475 3504 ParallelTaskTerminator* terminator) :
3476 3505 AbstractGangTask("Process reference objects in parallel"),
3477 3506 _proc_task(proc_task),
3478 3507 _g1h(g1h),
3479 3508 _pss(per_thread_states),
3480 3509 _task_queues(task_queues),
3481 3510 _terminator(terminator)
3482 3511 {}
3483 3512
3484 3513 virtual void work(uint worker_id) {
3485 3514 // The reference processing task executed by a single worker.
3486 3515 ResourceMark rm;
3487 3516 HandleMark hm;
3488 3517
3489 3518 G1STWIsAliveClosure is_alive(_g1h);
3490 3519
3491 3520 G1ParScanThreadState* pss = _pss->state_for_worker(worker_id);
3492 3521 pss->set_ref_discoverer(NULL);
3493 3522
3494 3523 // Keep alive closure.
3495 3524 G1CopyingKeepAliveClosure keep_alive(_g1h, pss);
3496 3525
3497 3526 // Complete GC closure
3498 3527 G1ParEvacuateFollowersClosure drain_queue(_g1h, pss, _task_queues, _terminator, G1GCPhaseTimes::ObjCopy);
3499 3528
3500 3529 // Call the reference processing task's work routine.
3501 3530 _proc_task.work(worker_id, is_alive, keep_alive, drain_queue);
3502 3531
3503 3532 // Note we cannot assert that the refs array is empty here as not all
3504 3533 // of the processing tasks (specifically phase2 - pp2_work) execute
3505 3534 // the complete_gc closure (which ordinarily would drain the queue) so
3506 3535 // the queue may not be empty.
3507 3536 }
3508 3537 };
3509 3538
3510 3539 // Driver routine for parallel reference processing.
3511 3540 // Creates an instance of the ref processing gang
3512 3541 // task and has the worker threads execute it.
3513 3542 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task, uint ergo_workers) {
3514 3543 assert(_workers != NULL, "Need parallel worker threads.");
3515 3544
3516 3545 assert(_workers->active_workers() >= ergo_workers,
3517 3546 "Ergonomically chosen workers (%u) should be less than or equal to active workers (%u)",
3518 3547 ergo_workers, _workers->active_workers());
3519 3548 TaskTerminator terminator(ergo_workers, _queues);
3520 3549 G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _pss, _queues, terminator.terminator());
3521 3550
3522 3551 _workers->run_task(&proc_task_proxy, ergo_workers);
3523 3552 }
3524 3553
3525 3554 // End of weak reference support closures
3526 3555
3527 3556 void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {
3528 3557 double ref_proc_start = os::elapsedTime();
3529 3558
3530 3559 ReferenceProcessor* rp = _ref_processor_stw;
3531 3560 assert(rp->discovery_enabled(), "should have been enabled");
3532 3561
3533 3562 // Closure to test whether a referent is alive.
3534 3563 G1STWIsAliveClosure is_alive(this);
3535 3564
3536 3565 // Even when parallel reference processing is enabled, the processing
3537 3566 // of JNI refs is serial and performed serially by the current thread
3538 3567 // rather than by a worker. The following PSS will be used for processing
3539 3568 // JNI refs.
3540 3569
3541 3570 // Use only a single queue for this PSS.
3542 3571 G1ParScanThreadState* pss = per_thread_states->state_for_worker(0);
3543 3572 pss->set_ref_discoverer(NULL);
3544 3573 assert(pss->queue_is_empty(), "pre-condition");
3545 3574
3546 3575 // Keep alive closure.
3547 3576 G1CopyingKeepAliveClosure keep_alive(this, pss);
3548 3577
3549 3578 // Serial Complete GC closure
3550 3579 G1STWDrainQueueClosure drain_queue(this, pss);
3551 3580
3552 3581 // Setup the soft refs policy...
3553 3582 rp->setup_policy(false);
3554 3583
3555 3584 ReferenceProcessorPhaseTimes* pt = phase_times()->ref_phase_times();
3556 3585
3557 3586 ReferenceProcessorStats stats;
3558 3587 if (!rp->processing_is_mt()) {
3559 3588 // Serial reference processing...
3560 3589 stats = rp->process_discovered_references(&is_alive,
3561 3590 &keep_alive,
3562 3591 &drain_queue,
3563 3592 NULL,
3564 3593 pt);
3565 3594 } else {
3566 3595 uint no_of_gc_workers = workers()->active_workers();
3567 3596
3568 3597 // Parallel reference processing
3569 3598 assert(no_of_gc_workers <= rp->max_num_queues(),
3570 3599 "Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u",
3571 3600 no_of_gc_workers, rp->max_num_queues());
3572 3601
3573 3602 G1STWRefProcTaskExecutor par_task_executor(this, per_thread_states, workers(), _task_queues);
3574 3603 stats = rp->process_discovered_references(&is_alive,
3575 3604 &keep_alive,
3576 3605 &drain_queue,
3577 3606 &par_task_executor,
3578 3607 pt);
3579 3608 }
3580 3609
3581 3610 _gc_tracer_stw->report_gc_reference_stats(stats);
3582 3611
3583 3612 // We have completed copying any necessary live referent objects.
3584 3613 assert(pss->queue_is_empty(), "both queue and overflow should be empty");
3585 3614
3586 3615 make_pending_list_reachable();
3587 3616
3588 3617 assert(!rp->discovery_enabled(), "Postcondition");
3589 3618 rp->verify_no_references_recorded();
3590 3619
3591 3620 double ref_proc_time = os::elapsedTime() - ref_proc_start;
3592 3621 phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
3593 3622 }
3594 3623
3595 3624 void G1CollectedHeap::make_pending_list_reachable() {
3596 3625 if (collector_state()->in_initial_mark_gc()) {
3597 3626 oop pll_head = Universe::reference_pending_list();
3598 3627 if (pll_head != NULL) {
3599 3628 // Any valid worker id is fine here as we are in the VM thread and single-threaded.
3600 3629 _cm->mark_in_next_bitmap(0 /* worker_id */, pll_head);
3601 3630 }
3602 3631 }
3603 3632 }
3604 3633
3605 3634 void G1CollectedHeap::merge_per_thread_state_info(G1ParScanThreadStateSet* per_thread_states) {
3606 3635 Ticks start = Ticks::now();
3607 3636 per_thread_states->flush();
3608 3637 phase_times()->record_or_add_time_secs(G1GCPhaseTimes::MergePSS, 0 /* worker_id */, (Ticks::now() - start).seconds());
3609 3638 }
3610 3639
3611 3640 class G1PrepareEvacuationTask : public AbstractGangTask {
3612 3641 class G1PrepareRegionsClosure : public HeapRegionClosure {
3613 3642 G1CollectedHeap* _g1h;
3614 3643 G1PrepareEvacuationTask* _parent_task;
3615 3644 size_t _worker_humongous_total;
3616 3645 size_t _worker_humongous_candidates;
3617 3646
3618 3647 bool humongous_region_is_candidate(HeapRegion* region) const {
3619 3648 assert(region->is_starts_humongous(), "Must start a humongous object");
3620 3649
3621 3650 oop obj = oop(region->bottom());
3622 3651
3623 3652 // Dead objects cannot be eager reclaim candidates. Due to class
3624 3653 // unloading it is unsafe to query their classes so we return early.
3625 3654 if (_g1h->is_obj_dead(obj, region)) {
3626 3655 return false;
3627 3656 }
3628 3657
3629 3658 // If we do not have a complete remembered set for the region, then we can
3630 3659 // not be sure that we have all references to it.
3631 3660 if (!region->rem_set()->is_complete()) {
3632 3661 return false;
3633 3662 }
3634 3663 // Candidate selection must satisfy the following constraints
3635 3664 // while concurrent marking is in progress:
3636 3665 //
3637 3666 // * In order to maintain SATB invariants, an object must not be
3638 3667 // reclaimed if it was allocated before the start of marking and
3639 3668 // has not had its references scanned. Such an object must have
3640 3669 // its references (including type metadata) scanned to ensure no
3641 3670 // live objects are missed by the marking process. Objects
3642 3671 // allocated after the start of concurrent marking don't need to
3643 3672 // be scanned.
3644 3673 //
3645 3674 // * An object must not be reclaimed if it is on the concurrent
3646 3675 // mark stack. Objects allocated after the start of concurrent
3647 3676 // marking are never pushed on the mark stack.
3648 3677 //
3649 3678 // Nominating only objects allocated after the start of concurrent
3650 3679 // marking is sufficient to meet both constraints. This may miss
3651 3680 // some objects that satisfy the constraints, but the marking data
3652 3681 // structures don't support efficiently performing the needed
3653 3682 // additional tests or scrubbing of the mark stack.
3654 3683 //
3655 3684 // However, we presently only nominate is_typeArray() objects.
3656 3685 // A humongous object containing references induces remembered
3657 3686 // set entries on other regions. In order to reclaim such an
3658 3687 // object, those remembered sets would need to be cleaned up.
3659 3688 //
3660 3689 // We also treat is_typeArray() objects specially, allowing them
3661 3690 // to be reclaimed even if allocated before the start of
3662 3691 // concurrent mark. For this we rely on mark stack insertion to
3663 3692 // exclude is_typeArray() objects, preventing reclaiming an object
3664 3693 // that is in the mark stack. We also rely on the metadata for
3665 3694 // such objects to be built-in and so ensured to be kept live.
3666 3695 // Frequent allocation and drop of large binary blobs is an
3667 3696 // important use case for eager reclaim, and this special handling
3668 3697 // may reduce needed headroom.
3669 3698
3670 3699 return obj->is_typeArray() &&
3671 3700 _g1h->is_potential_eager_reclaim_candidate(region);
3672 3701 }
3673 3702
3674 3703 public:
3675 3704 G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :
3676 3705 _g1h(g1h),
3677 3706 _parent_task(parent_task),
3678 3707 _worker_humongous_total(0),
3679 3708 _worker_humongous_candidates(0) { }
3680 3709
3681 3710 ~G1PrepareRegionsClosure() {
3682 3711 _parent_task->add_humongous_candidates(_worker_humongous_candidates);
3683 3712 _parent_task->add_humongous_total(_worker_humongous_total);
3684 3713 }
3685 3714
3686 3715 virtual bool do_heap_region(HeapRegion* hr) {
3687 3716 // First prepare the region for scanning
3688 3717 _g1h->rem_set()->prepare_region_for_scan(hr);
3689 3718
3690 3719 // Now check if region is a humongous candidate
3691 3720 if (!hr->is_starts_humongous()) {
3692 3721 _g1h->register_region_with_region_attr(hr);
3693 3722 return false;
3694 3723 }
3695 3724
3696 3725 uint index = hr->hrm_index();
3697 3726 if (humongous_region_is_candidate(hr)) {
3698 3727 _g1h->set_humongous_reclaim_candidate(index, true);
3699 3728 _g1h->register_humongous_region_with_region_attr(index);
3700 3729 _worker_humongous_candidates++;
3701 3730 // We will later handle the remembered sets of these regions.
3702 3731 } else {
3703 3732 _g1h->set_humongous_reclaim_candidate(index, false);
3704 3733 _g1h->register_region_with_region_attr(hr);
3705 3734 }
3706 3735 _worker_humongous_total++;
3707 3736
3708 3737 return false;
3709 3738 }
3710 3739 };
3711 3740
3712 3741 G1CollectedHeap* _g1h;
3713 3742 HeapRegionClaimer _claimer;
3714 3743 volatile size_t _humongous_total;
3715 3744 volatile size_t _humongous_candidates;
3716 3745 public:
3717 3746 G1PrepareEvacuationTask(G1CollectedHeap* g1h) :
3718 3747 AbstractGangTask("Prepare Evacuation"),
3719 3748 _g1h(g1h),
3720 3749 _claimer(_g1h->workers()->active_workers()),
3721 3750 _humongous_total(0),
3722 3751 _humongous_candidates(0) { }
3723 3752
3724 3753 ~G1PrepareEvacuationTask() {
3725 3754 _g1h->set_has_humongous_reclaim_candidate(_humongous_candidates > 0);
3726 3755 }
3727 3756
3728 3757 void work(uint worker_id) {
3729 3758 G1PrepareRegionsClosure cl(_g1h, this);
3730 3759 _g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);
3731 3760 }
3732 3761
3733 3762 void add_humongous_candidates(size_t candidates) {
3734 3763 Atomic::add(&_humongous_candidates, candidates);
3735 3764 }
3736 3765
3737 3766 void add_humongous_total(size_t total) {
3738 3767 Atomic::add(&_humongous_total, total);
3739 3768 }
3740 3769
3741 3770 size_t humongous_candidates() {
3742 3771 return _humongous_candidates;
3743 3772 }
3744 3773
3745 3774 size_t humongous_total() {
3746 3775 return _humongous_total;
3747 3776 }
3748 3777 };
3749 3778
3750 3779 void G1CollectedHeap::pre_evacuate_collection_set(G1EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) {
3751 3780 _bytes_used_during_gc = 0;
3752 3781
3753 3782 _expand_heap_after_alloc_failure = true;
3754 3783 _evacuation_failed = false;
3755 3784
3756 3785 // Disable the hot card cache.
3757 3786 _hot_card_cache->reset_hot_cache_claimed_index();
3758 3787 _hot_card_cache->set_use_cache(false);
3759 3788
3760 3789 // Initialize the GC alloc regions.
3761 3790 _allocator->init_gc_alloc_regions(evacuation_info);
3762 3791
3763 3792 {
3764 3793 Ticks start = Ticks::now();
3765 3794 rem_set()->prepare_for_scan_heap_roots();
3766 3795 phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);
3767 3796 }
3768 3797
3769 3798 {
3770 3799 G1PrepareEvacuationTask g1_prep_task(this);
3771 3800 Tickspan task_time = run_task(&g1_prep_task);
3772 3801
3773 3802 phase_times()->record_register_regions(task_time.seconds() * 1000.0,
3774 3803 g1_prep_task.humongous_total(),
3775 3804 g1_prep_task.humongous_candidates());
3776 3805 }
3777 3806
3778 3807 assert(_verifier->check_region_attr_table(), "Inconsistency in the region attributes table.");
3779 3808 _preserved_marks_set.assert_empty();
3780 3809
3781 3810 #if COMPILER2_OR_JVMCI
3782 3811 DerivedPointerTable::clear();
3783 3812 #endif
3784 3813
3785 3814 // InitialMark needs claim bits to keep track of the marked-through CLDs.
3786 3815 if (collector_state()->in_initial_mark_gc()) {
3787 3816 concurrent_mark()->pre_initial_mark();
3788 3817
3789 3818 double start_clear_claimed_marks = os::elapsedTime();
3790 3819
3791 3820 ClassLoaderDataGraph::clear_claimed_marks();
3792 3821
3793 3822 double recorded_clear_claimed_marks_time_ms = (os::elapsedTime() - start_clear_claimed_marks) * 1000.0;
3794 3823 phase_times()->record_clear_claimed_marks_time_ms(recorded_clear_claimed_marks_time_ms);
3795 3824 }
3796 3825
3797 3826 // Should G1EvacuationFailureALot be in effect for this GC?
3798 3827 NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
3799 3828 }
3800 3829
3801 3830 class G1EvacuateRegionsBaseTask : public AbstractGangTask {
3802 3831 protected:
3803 3832 G1CollectedHeap* _g1h;
3804 3833 G1ParScanThreadStateSet* _per_thread_states;
3805 3834 RefToScanQueueSet* _task_queues;
3806 3835 TaskTerminator _terminator;
3807 3836 uint _num_workers;
3808 3837
3809 3838 void evacuate_live_objects(G1ParScanThreadState* pss,
3810 3839 uint worker_id,
3811 3840 G1GCPhaseTimes::GCParPhases objcopy_phase,
3812 3841 G1GCPhaseTimes::GCParPhases termination_phase) {
3813 3842 G1GCPhaseTimes* p = _g1h->phase_times();
3814 3843
3815 3844 Ticks start = Ticks::now();
3816 3845 G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, _terminator.terminator(), objcopy_phase);
3817 3846 cl.do_void();
3818 3847
3819 3848 assert(pss->queue_is_empty(), "should be empty");
3820 3849
3821 3850 Tickspan evac_time = (Ticks::now() - start);
3822 3851 p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());
3823 3852
3824 3853 if (termination_phase == G1GCPhaseTimes::Termination) {
3825 3854 p->record_time_secs(termination_phase, worker_id, cl.term_time());
3826 3855 p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3827 3856 } else {
3828 3857 p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());
3829 3858 p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3830 3859 }
3831 3860 assert(pss->trim_ticks().seconds() == 0.0, "Unexpected partial trimming during evacuation");
3832 3861 }
3833 3862
3834 3863 virtual void start_work(uint worker_id) { }
3835 3864
3836 3865 virtual void end_work(uint worker_id) { }
3837 3866
3838 3867 virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;
3839 3868
3840 3869 virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;
3841 3870
3842 3871 public:
3843 3872 G1EvacuateRegionsBaseTask(const char* name, G1ParScanThreadStateSet* per_thread_states, RefToScanQueueSet* task_queues, uint num_workers) :
3844 3873 AbstractGangTask(name),
3845 3874 _g1h(G1CollectedHeap::heap()),
3846 3875 _per_thread_states(per_thread_states),
3847 3876 _task_queues(task_queues),
3848 3877 _terminator(num_workers, _task_queues),
3849 3878 _num_workers(num_workers)
3850 3879 { }
3851 3880
3852 3881 void work(uint worker_id) {
3853 3882 start_work(worker_id);
3854 3883
3855 3884 {
3856 3885 ResourceMark rm;
3857 3886 HandleMark hm;
3858 3887
3859 3888 G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);
3860 3889 pss->set_ref_discoverer(_g1h->ref_processor_stw());
3861 3890
3862 3891 scan_roots(pss, worker_id);
3863 3892 evacuate_live_objects(pss, worker_id);
3864 3893 }
3865 3894
3866 3895 end_work(worker_id);
3867 3896 }
3868 3897 };
3869 3898
3870 3899 class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {
3871 3900 G1RootProcessor* _root_processor;
3872 3901
3873 3902 void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3874 3903 _root_processor->evacuate_roots(pss, worker_id);
3875 3904 _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy);
3876 3905 _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);
3877 3906 }
3878 3907
3879 3908 void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3880 3909 G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);
3881 3910 }
3882 3911
3883 3912 void start_work(uint worker_id) {
3884 3913 _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());
3885 3914 }
3886 3915
3887 3916 void end_work(uint worker_id) {
3888 3917 _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());
3889 3918 }
3890 3919
3891 3920 public:
3892 3921 G1EvacuateRegionsTask(G1CollectedHeap* g1h,
3893 3922 G1ParScanThreadStateSet* per_thread_states,
3894 3923 RefToScanQueueSet* task_queues,
3895 3924 G1RootProcessor* root_processor,
3896 3925 uint num_workers) :
3897 3926 G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),
3898 3927 _root_processor(root_processor)
3899 3928 { }
3900 3929 };
3901 3930
3902 3931 void G1CollectedHeap::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states) {
3903 3932 G1GCPhaseTimes* p = phase_times();
3904 3933
3905 3934 {
3906 3935 Ticks start = Ticks::now();
3907 3936 rem_set()->merge_heap_roots(true /* initial_evacuation */);
3908 3937 p->record_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3909 3938 }
3910 3939
3911 3940 Tickspan task_time;
3912 3941 const uint num_workers = workers()->active_workers();
3913 3942
3914 3943 Ticks start_processing = Ticks::now();
3915 3944 {
3916 3945 G1RootProcessor root_processor(this, num_workers);
3917 3946 G1EvacuateRegionsTask g1_par_task(this, per_thread_states, _task_queues, &root_processor, num_workers);
3918 3947 task_time = run_task(&g1_par_task);
3919 3948 // Closing the inner scope will execute the destructor for the G1RootProcessor object.
3920 3949 // To extract its code root fixup time we measure total time of this scope and
3921 3950 // subtract from the time the WorkGang task took.
3922 3951 }
3923 3952 Tickspan total_processing = Ticks::now() - start_processing;
3924 3953
3925 3954 p->record_initial_evac_time(task_time.seconds() * 1000.0);
3926 3955 p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3927 3956 }
3928 3957
3929 3958 class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {
3930 3959
3931 3960 void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3932 3961 _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy);
3933 3962 _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);
3934 3963 }
3935 3964
3936 3965 void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3937 3966 G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);
3938 3967 }
3939 3968
3940 3969 public:
3941 3970 G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,
3942 3971 RefToScanQueueSet* queues,
3943 3972 uint num_workers) :
3944 3973 G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {
3945 3974 }
3946 3975 };
3947 3976
3948 3977 void G1CollectedHeap::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {
3949 3978 class G1MarkScope : public MarkScope { };
3950 3979
3951 3980 Tickspan task_time;
3952 3981
3953 3982 Ticks start_processing = Ticks::now();
3954 3983 {
3955 3984 G1MarkScope code_mark_scope;
3956 3985 G1EvacuateOptionalRegionsTask task(per_thread_states, _task_queues, workers()->active_workers());
3957 3986 task_time = run_task(&task);
3958 3987 // See comment in evacuate_collection_set() for the reason of the scope.
3959 3988 }
3960 3989 Tickspan total_processing = Ticks::now() - start_processing;
3961 3990
3962 3991 G1GCPhaseTimes* p = phase_times();
3963 3992 p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3964 3993 }
3965 3994
3966 3995 void G1CollectedHeap::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {
3967 3996 const double gc_start_time_ms = phase_times()->cur_collection_start_sec() * 1000.0;
3968 3997
3969 3998 while (!evacuation_failed() && _collection_set.optional_region_length() > 0) {
3970 3999
3971 4000 double time_used_ms = os::elapsedTime() * 1000.0 - gc_start_time_ms;
3972 4001 double time_left_ms = MaxGCPauseMillis - time_used_ms;
3973 4002
3974 4003 if (time_left_ms < 0 ||
3975 4004 !_collection_set.finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {
3976 4005 log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",
3977 4006 _collection_set.optional_region_length(), time_left_ms);
3978 4007 break;
3979 4008 }
3980 4009
3981 4010 {
3982 4011 Ticks start = Ticks::now();
3983 4012 rem_set()->merge_heap_roots(false /* initial_evacuation */);
3984 4013 phase_times()->record_or_add_optional_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3985 4014 }
3986 4015
3987 4016 {
3988 4017 Ticks start = Ticks::now();
3989 4018 evacuate_next_optional_regions(per_thread_states);
3990 4019 phase_times()->record_or_add_optional_evac_time((Ticks::now() - start).seconds() * 1000.0);
3991 4020 }
3992 4021 }
3993 4022
3994 4023 _collection_set.abandon_optional_collection_set(per_thread_states);
3995 4024 }
3996 4025
3997 4026 void G1CollectedHeap::post_evacuate_collection_set(G1EvacuationInfo& evacuation_info,
3998 4027 G1RedirtyCardsQueueSet* rdcqs,
3999 4028 G1ParScanThreadStateSet* per_thread_states) {
4000 4029 G1GCPhaseTimes* p = phase_times();
4001 4030
4002 4031 rem_set()->cleanup_after_scan_heap_roots();
4003 4032
4004 4033 // Process any discovered reference objects - we have
4005 4034 // to do this _before_ we retire the GC alloc regions
4006 4035 // as we may have to copy some 'reachable' referent
4007 4036 // objects (and their reachable sub-graphs) that were
4008 4037 // not copied during the pause.
4009 4038 process_discovered_references(per_thread_states);
4010 4039
4011 4040 G1STWIsAliveClosure is_alive(this);
4012 4041 G1KeepAliveClosure keep_alive(this);
4013 4042
4014 4043 WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());
4015 4044
4016 4045 if (G1StringDedup::is_enabled()) {
4017 4046 double string_dedup_time_ms = os::elapsedTime();
4018 4047
4019 4048 string_dedup_cleaning(&is_alive, &keep_alive, p);
4020 4049
4021 4050 double string_cleanup_time_ms = (os::elapsedTime() - string_dedup_time_ms) * 1000.0;
4022 4051 p->record_string_deduplication_time(string_cleanup_time_ms);
4023 4052 }
4024 4053
4025 4054 _allocator->release_gc_alloc_regions(evacuation_info);
4026 4055
4027 4056 if (evacuation_failed()) {
4028 4057 restore_after_evac_failure(rdcqs);
4029 4058
4030 4059 // Reset the G1EvacuationFailureALot counters and flags
4031 4060 NOT_PRODUCT(reset_evacuation_should_fail();)
4032 4061
4033 4062 double recalculate_used_start = os::elapsedTime();
4034 4063 set_used(recalculate_used());
4035 4064 p->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0);
4036 4065
4037 4066 if (_archive_allocator != NULL) {
4038 4067 _archive_allocator->clear_used();
4039 4068 }
4040 4069 for (uint i = 0; i < ParallelGCThreads; i++) {
4041 4070 if (_evacuation_failed_info_array[i].has_failed()) {
4042 4071 _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4043 4072 }
4044 4073 }
4045 4074 } else {
4046 4075 // The "used" of the the collection set have already been subtracted
4047 4076 // when they were freed. Add in the bytes used.
4048 4077 increase_used(_bytes_used_during_gc);
4049 4078 }
4050 4079
4051 4080 _preserved_marks_set.assert_empty();
4052 4081
4053 4082 merge_per_thread_state_info(per_thread_states);
4054 4083
4055 4084 // Reset and re-enable the hot card cache.
4056 4085 // Note the counts for the cards in the regions in the
4057 4086 // collection set are reset when the collection set is freed.
4058 4087 _hot_card_cache->reset_hot_cache();
4059 4088 _hot_card_cache->set_use_cache(true);
4060 4089
4061 4090 purge_code_root_memory();
4062 4091
4063 4092 redirty_logged_cards(rdcqs);
4064 4093
4065 4094 free_collection_set(&_collection_set, evacuation_info, per_thread_states->surviving_young_words());
4066 4095
4067 4096 eagerly_reclaim_humongous_regions();
4068 4097
4069 4098 record_obj_copy_mem_stats();
4070 4099
4071 4100 evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());
4072 4101 evacuation_info.set_bytes_used(_bytes_used_during_gc);
4073 4102
4074 4103 #if COMPILER2_OR_JVMCI
4075 4104 double start = os::elapsedTime();
4076 4105 DerivedPointerTable::update_pointers();
4077 4106 phase_times()->record_derived_pointer_table_update_time((os::elapsedTime() - start) * 1000.0);
4078 4107 #endif
4079 4108 policy()->print_age_table();
4080 4109 }
4081 4110
4082 4111 void G1CollectedHeap::record_obj_copy_mem_stats() {
4083 4112 policy()->add_bytes_allocated_in_old_since_last_gc(_old_evac_stats.allocated() * HeapWordSize);
4084 4113
4085 4114 _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),
4086 4115 create_g1_evac_summary(&_old_evac_stats));
4087 4116 }
4088 4117
4089 4118 void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) {
4090 4119 assert(!hr->is_free(), "the region should not be free");
4091 4120 assert(!hr->is_empty(), "the region should not be empty");
4092 4121 assert(_hrm->is_available(hr->hrm_index()), "region should be committed");
4093 4122
4094 4123 if (G1VerifyBitmaps) {
4095 4124 MemRegion mr(hr->bottom(), hr->end());
4096 4125 concurrent_mark()->clear_range_in_prev_bitmap(mr);
4097 4126 }
4098 4127
4099 4128 // Clear the card counts for this region.
4100 4129 // Note: we only need to do this if the region is not young
4101 4130 // (since we don't refine cards in young regions).
4102 4131 if (!hr->is_young()) {
4103 4132 _hot_card_cache->reset_card_counts(hr);
4104 4133 }
4105 4134
4106 4135 // Reset region metadata to allow reuse.
4107 4136 hr->hr_clear(true /* clear_space */);
4108 4137 _policy->remset_tracker()->update_at_free(hr);
4109 4138
4110 4139 if (free_list != NULL) {
4111 4140 free_list->add_ordered(hr);
4112 4141 }
4113 4142 }
4114 4143
4115 4144 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
4116 4145 FreeRegionList* free_list) {
4117 4146 assert(hr->is_humongous(), "this is only for humongous regions");
4118 4147 assert(free_list != NULL, "pre-condition");
4119 4148 hr->clear_humongous();
4120 4149 free_region(hr, free_list);
4121 4150 }
4122 4151
4123 4152 void G1CollectedHeap::remove_from_old_sets(const uint old_regions_removed,
4124 4153 const uint humongous_regions_removed) {
4125 4154 if (old_regions_removed > 0 || humongous_regions_removed > 0) {
4126 4155 MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);
4127 4156 _old_set.bulk_remove(old_regions_removed);
4128 4157 _humongous_set.bulk_remove(humongous_regions_removed);
4129 4158 }
4130 4159
4131 4160 }
4132 4161
4133 4162 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
4134 4163 assert(list != NULL, "list can't be null");
4135 4164 if (!list->is_empty()) {
4136 4165 MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag);
4137 4166 _hrm->insert_list_into_free_list(list);
4138 4167 }
4139 4168 }
4140 4169
4141 4170 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
4142 4171 decrease_used(bytes);
4143 4172 }
4144 4173
4145 4174 class G1FreeCollectionSetTask : public AbstractGangTask {
4146 4175 // Helper class to keep statistics for the collection set freeing
4147 4176 class FreeCSetStats {
4148 4177 size_t _before_used_bytes; // Usage in regions successfully evacutate
4149 4178 size_t _after_used_bytes; // Usage in regions failing evacuation
4150 4179 size_t _bytes_allocated_in_old_since_last_gc; // Size of young regions turned into old
4151 4180 size_t _failure_used_words; // Live size in failed regions
4152 4181 size_t _failure_waste_words; // Wasted size in failed regions
4153 4182 size_t _rs_length; // Remembered set size
4154 4183 uint _regions_freed; // Number of regions freed
4155 4184 public:
4156 4185 FreeCSetStats() :
4157 4186 _before_used_bytes(0),
4158 4187 _after_used_bytes(0),
4159 4188 _bytes_allocated_in_old_since_last_gc(0),
4160 4189 _failure_used_words(0),
4161 4190 _failure_waste_words(0),
4162 4191 _rs_length(0),
4163 4192 _regions_freed(0) { }
4164 4193
4165 4194 void merge_stats(FreeCSetStats* other) {
4166 4195 assert(other != NULL, "invariant");
4167 4196 _before_used_bytes += other->_before_used_bytes;
4168 4197 _after_used_bytes += other->_after_used_bytes;
4169 4198 _bytes_allocated_in_old_since_last_gc += other->_bytes_allocated_in_old_since_last_gc;
4170 4199 _failure_used_words += other->_failure_used_words;
4171 4200 _failure_waste_words += other->_failure_waste_words;
4172 4201 _rs_length += other->_rs_length;
4173 4202 _regions_freed += other->_regions_freed;
4174 4203 }
4175 4204
4176 4205 void report(G1CollectedHeap* g1h, G1EvacuationInfo* evacuation_info) {
4177 4206 evacuation_info->set_regions_freed(_regions_freed);
4178 4207 evacuation_info->increment_collectionset_used_after(_after_used_bytes);
4179 4208
4180 4209 g1h->decrement_summary_bytes(_before_used_bytes);
4181 4210 g1h->alloc_buffer_stats(G1HeapRegionAttr::Old)->add_failure_used_and_waste(_failure_used_words, _failure_waste_words);
4182 4211
4183 4212 G1Policy *policy = g1h->policy();
4184 4213 policy->add_bytes_allocated_in_old_since_last_gc(_bytes_allocated_in_old_since_last_gc);
4185 4214 policy->record_rs_length(_rs_length);
4186 4215 policy->cset_regions_freed();
4187 4216 }
4188 4217
4189 4218 void account_failed_region(HeapRegion* r) {
4190 4219 size_t used_words = r->marked_bytes() / HeapWordSize;
4191 4220 _failure_used_words += used_words;
4192 4221 _failure_waste_words += HeapRegion::GrainWords - used_words;
4193 4222 _after_used_bytes += r->used();
4194 4223
4195 4224 // When moving a young gen region to old gen, we "allocate" that whole
4196 4225 // region there. This is in addition to any already evacuated objects.
4197 4226 // Notify the policy about that. Old gen regions do not cause an
4198 4227 // additional allocation: both the objects still in the region and the
4199 4228 // ones already moved are accounted for elsewhere.
4200 4229 if (r->is_young()) {
4201 4230 _bytes_allocated_in_old_since_last_gc += HeapRegion::GrainBytes;
4202 4231 }
4203 4232 }
4204 4233
4205 4234 void account_evacuated_region(HeapRegion* r) {
4206 4235 _before_used_bytes += r->used();
4207 4236 _regions_freed += 1;
4208 4237 }
4209 4238
4210 4239 void account_rs_length(HeapRegion* r) {
4211 4240 _rs_length += r->rem_set()->occupied();
4212 4241 }
4213 4242 };
4214 4243
4215 4244 // Closure applied to all regions in the collection set.
4216 4245 class FreeCSetClosure : public HeapRegionClosure {
4217 4246 // Helper to send JFR events for regions.
4218 4247 class JFREventForRegion {
4219 4248 EventGCPhaseParallel _event;
4220 4249 public:
4221 4250 JFREventForRegion(HeapRegion* region, uint worker_id) : _event() {
4222 4251 _event.set_gcId(GCId::current());
4223 4252 _event.set_gcWorkerId(worker_id);
4224 4253 if (region->is_young()) {
4225 4254 _event.set_name(G1GCPhaseTimes::phase_name(G1GCPhaseTimes::YoungFreeCSet));
4226 4255 } else {
4227 4256 _event.set_name(G1GCPhaseTimes::phase_name(G1GCPhaseTimes::NonYoungFreeCSet));
4228 4257 }
4229 4258 }
4230 4259
4231 4260 ~JFREventForRegion() {
4232 4261 _event.commit();
4233 4262 }
4234 4263 };
4235 4264
4236 4265 // Helper to do timing for region work.
4237 4266 class TimerForRegion {
4238 4267 Tickspan& _time;
4239 4268 Ticks _start_time;
4240 4269 public:
4241 4270 TimerForRegion(Tickspan& time) : _time(time), _start_time(Ticks::now()) { }
4242 4271 ~TimerForRegion() {
4243 4272 _time += Ticks::now() - _start_time;
4244 4273 }
4245 4274 };
4246 4275
4247 4276 // FreeCSetClosure members
4248 4277 G1CollectedHeap* _g1h;
4249 4278 const size_t* _surviving_young_words;
4250 4279 uint _worker_id;
4251 4280 Tickspan _young_time;
4252 4281 Tickspan _non_young_time;
4253 4282 FreeCSetStats* _stats;
4254 4283
4255 4284 void assert_in_cset(HeapRegion* r) {
4256 4285 assert(r->young_index_in_cset() != 0 &&
4257 4286 (uint)r->young_index_in_cset() <= _g1h->collection_set()->young_region_length(),
4258 4287 "Young index %u is wrong for region %u of type %s with %u young regions",
4259 4288 r->young_index_in_cset(), r->hrm_index(), r->get_type_str(), _g1h->collection_set()->young_region_length());
4260 4289 }
4261 4290
4262 4291 void handle_evacuated_region(HeapRegion* r) {
4263 4292 assert(!r->is_empty(), "Region %u is an empty region in the collection set.", r->hrm_index());
4264 4293 stats()->account_evacuated_region(r);
4265 4294
4266 4295 // Free the region and and its remembered set.
4267 4296 _g1h->free_region(r, NULL);
4268 4297 }
4269 4298
4270 4299 void handle_failed_region(HeapRegion* r) {
4271 4300 // Do some allocation statistics accounting. Regions that failed evacuation
4272 4301 // are always made old, so there is no need to update anything in the young
4273 4302 // gen statistics, but we need to update old gen statistics.
4274 4303 stats()->account_failed_region(r);
4275 4304
4276 4305 // Update the region state due to the failed evacuation.
4277 4306 r->handle_evacuation_failure();
4278 4307
4279 4308 // Add region to old set, need to hold lock.
4280 4309 MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);
4281 4310 _g1h->old_set_add(r);
4282 4311 }
4283 4312
4284 4313 Tickspan& timer_for_region(HeapRegion* r) {
4285 4314 return r->is_young() ? _young_time : _non_young_time;
4286 4315 }
4287 4316
4288 4317 FreeCSetStats* stats() {
4289 4318 return _stats;
4290 4319 }
4291 4320 public:
4292 4321 FreeCSetClosure(const size_t* surviving_young_words,
4293 4322 uint worker_id,
4294 4323 FreeCSetStats* stats) :
4295 4324 HeapRegionClosure(),
4296 4325 _g1h(G1CollectedHeap::heap()),
4297 4326 _surviving_young_words(surviving_young_words),
4298 4327 _worker_id(worker_id),
4299 4328 _young_time(),
4300 4329 _non_young_time(),
4301 4330 _stats(stats) { }
4302 4331
4303 4332 virtual bool do_heap_region(HeapRegion* r) {
4304 4333 assert(r->in_collection_set(), "Invariant: %u missing from CSet", r->hrm_index());
4305 4334 JFREventForRegion event(r, _worker_id);
4306 4335 TimerForRegion timer(timer_for_region(r));
4307 4336
4308 4337 _g1h->clear_region_attr(r);
4309 4338 stats()->account_rs_length(r);
4310 4339
4311 4340 if (r->is_young()) {
4312 4341 assert_in_cset(r);
4313 4342 r->record_surv_words_in_group(_surviving_young_words[r->young_index_in_cset()]);
4314 4343 }
4315 4344
4316 4345 if (r->evacuation_failed()) {
4317 4346 handle_failed_region(r);
4318 4347 } else {
4319 4348 handle_evacuated_region(r);
4320 4349 }
4321 4350 assert(!_g1h->is_on_master_free_list(r), "sanity");
4322 4351
4323 4352 return false;
4324 4353 }
4325 4354
4326 4355 void report_timing(Tickspan parallel_time) {
4327 4356 G1GCPhaseTimes* pt = _g1h->phase_times();
4328 4357 pt->record_time_secs(G1GCPhaseTimes::ParFreeCSet, _worker_id, parallel_time.seconds());
4329 4358 if (_young_time.value() > 0) {
4330 4359 pt->record_time_secs(G1GCPhaseTimes::YoungFreeCSet, _worker_id, _young_time.seconds());
4331 4360 }
4332 4361 if (_non_young_time.value() > 0) {
4333 4362 pt->record_time_secs(G1GCPhaseTimes::NonYoungFreeCSet, _worker_id, _non_young_time.seconds());
4334 4363 }
4335 4364 }
4336 4365 };
4337 4366
4338 4367 // G1FreeCollectionSetTask members
4339 4368 G1CollectedHeap* _g1h;
4340 4369 G1EvacuationInfo* _evacuation_info;
4341 4370 FreeCSetStats* _worker_stats;
4342 4371 HeapRegionClaimer _claimer;
4343 4372 const size_t* _surviving_young_words;
4344 4373 uint _active_workers;
4345 4374
4346 4375 FreeCSetStats* worker_stats(uint worker) {
4347 4376 return &_worker_stats[worker];
4348 4377 }
4349 4378
4350 4379 void report_statistics() {
4351 4380 // Merge the accounting
4352 4381 FreeCSetStats total_stats;
4353 4382 for (uint worker = 0; worker < _active_workers; worker++) {
4354 4383 total_stats.merge_stats(worker_stats(worker));
4355 4384 }
4356 4385 total_stats.report(_g1h, _evacuation_info);
4357 4386 }
4358 4387
4359 4388 public:
4360 4389 G1FreeCollectionSetTask(G1EvacuationInfo* evacuation_info, const size_t* surviving_young_words, uint active_workers) :
4361 4390 AbstractGangTask("G1 Free Collection Set"),
4362 4391 _g1h(G1CollectedHeap::heap()),
4363 4392 _evacuation_info(evacuation_info),
4364 4393 _worker_stats(NEW_C_HEAP_ARRAY(FreeCSetStats, active_workers, mtGC)),
4365 4394 _claimer(active_workers),
4366 4395 _surviving_young_words(surviving_young_words),
4367 4396 _active_workers(active_workers) {
4368 4397 for (uint worker = 0; worker < active_workers; worker++) {
4369 4398 ::new (&_worker_stats[worker]) FreeCSetStats();
4370 4399 }
4371 4400 }
4372 4401
4373 4402 ~G1FreeCollectionSetTask() {
4374 4403 Ticks serial_time = Ticks::now();
4375 4404 report_statistics();
4376 4405 for (uint worker = 0; worker < _active_workers; worker++) {
4377 4406 _worker_stats[worker].~FreeCSetStats();
4378 4407 }
4379 4408 FREE_C_HEAP_ARRAY(FreeCSetStats, _worker_stats);
4380 4409 _g1h->phase_times()->record_serial_free_cset_time_ms((Ticks::now() - serial_time).seconds() * 1000.0);
4381 4410 }
4382 4411
4383 4412 virtual void work(uint worker_id) {
4384 4413 EventGCPhaseParallel event;
4385 4414 Ticks start = Ticks::now();
4386 4415 FreeCSetClosure cl(_surviving_young_words, worker_id, worker_stats(worker_id));
4387 4416 _g1h->collection_set_par_iterate_all(&cl, &_claimer, worker_id);
4388 4417
4389 4418 // Report the total parallel time along with some more detailed metrics.
4390 4419 cl.report_timing(Ticks::now() - start);
4391 4420 event.commit(GCId::current(), worker_id, G1GCPhaseTimes::phase_name(G1GCPhaseTimes::ParFreeCSet));
4392 4421 }
4393 4422 };
4394 4423
4395 4424 void G1CollectedHeap::free_collection_set(G1CollectionSet* collection_set, G1EvacuationInfo& evacuation_info, const size_t* surviving_young_words) {
4396 4425 _eden.clear();
4397 4426
4398 4427 // The free collections set is split up in two tasks, the first
4399 4428 // frees the collection set and records what regions are free,
4400 4429 // and the second one rebuilds the free list. This proved to be
4401 4430 // more efficient than adding a sorted list to another.
4402 4431
4403 4432 Ticks free_cset_start_time = Ticks::now();
4404 4433 {
4405 4434 uint const num_cs_regions = _collection_set.region_length();
4406 4435 uint const num_workers = clamp(num_cs_regions, 1u, workers()->active_workers());
4407 4436 G1FreeCollectionSetTask cl(&evacuation_info, surviving_young_words, num_workers);
4408 4437
4409 4438 log_debug(gc, ergo)("Running %s using %u workers for collection set length %u (%u)",
4410 4439 cl.name(), num_workers, num_cs_regions, num_regions());
4411 4440 workers()->run_task(&cl, num_workers);
4412 4441 }
4413 4442
4414 4443 Ticks free_cset_end_time = Ticks::now();
4415 4444 phase_times()->record_total_free_cset_time_ms((free_cset_end_time - free_cset_start_time).seconds() * 1000.0);
4416 4445
4417 4446 // Now rebuild the free region list.
4418 4447 hrm()->rebuild_free_list(workers());
4419 4448 phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - free_cset_end_time).seconds() * 1000.0);
4420 4449
4421 4450 collection_set->clear();
4422 4451 }
4423 4452
4424 4453 class G1FreeHumongousRegionClosure : public HeapRegionClosure {
4425 4454 private:
4426 4455 FreeRegionList* _free_region_list;
4427 4456 HeapRegionSet* _proxy_set;
4428 4457 uint _humongous_objects_reclaimed;
4429 4458 uint _humongous_regions_reclaimed;
4430 4459 size_t _freed_bytes;
4431 4460 public:
4432 4461
4433 4462 G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) :
4434 4463 _free_region_list(free_region_list), _proxy_set(NULL), _humongous_objects_reclaimed(0), _humongous_regions_reclaimed(0), _freed_bytes(0) {
4435 4464 }
4436 4465
4437 4466 virtual bool do_heap_region(HeapRegion* r) {
4438 4467 if (!r->is_starts_humongous()) {
4439 4468 return false;
4440 4469 }
4441 4470
4442 4471 G1CollectedHeap* g1h = G1CollectedHeap::heap();
4443 4472
4444 4473 oop obj = (oop)r->bottom();
4445 4474 G1CMBitMap* next_bitmap = g1h->concurrent_mark()->next_mark_bitmap();
4446 4475
4447 4476 // The following checks whether the humongous object is live are sufficient.
4448 4477 // The main additional check (in addition to having a reference from the roots
4449 4478 // or the young gen) is whether the humongous object has a remembered set entry.
4450 4479 //
4451 4480 // A humongous object cannot be live if there is no remembered set for it
4452 4481 // because:
4453 4482 // - there can be no references from within humongous starts regions referencing
4454 4483 // the object because we never allocate other objects into them.
4455 4484 // (I.e. there are no intra-region references that may be missed by the
4456 4485 // remembered set)
4457 4486 // - as soon there is a remembered set entry to the humongous starts region
4458 4487 // (i.e. it has "escaped" to an old object) this remembered set entry will stay
4459 4488 // until the end of a concurrent mark.
4460 4489 //
4461 4490 // It is not required to check whether the object has been found dead by marking
4462 4491 // or not, in fact it would prevent reclamation within a concurrent cycle, as
4463 4492 // all objects allocated during that time are considered live.
4464 4493 // SATB marking is even more conservative than the remembered set.
4465 4494 // So if at this point in the collection there is no remembered set entry,
4466 4495 // nobody has a reference to it.
4467 4496 // At the start of collection we flush all refinement logs, and remembered sets
4468 4497 // are completely up-to-date wrt to references to the humongous object.
4469 4498 //
4470 4499 // Other implementation considerations:
4471 4500 // - never consider object arrays at this time because they would pose
4472 4501 // considerable effort for cleaning up the the remembered sets. This is
4473 4502 // required because stale remembered sets might reference locations that
4474 4503 // are currently allocated into.
4475 4504 uint region_idx = r->hrm_index();
4476 4505 if (!g1h->is_humongous_reclaim_candidate(region_idx) ||
4477 4506 !r->rem_set()->is_empty()) {
4478 4507 log_debug(gc, humongous)("Live humongous region %u object size " SIZE_FORMAT " start " PTR_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",
4479 4508 region_idx,
4480 4509 (size_t)obj->size() * HeapWordSize,
4481 4510 p2i(r->bottom()),
4482 4511 r->rem_set()->occupied(),
4483 4512 r->rem_set()->strong_code_roots_list_length(),
4484 4513 next_bitmap->is_marked(r->bottom()),
4485 4514 g1h->is_humongous_reclaim_candidate(region_idx),
4486 4515 obj->is_typeArray()
4487 4516 );
4488 4517 return false;
4489 4518 }
4490 4519
4491 4520 guarantee(obj->is_typeArray(),
4492 4521 "Only eagerly reclaiming type arrays is supported, but the object "
4493 4522 PTR_FORMAT " is not.", p2i(r->bottom()));
4494 4523
4495 4524 log_debug(gc, humongous)("Dead humongous region %u object size " SIZE_FORMAT " start " PTR_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",
4496 4525 region_idx,
4497 4526 (size_t)obj->size() * HeapWordSize,
4498 4527 p2i(r->bottom()),
4499 4528 r->rem_set()->occupied(),
4500 4529 r->rem_set()->strong_code_roots_list_length(),
4501 4530 next_bitmap->is_marked(r->bottom()),
4502 4531 g1h->is_humongous_reclaim_candidate(region_idx),
4503 4532 obj->is_typeArray()
4504 4533 );
4505 4534
4506 4535 G1ConcurrentMark* const cm = g1h->concurrent_mark();
4507 4536 cm->humongous_object_eagerly_reclaimed(r);
4508 4537 assert(!cm->is_marked_in_prev_bitmap(obj) && !cm->is_marked_in_next_bitmap(obj),
4509 4538 "Eagerly reclaimed humongous region %u should not be marked at all but is in prev %s next %s",
4510 4539 region_idx,
4511 4540 BOOL_TO_STR(cm->is_marked_in_prev_bitmap(obj)),
4512 4541 BOOL_TO_STR(cm->is_marked_in_next_bitmap(obj)));
4513 4542 _humongous_objects_reclaimed++;
4514 4543 do {
4515 4544 HeapRegion* next = g1h->next_region_in_humongous(r);
4516 4545 _freed_bytes += r->used();
4517 4546 r->set_containing_set(NULL);
4518 4547 _humongous_regions_reclaimed++;
4519 4548 g1h->free_humongous_region(r, _free_region_list);
4520 4549 r = next;
4521 4550 } while (r != NULL);
4522 4551
4523 4552 return false;
4524 4553 }
4525 4554
4526 4555 uint humongous_objects_reclaimed() {
4527 4556 return _humongous_objects_reclaimed;
4528 4557 }
4529 4558
4530 4559 uint humongous_regions_reclaimed() {
4531 4560 return _humongous_regions_reclaimed;
4532 4561 }
4533 4562
4534 4563 size_t bytes_freed() const {
4535 4564 return _freed_bytes;
4536 4565 }
4537 4566 };
4538 4567
4539 4568 void G1CollectedHeap::eagerly_reclaim_humongous_regions() {
4540 4569 assert_at_safepoint_on_vm_thread();
4541 4570
4542 4571 if (!G1EagerReclaimHumongousObjects ||
4543 4572 (!_has_humongous_reclaim_candidates && !log_is_enabled(Debug, gc, humongous))) {
4544 4573 phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0);
4545 4574 return;
4546 4575 }
4547 4576
4548 4577 double start_time = os::elapsedTime();
4549 4578
4550 4579 FreeRegionList local_cleanup_list("Local Humongous Cleanup List");
4551 4580
4552 4581 G1FreeHumongousRegionClosure cl(&local_cleanup_list);
4553 4582 heap_region_iterate(&cl);
4554 4583
4555 4584 remove_from_old_sets(0, cl.humongous_regions_reclaimed());
4556 4585
4557 4586 G1HRPrinter* hrp = hr_printer();
4558 4587 if (hrp->is_active()) {
4559 4588 FreeRegionListIterator iter(&local_cleanup_list);
4560 4589 while (iter.more_available()) {
4561 4590 HeapRegion* hr = iter.get_next();
4562 4591 hrp->cleanup(hr);
4563 4592 }
4564 4593 }
4565 4594
4566 4595 prepend_to_freelist(&local_cleanup_list);
4567 4596 decrement_summary_bytes(cl.bytes_freed());
4568 4597
4569 4598 phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0,
4570 4599 cl.humongous_objects_reclaimed());
4571 4600 }
4572 4601
4573 4602 class G1AbandonCollectionSetClosure : public HeapRegionClosure {
4574 4603 public:
4575 4604 virtual bool do_heap_region(HeapRegion* r) {
4576 4605 assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());
4577 4606 G1CollectedHeap::heap()->clear_region_attr(r);
4578 4607 r->clear_young_index_in_cset();
4579 4608 return false;
4580 4609 }
4581 4610 };
4582 4611
4583 4612 void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) {
4584 4613 G1AbandonCollectionSetClosure cl;
4585 4614 collection_set_iterate_all(&cl);
4586 4615
4587 4616 collection_set->clear();
4588 4617 collection_set->stop_incremental_building();
4589 4618 }
4590 4619
4591 4620 bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) {
4592 4621 return _allocator->is_retained_old_region(hr);
4593 4622 }
4594 4623
4595 4624 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
4596 4625 _eden.add(hr);
4597 4626 _policy->set_region_eden(hr);
4598 4627 }
4599 4628
4600 4629 #ifdef ASSERT
4601 4630
4602 4631 class NoYoungRegionsClosure: public HeapRegionClosure {
4603 4632 private:
4604 4633 bool _success;
4605 4634 public:
4606 4635 NoYoungRegionsClosure() : _success(true) { }
4607 4636 bool do_heap_region(HeapRegion* r) {
4608 4637 if (r->is_young()) {
4609 4638 log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
4610 4639 p2i(r->bottom()), p2i(r->end()));
4611 4640 _success = false;
4612 4641 }
4613 4642 return false;
4614 4643 }
4615 4644 bool success() { return _success; }
4616 4645 };
4617 4646
4618 4647 bool G1CollectedHeap::check_young_list_empty() {
4619 4648 bool ret = (young_regions_count() == 0);
4620 4649
4621 4650 NoYoungRegionsClosure closure;
4622 4651 heap_region_iterate(&closure);
4623 4652 ret = ret && closure.success();
4624 4653
4625 4654 return ret;
4626 4655 }
4627 4656
4628 4657 #endif // ASSERT
4629 4658
4630 4659 class TearDownRegionSetsClosure : public HeapRegionClosure {
4631 4660 HeapRegionSet *_old_set;
4632 4661
4633 4662 public:
4634 4663 TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }
4635 4664
4636 4665 bool do_heap_region(HeapRegion* r) {
4637 4666 if (r->is_old()) {
4638 4667 _old_set->remove(r);
4639 4668 } else if(r->is_young()) {
4640 4669 r->uninstall_surv_rate_group();
4641 4670 } else {
4642 4671 // We ignore free regions, we'll empty the free list afterwards.
4643 4672 // We ignore humongous and archive regions, we're not tearing down these
4644 4673 // sets.
4645 4674 assert(r->is_archive() || r->is_free() || r->is_humongous(),
4646 4675 "it cannot be another type");
4647 4676 }
4648 4677 return false;
4649 4678 }
4650 4679
4651 4680 ~TearDownRegionSetsClosure() {
4652 4681 assert(_old_set->is_empty(), "post-condition");
4653 4682 }
4654 4683 };
4655 4684
4656 4685 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {
4657 4686 assert_at_safepoint_on_vm_thread();
4658 4687
4659 4688 if (!free_list_only) {
4660 4689 TearDownRegionSetsClosure cl(&_old_set);
4661 4690 heap_region_iterate(&cl);
4662 4691
4663 4692 // Note that emptying the _young_list is postponed and instead done as
4664 4693 // the first step when rebuilding the regions sets again. The reason for
4665 4694 // this is that during a full GC string deduplication needs to know if
4666 4695 // a collected region was young or old when the full GC was initiated.
4667 4696 }
4668 4697 _hrm->remove_all_free_regions();
4669 4698 }
4670 4699
4671 4700 void G1CollectedHeap::increase_used(size_t bytes) {
4672 4701 _summary_bytes_used += bytes;
4673 4702 }
4674 4703
4675 4704 void G1CollectedHeap::decrease_used(size_t bytes) {
4676 4705 assert(_summary_bytes_used >= bytes,
4677 4706 "invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,
4678 4707 _summary_bytes_used, bytes);
4679 4708 _summary_bytes_used -= bytes;
4680 4709 }
4681 4710
4682 4711 void G1CollectedHeap::set_used(size_t bytes) {
4683 4712 _summary_bytes_used = bytes;
4684 4713 }
4685 4714
4686 4715 class RebuildRegionSetsClosure : public HeapRegionClosure {
4687 4716 private:
4688 4717 bool _free_list_only;
4689 4718
4690 4719 HeapRegionSet* _old_set;
4691 4720 HeapRegionManager* _hrm;
4692 4721
4693 4722 size_t _total_used;
4694 4723
4695 4724 public:
4696 4725 RebuildRegionSetsClosure(bool free_list_only,
4697 4726 HeapRegionSet* old_set,
4698 4727 HeapRegionManager* hrm) :
4699 4728 _free_list_only(free_list_only),
4700 4729 _old_set(old_set), _hrm(hrm), _total_used(0) {
4701 4730 assert(_hrm->num_free_regions() == 0, "pre-condition");
4702 4731 if (!free_list_only) {
4703 4732 assert(_old_set->is_empty(), "pre-condition");
4704 4733 }
4705 4734 }
4706 4735
4707 4736 bool do_heap_region(HeapRegion* r) {
4708 4737 if (r->is_empty()) {
4709 4738 assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");
4710 4739 // Add free regions to the free list
4711 4740 r->set_free();
4712 4741 _hrm->insert_into_free_list(r);
4713 4742 } else if (!_free_list_only) {
4714 4743 assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");
4715 4744
4716 4745 if (r->is_archive() || r->is_humongous()) {
4717 4746 // We ignore archive and humongous regions. We left these sets unchanged.
4718 4747 } else {
4719 4748 assert(r->is_young() || r->is_free() || r->is_old(), "invariant");
4720 4749 // We now move all (non-humongous, non-old, non-archive) regions to old gen, and register them as such.
4721 4750 r->move_to_old();
4722 4751 _old_set->add(r);
4723 4752 }
4724 4753 _total_used += r->used();
4725 4754 }
4726 4755
4727 4756 return false;
4728 4757 }
4729 4758
4730 4759 size_t total_used() {
4731 4760 return _total_used;
4732 4761 }
4733 4762 };
4734 4763
4735 4764 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
4736 4765 assert_at_safepoint_on_vm_thread();
4737 4766
4738 4767 if (!free_list_only) {
4739 4768 _eden.clear();
4740 4769 _survivor.clear();
4741 4770 }
4742 4771
4743 4772 RebuildRegionSetsClosure cl(free_list_only, &_old_set, _hrm);
4744 4773 heap_region_iterate(&cl);
4745 4774
4746 4775 if (!free_list_only) {
4747 4776 set_used(cl.total_used());
4748 4777 if (_archive_allocator != NULL) {
4749 4778 _archive_allocator->clear_used();
4750 4779 }
4751 4780 }
4752 4781 assert_used_and_recalculate_used_equal(this);
4753 4782 }
4754 4783
4755 4784 // Methods for the mutator alloc region
4756 4785
4757 4786 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
4758 4787 bool force,
4759 4788 uint node_index) {
4760 4789 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4761 4790 bool should_allocate = policy()->should_allocate_mutator_region();
4762 4791 if (force || should_allocate) {
4763 4792 HeapRegion* new_alloc_region = new_region(word_size,
4764 4793 HeapRegionType::Eden,
4765 4794 false /* do_expand */,
4766 4795 node_index);
4767 4796 if (new_alloc_region != NULL) {
4768 4797 set_region_short_lived_locked(new_alloc_region);
4769 4798 _hr_printer.alloc(new_alloc_region, !should_allocate);
4770 4799 _verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region);
4771 4800 _policy->remset_tracker()->update_at_allocate(new_alloc_region);
4772 4801 return new_alloc_region;
4773 4802 }
4774 4803 }
4775 4804 return NULL;
4776 4805 }
4777 4806
4778 4807 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
4779 4808 size_t allocated_bytes) {
4780 4809 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4781 4810 assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
4782 4811
4783 4812 collection_set()->add_eden_region(alloc_region);
4784 4813 increase_used(allocated_bytes);
4785 4814 _eden.add_used_bytes(allocated_bytes);
4786 4815 _hr_printer.retire(alloc_region);
4787 4816
4788 4817 // We update the eden sizes here, when the region is retired,
4789 4818 // instead of when it's allocated, since this is the point that its
4790 4819 // used space has been recorded in _summary_bytes_used.
4791 4820 g1mm()->update_eden_size();
4792 4821 }
4793 4822
4794 4823 // Methods for the GC alloc regions
4795 4824
4796 4825 bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {
4797 4826 if (dest.is_old()) {
4798 4827 return true;
4799 4828 } else {
4800 4829 return survivor_regions_count() < policy()->max_survivor_regions();
4801 4830 }
4802 4831 }
4803 4832
4804 4833 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {
4805 4834 assert(FreeList_lock->owned_by_self(), "pre-condition");
4806 4835
4807 4836 if (!has_more_regions(dest)) {
4808 4837 return NULL;
4809 4838 }
4810 4839
4811 4840 HeapRegionType type;
4812 4841 if (dest.is_young()) {
4813 4842 type = HeapRegionType::Survivor;
4814 4843 } else {
4815 4844 type = HeapRegionType::Old;
4816 4845 }
4817 4846
4818 4847 HeapRegion* new_alloc_region = new_region(word_size,
4819 4848 type,
4820 4849 true /* do_expand */,
4821 4850 node_index);
4822 4851
4823 4852 if (new_alloc_region != NULL) {
4824 4853 if (type.is_survivor()) {
4825 4854 new_alloc_region->set_survivor();
4826 4855 _survivor.add(new_alloc_region);
4827 4856 _verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region);
4828 4857 } else {
4829 4858 new_alloc_region->set_old();
4830 4859 _verifier->check_bitmaps("Old Region Allocation", new_alloc_region);
4831 4860 }
4832 4861 _policy->remset_tracker()->update_at_allocate(new_alloc_region);
4833 4862 register_region_with_region_attr(new_alloc_region);
4834 4863 _hr_printer.alloc(new_alloc_region);
4835 4864 return new_alloc_region;
4836 4865 }
4837 4866 return NULL;
4838 4867 }
4839 4868
4840 4869 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
4841 4870 size_t allocated_bytes,
4842 4871 G1HeapRegionAttr dest) {
4843 4872 _bytes_used_during_gc += allocated_bytes;
4844 4873 if (dest.is_old()) {
4845 4874 old_set_add(alloc_region);
4846 4875 } else {
4847 4876 assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());
4848 4877 _survivor.add_used_bytes(allocated_bytes);
4849 4878 }
4850 4879
4851 4880 bool const during_im = collector_state()->in_initial_mark_gc();
4852 4881 if (during_im && allocated_bytes > 0) {
4853 4882 _cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top());
4854 4883 }
4855 4884 _hr_printer.retire(alloc_region);
4856 4885 }
4857 4886
4858 4887 HeapRegion* G1CollectedHeap::alloc_highest_free_region() {
4859 4888 bool expanded = false;
4860 4889 uint index = _hrm->find_highest_free(&expanded);
4861 4890
4862 4891 if (index != G1_NO_HRM_INDEX) {
4863 4892 if (expanded) {
4864 4893 log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B",
4865 4894 HeapRegion::GrainWords * HeapWordSize);
4866 4895 }
4867 4896 _hrm->allocate_free_regions_starting_at(index, 1);
4868 4897 return region_at(index);
4869 4898 }
4870 4899 return NULL;
4871 4900 }
4872 4901
4873 4902 // Optimized nmethod scanning
4874 4903
4875 4904 class RegisterNMethodOopClosure: public OopClosure {
4876 4905 G1CollectedHeap* _g1h;
4877 4906 nmethod* _nm;
4878 4907
4879 4908 template <class T> void do_oop_work(T* p) {
4880 4909 T heap_oop = RawAccess<>::oop_load(p);
4881 4910 if (!CompressedOops::is_null(heap_oop)) {
4882 4911 oop obj = CompressedOops::decode_not_null(heap_oop);
4883 4912 HeapRegion* hr = _g1h->heap_region_containing(obj);
4884 4913 assert(!hr->is_continues_humongous(),
4885 4914 "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4886 4915 " starting at " HR_FORMAT,
4887 4916 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4888 4917
4889 4918 // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.
4890 4919 hr->add_strong_code_root_locked(_nm);
4891 4920 }
4892 4921 }
4893 4922
4894 4923 public:
4895 4924 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4896 4925 _g1h(g1h), _nm(nm) {}
4897 4926
4898 4927 void do_oop(oop* p) { do_oop_work(p); }
4899 4928 void do_oop(narrowOop* p) { do_oop_work(p); }
4900 4929 };
4901 4930
4902 4931 class UnregisterNMethodOopClosure: public OopClosure {
4903 4932 G1CollectedHeap* _g1h;
4904 4933 nmethod* _nm;
4905 4934
4906 4935 template <class T> void do_oop_work(T* p) {
4907 4936 T heap_oop = RawAccess<>::oop_load(p);
4908 4937 if (!CompressedOops::is_null(heap_oop)) {
4909 4938 oop obj = CompressedOops::decode_not_null(heap_oop);
4910 4939 HeapRegion* hr = _g1h->heap_region_containing(obj);
4911 4940 assert(!hr->is_continues_humongous(),
4912 4941 "trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4913 4942 " starting at " HR_FORMAT,
4914 4943 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4915 4944
4916 4945 hr->remove_strong_code_root(_nm);
4917 4946 }
4918 4947 }
4919 4948
4920 4949 public:
4921 4950 UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4922 4951 _g1h(g1h), _nm(nm) {}
4923 4952
4924 4953 void do_oop(oop* p) { do_oop_work(p); }
4925 4954 void do_oop(narrowOop* p) { do_oop_work(p); }
4926 4955 };
4927 4956
4928 4957 void G1CollectedHeap::register_nmethod(nmethod* nm) {
4929 4958 guarantee(nm != NULL, "sanity");
4930 4959 RegisterNMethodOopClosure reg_cl(this, nm);
4931 4960 nm->oops_do(®_cl);
4932 4961 }
4933 4962
4934 4963 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
4935 4964 guarantee(nm != NULL, "sanity");
4936 4965 UnregisterNMethodOopClosure reg_cl(this, nm);
4937 4966 nm->oops_do(®_cl, true);
4938 4967 }
4939 4968
4940 4969 void G1CollectedHeap::purge_code_root_memory() {
4941 4970 double purge_start = os::elapsedTime();
4942 4971 G1CodeRootSet::purge();
4943 4972 double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0;
4944 4973 phase_times()->record_strong_code_root_purge_time(purge_time_ms);
4945 4974 }
4946 4975
4947 4976 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
4948 4977 G1CollectedHeap* _g1h;
4949 4978
4950 4979 public:
4951 4980 RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
4952 4981 _g1h(g1h) {}
4953 4982
4954 4983 void do_code_blob(CodeBlob* cb) {
4955 4984 nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
4956 4985 if (nm == NULL) {
4957 4986 return;
4958 4987 }
4959 4988
4960 4989 _g1h->register_nmethod(nm);
4961 4990 }
4962 4991 };
4963 4992
4964 4993 void G1CollectedHeap::rebuild_strong_code_roots() {
4965 4994 RebuildStrongCodeRootClosure blob_cl(this);
4966 4995 CodeCache::blobs_do(&blob_cl);
4967 4996 }
4968 4997
4969 4998 void G1CollectedHeap::initialize_serviceability() {
4970 4999 _g1mm->initialize_serviceability();
4971 5000 }
4972 5001
4973 5002 MemoryUsage G1CollectedHeap::memory_usage() {
4974 5003 return _g1mm->memory_usage();
4975 5004 }
4976 5005
4977 5006 GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {
4978 5007 return _g1mm->memory_managers();
4979 5008 }
4980 5009
4981 5010 GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {
4982 5011 return _g1mm->memory_pools();
4983 5012 }
↓ open down ↓ |
1853 lines elided |
↑ open up ↑ |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX