comparison src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp @ 362:f8199438385b

Merge
author apetrusenko
date Wed, 17 Sep 2008 16:49:18 +0400
parents 0edda524b58c
children cc68c8e9b309
comparison
equal deleted inserted replaced
316:5fa96a5a7e76 362:f8199438385b
1 /*
2 * Copyright 2001-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
24
25 #include "incls/_precompiled.incl"
26 #include "incls/_g1CollectedHeap.cpp.incl"
27
28 // turn it on so that the contents of the young list (scan-only /
29 // to-be-collected) are printed at "strategic" points before / during
30 // / after the collection --- this is useful for debugging
31 #define SCAN_ONLY_VERBOSE 0
32 // CURRENT STATUS
33 // This file is under construction. Search for "FIXME".
34
35 // INVARIANTS/NOTES
36 //
37 // All allocation activity covered by the G1CollectedHeap interface is
38 // serialized by acquiring the HeapLock. This happens in
39 // mem_allocate_work, which all such allocation functions call.
40 // (Note that this does not apply to TLAB allocation, which is not part
41 // of this interface: it is done by clients of this interface.)
42
43 // Local to this file.
44
45 // Finds the first HeapRegion.
46 // No longer used, but might be handy someday.
47
48 class FindFirstRegionClosure: public HeapRegionClosure {
49 HeapRegion* _a_region;
50 public:
51 FindFirstRegionClosure() : _a_region(NULL) {}
52 bool doHeapRegion(HeapRegion* r) {
53 _a_region = r;
54 return true;
55 }
56 HeapRegion* result() { return _a_region; }
57 };
58
59
60 class RefineCardTableEntryClosure: public CardTableEntryClosure {
61 SuspendibleThreadSet* _sts;
62 G1RemSet* _g1rs;
63 ConcurrentG1Refine* _cg1r;
64 bool _concurrent;
65 public:
66 RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
67 G1RemSet* g1rs,
68 ConcurrentG1Refine* cg1r) :
69 _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
70 {}
71 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
72 _g1rs->concurrentRefineOneCard(card_ptr, worker_i);
73 if (_concurrent && _sts->should_yield()) {
74 // Caller will actually yield.
75 return false;
76 }
77 // Otherwise, we finished successfully; return true.
78 return true;
79 }
80 void set_concurrent(bool b) { _concurrent = b; }
81 };
82
83
84 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
85 int _calls;
86 G1CollectedHeap* _g1h;
87 CardTableModRefBS* _ctbs;
88 int _histo[256];
89 public:
90 ClearLoggedCardTableEntryClosure() :
91 _calls(0)
92 {
93 _g1h = G1CollectedHeap::heap();
94 _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
95 for (int i = 0; i < 256; i++) _histo[i] = 0;
96 }
97 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
98 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
99 _calls++;
100 unsigned char* ujb = (unsigned char*)card_ptr;
101 int ind = (int)(*ujb);
102 _histo[ind]++;
103 *card_ptr = -1;
104 }
105 return true;
106 }
107 int calls() { return _calls; }
108 void print_histo() {
109 gclog_or_tty->print_cr("Card table value histogram:");
110 for (int i = 0; i < 256; i++) {
111 if (_histo[i] != 0) {
112 gclog_or_tty->print_cr(" %d: %d", i, _histo[i]);
113 }
114 }
115 }
116 };
117
118 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
119 int _calls;
120 G1CollectedHeap* _g1h;
121 CardTableModRefBS* _ctbs;
122 public:
123 RedirtyLoggedCardTableEntryClosure() :
124 _calls(0)
125 {
126 _g1h = G1CollectedHeap::heap();
127 _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
128 }
129 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
130 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
131 _calls++;
132 *card_ptr = 0;
133 }
134 return true;
135 }
136 int calls() { return _calls; }
137 };
138
139 YoungList::YoungList(G1CollectedHeap* g1h)
140 : _g1h(g1h), _head(NULL),
141 _scan_only_head(NULL), _scan_only_tail(NULL), _curr_scan_only(NULL),
142 _length(0), _scan_only_length(0),
143 _last_sampled_rs_lengths(0),
144 _survivor_head(NULL), _survivors_tail(NULL), _survivor_length(0)
145 {
146 guarantee( check_list_empty(false), "just making sure..." );
147 }
148
149 void YoungList::push_region(HeapRegion *hr) {
150 assert(!hr->is_young(), "should not already be young");
151 assert(hr->get_next_young_region() == NULL, "cause it should!");
152
153 hr->set_next_young_region(_head);
154 _head = hr;
155
156 hr->set_young();
157 double yg_surv_rate = _g1h->g1_policy()->predict_yg_surv_rate((int)_length);
158 ++_length;
159 }
160
161 void YoungList::add_survivor_region(HeapRegion* hr) {
162 assert(!hr->is_survivor(), "should not already be for survived");
163 assert(hr->get_next_young_region() == NULL, "cause it should!");
164
165 hr->set_next_young_region(_survivor_head);
166 if (_survivor_head == NULL) {
167 _survivors_tail = hr;
168 }
169 _survivor_head = hr;
170
171 hr->set_survivor();
172 ++_survivor_length;
173 }
174
175 HeapRegion* YoungList::pop_region() {
176 while (_head != NULL) {
177 assert( length() > 0, "list should not be empty" );
178 HeapRegion* ret = _head;
179 _head = ret->get_next_young_region();
180 ret->set_next_young_region(NULL);
181 --_length;
182 assert(ret->is_young(), "region should be very young");
183
184 // Replace 'Survivor' region type with 'Young'. So the region will
185 // be treated as a young region and will not be 'confused' with
186 // newly created survivor regions.
187 if (ret->is_survivor()) {
188 ret->set_young();
189 }
190
191 if (!ret->is_scan_only()) {
192 return ret;
193 }
194
195 // scan-only, we'll add it to the scan-only list
196 if (_scan_only_tail == NULL) {
197 guarantee( _scan_only_head == NULL, "invariant" );
198
199 _scan_only_head = ret;
200 _curr_scan_only = ret;
201 } else {
202 guarantee( _scan_only_head != NULL, "invariant" );
203 _scan_only_tail->set_next_young_region(ret);
204 }
205 guarantee( ret->get_next_young_region() == NULL, "invariant" );
206 _scan_only_tail = ret;
207
208 // no need to be tagged as scan-only any more
209 ret->set_young();
210
211 ++_scan_only_length;
212 }
213 assert( length() == 0, "list should be empty" );
214 return NULL;
215 }
216
217 void YoungList::empty_list(HeapRegion* list) {
218 while (list != NULL) {
219 HeapRegion* next = list->get_next_young_region();
220 list->set_next_young_region(NULL);
221 list->uninstall_surv_rate_group();
222 list->set_not_young();
223 list = next;
224 }
225 }
226
227 void YoungList::empty_list() {
228 assert(check_list_well_formed(), "young list should be well formed");
229
230 empty_list(_head);
231 _head = NULL;
232 _length = 0;
233
234 empty_list(_scan_only_head);
235 _scan_only_head = NULL;
236 _scan_only_tail = NULL;
237 _scan_only_length = 0;
238 _curr_scan_only = NULL;
239
240 empty_list(_survivor_head);
241 _survivor_head = NULL;
242 _survivors_tail = NULL;
243 _survivor_length = 0;
244
245 _last_sampled_rs_lengths = 0;
246
247 assert(check_list_empty(false), "just making sure...");
248 }
249
250 bool YoungList::check_list_well_formed() {
251 bool ret = true;
252
253 size_t length = 0;
254 HeapRegion* curr = _head;
255 HeapRegion* last = NULL;
256 while (curr != NULL) {
257 if (!curr->is_young() || curr->is_scan_only()) {
258 gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
259 "incorrectly tagged (%d, %d)",
260 curr->bottom(), curr->end(),
261 curr->is_young(), curr->is_scan_only());
262 ret = false;
263 }
264 ++length;
265 last = curr;
266 curr = curr->get_next_young_region();
267 }
268 ret = ret && (length == _length);
269
270 if (!ret) {
271 gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
272 gclog_or_tty->print_cr("### list has %d entries, _length is %d",
273 length, _length);
274 }
275
276 bool scan_only_ret = true;
277 length = 0;
278 curr = _scan_only_head;
279 last = NULL;
280 while (curr != NULL) {
281 if (!curr->is_young() || curr->is_scan_only()) {
282 gclog_or_tty->print_cr("### SCAN-ONLY REGION "PTR_FORMAT"-"PTR_FORMAT" "
283 "incorrectly tagged (%d, %d)",
284 curr->bottom(), curr->end(),
285 curr->is_young(), curr->is_scan_only());
286 scan_only_ret = false;
287 }
288 ++length;
289 last = curr;
290 curr = curr->get_next_young_region();
291 }
292 scan_only_ret = scan_only_ret && (length == _scan_only_length);
293
294 if ( (last != _scan_only_tail) ||
295 (_scan_only_head == NULL && _scan_only_tail != NULL) ||
296 (_scan_only_head != NULL && _scan_only_tail == NULL) ) {
297 gclog_or_tty->print_cr("## _scan_only_tail is set incorrectly");
298 scan_only_ret = false;
299 }
300
301 if (_curr_scan_only != NULL && _curr_scan_only != _scan_only_head) {
302 gclog_or_tty->print_cr("### _curr_scan_only is set incorrectly");
303 scan_only_ret = false;
304 }
305
306 if (!scan_only_ret) {
307 gclog_or_tty->print_cr("### SCAN-ONLY LIST seems not well formed!");
308 gclog_or_tty->print_cr("### list has %d entries, _scan_only_length is %d",
309 length, _scan_only_length);
310 }
311
312 return ret && scan_only_ret;
313 }
314
315 bool YoungList::check_list_empty(bool ignore_scan_only_list,
316 bool check_sample) {
317 bool ret = true;
318
319 if (_length != 0) {
320 gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %d",
321 _length);
322 ret = false;
323 }
324 if (check_sample && _last_sampled_rs_lengths != 0) {
325 gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
326 ret = false;
327 }
328 if (_head != NULL) {
329 gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
330 ret = false;
331 }
332 if (!ret) {
333 gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
334 }
335
336 if (ignore_scan_only_list)
337 return ret;
338
339 bool scan_only_ret = true;
340 if (_scan_only_length != 0) {
341 gclog_or_tty->print_cr("### SCAN-ONLY LIST should have 0 length, not %d",
342 _scan_only_length);
343 scan_only_ret = false;
344 }
345 if (_scan_only_head != NULL) {
346 gclog_or_tty->print_cr("### SCAN-ONLY LIST does not have a NULL head");
347 scan_only_ret = false;
348 }
349 if (_scan_only_tail != NULL) {
350 gclog_or_tty->print_cr("### SCAN-ONLY LIST does not have a NULL tail");
351 scan_only_ret = false;
352 }
353 if (!scan_only_ret) {
354 gclog_or_tty->print_cr("### SCAN-ONLY LIST does not seem empty");
355 }
356
357 return ret && scan_only_ret;
358 }
359
360 void
361 YoungList::rs_length_sampling_init() {
362 _sampled_rs_lengths = 0;
363 _curr = _head;
364 }
365
366 bool
367 YoungList::rs_length_sampling_more() {
368 return _curr != NULL;
369 }
370
371 void
372 YoungList::rs_length_sampling_next() {
373 assert( _curr != NULL, "invariant" );
374 _sampled_rs_lengths += _curr->rem_set()->occupied();
375 _curr = _curr->get_next_young_region();
376 if (_curr == NULL) {
377 _last_sampled_rs_lengths = _sampled_rs_lengths;
378 // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
379 }
380 }
381
382 void
383 YoungList::reset_auxilary_lists() {
384 // We could have just "moved" the scan-only list to the young list.
385 // However, the scan-only list is ordered according to the region
386 // age in descending order, so, by moving one entry at a time, we
387 // ensure that it is recreated in ascending order.
388
389 guarantee( is_empty(), "young list should be empty" );
390 assert(check_list_well_formed(), "young list should be well formed");
391
392 // Add survivor regions to SurvRateGroup.
393 _g1h->g1_policy()->note_start_adding_survivor_regions();
394 for (HeapRegion* curr = _survivor_head;
395 curr != NULL;
396 curr = curr->get_next_young_region()) {
397 _g1h->g1_policy()->set_region_survivors(curr);
398 }
399 _g1h->g1_policy()->note_stop_adding_survivor_regions();
400
401 if (_survivor_head != NULL) {
402 _head = _survivor_head;
403 _length = _survivor_length + _scan_only_length;
404 _survivors_tail->set_next_young_region(_scan_only_head);
405 } else {
406 _head = _scan_only_head;
407 _length = _scan_only_length;
408 }
409
410 for (HeapRegion* curr = _scan_only_head;
411 curr != NULL;
412 curr = curr->get_next_young_region()) {
413 curr->recalculate_age_in_surv_rate_group();
414 }
415 _scan_only_head = NULL;
416 _scan_only_tail = NULL;
417 _scan_only_length = 0;
418 _curr_scan_only = NULL;
419
420 _survivor_head = NULL;
421 _survivors_tail = NULL;
422 _survivor_length = 0;
423 _g1h->g1_policy()->finished_recalculating_age_indexes();
424
425 assert(check_list_well_formed(), "young list should be well formed");
426 }
427
428 void YoungList::print() {
429 HeapRegion* lists[] = {_head, _scan_only_head, _survivor_head};
430 const char* names[] = {"YOUNG", "SCAN-ONLY", "SURVIVOR"};
431
432 for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
433 gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
434 HeapRegion *curr = lists[list];
435 if (curr == NULL)
436 gclog_or_tty->print_cr(" empty");
437 while (curr != NULL) {
438 gclog_or_tty->print_cr(" [%08x-%08x], t: %08x, P: %08x, N: %08x, C: %08x, "
439 "age: %4d, y: %d, s-o: %d, surv: %d",
440 curr->bottom(), curr->end(),
441 curr->top(),
442 curr->prev_top_at_mark_start(),
443 curr->next_top_at_mark_start(),
444 curr->top_at_conc_mark_count(),
445 curr->age_in_surv_rate_group_cond(),
446 curr->is_young(),
447 curr->is_scan_only(),
448 curr->is_survivor());
449 curr = curr->get_next_young_region();
450 }
451 }
452
453 gclog_or_tty->print_cr("");
454 }
455
456 void G1CollectedHeap::stop_conc_gc_threads() {
457 _cg1r->cg1rThread()->stop();
458 _czft->stop();
459 _cmThread->stop();
460 }
461
462
463 void G1CollectedHeap::check_ct_logs_at_safepoint() {
464 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
465 CardTableModRefBS* ct_bs = (CardTableModRefBS*)barrier_set();
466
467 // Count the dirty cards at the start.
468 CountNonCleanMemRegionClosure count1(this);
469 ct_bs->mod_card_iterate(&count1);
470 int orig_count = count1.n();
471
472 // First clear the logged cards.
473 ClearLoggedCardTableEntryClosure clear;
474 dcqs.set_closure(&clear);
475 dcqs.apply_closure_to_all_completed_buffers();
476 dcqs.iterate_closure_all_threads(false);
477 clear.print_histo();
478
479 // Now ensure that there's no dirty cards.
480 CountNonCleanMemRegionClosure count2(this);
481 ct_bs->mod_card_iterate(&count2);
482 if (count2.n() != 0) {
483 gclog_or_tty->print_cr("Card table has %d entries; %d originally",
484 count2.n(), orig_count);
485 }
486 guarantee(count2.n() == 0, "Card table should be clean.");
487
488 RedirtyLoggedCardTableEntryClosure redirty;
489 JavaThread::dirty_card_queue_set().set_closure(&redirty);
490 dcqs.apply_closure_to_all_completed_buffers();
491 dcqs.iterate_closure_all_threads(false);
492 gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
493 clear.calls(), orig_count);
494 guarantee(redirty.calls() == clear.calls(),
495 "Or else mechanism is broken.");
496
497 CountNonCleanMemRegionClosure count3(this);
498 ct_bs->mod_card_iterate(&count3);
499 if (count3.n() != orig_count) {
500 gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
501 orig_count, count3.n());
502 guarantee(count3.n() >= orig_count, "Should have restored them all.");
503 }
504
505 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
506 }
507
508 // Private class members.
509
510 G1CollectedHeap* G1CollectedHeap::_g1h;
511
512 // Private methods.
513
514 // Finds a HeapRegion that can be used to allocate a given size of block.
515
516
517 HeapRegion* G1CollectedHeap::newAllocRegion_work(size_t word_size,
518 bool do_expand,
519 bool zero_filled) {
520 ConcurrentZFThread::note_region_alloc();
521 HeapRegion* res = alloc_free_region_from_lists(zero_filled);
522 if (res == NULL && do_expand) {
523 expand(word_size * HeapWordSize);
524 res = alloc_free_region_from_lists(zero_filled);
525 assert(res == NULL ||
526 (!res->isHumongous() &&
527 (!zero_filled ||
528 res->zero_fill_state() == HeapRegion::Allocated)),
529 "Alloc Regions must be zero filled (and non-H)");
530 }
531 if (res != NULL && res->is_empty()) _free_regions--;
532 assert(res == NULL ||
533 (!res->isHumongous() &&
534 (!zero_filled ||
535 res->zero_fill_state() == HeapRegion::Allocated)),
536 "Non-young alloc Regions must be zero filled (and non-H)");
537
538 if (G1TraceRegions) {
539 if (res != NULL) {
540 gclog_or_tty->print_cr("new alloc region %d:["PTR_FORMAT", "PTR_FORMAT"], "
541 "top "PTR_FORMAT,
542 res->hrs_index(), res->bottom(), res->end(), res->top());
543 }
544 }
545
546 return res;
547 }
548
549 HeapRegion* G1CollectedHeap::newAllocRegionWithExpansion(int purpose,
550 size_t word_size,
551 bool zero_filled) {
552 HeapRegion* alloc_region = NULL;
553 if (_gc_alloc_region_counts[purpose] < g1_policy()->max_regions(purpose)) {
554 alloc_region = newAllocRegion_work(word_size, true, zero_filled);
555 if (purpose == GCAllocForSurvived && alloc_region != NULL) {
556 _young_list->add_survivor_region(alloc_region);
557 }
558 ++_gc_alloc_region_counts[purpose];
559 } else {
560 g1_policy()->note_alloc_region_limit_reached(purpose);
561 }
562 return alloc_region;
563 }
564
565 // If could fit into free regions w/o expansion, try.
566 // Otherwise, if can expand, do so.
567 // Otherwise, if using ex regions might help, try with ex given back.
568 HeapWord* G1CollectedHeap::humongousObjAllocate(size_t word_size) {
569 assert(regions_accounted_for(), "Region leakage!");
570
571 // We can't allocate H regions while cleanupComplete is running, since
572 // some of the regions we find to be empty might not yet be added to the
573 // unclean list. (If we're already at a safepoint, this call is
574 // unnecessary, not to mention wrong.)
575 if (!SafepointSynchronize::is_at_safepoint())
576 wait_for_cleanup_complete();
577
578 size_t num_regions =
579 round_to(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
580
581 // Special case if < one region???
582
583 // Remember the ft size.
584 size_t x_size = expansion_regions();
585
586 HeapWord* res = NULL;
587 bool eliminated_allocated_from_lists = false;
588
589 // Can the allocation potentially fit in the free regions?
590 if (free_regions() >= num_regions) {
591 res = _hrs->obj_allocate(word_size);
592 }
593 if (res == NULL) {
594 // Try expansion.
595 size_t fs = _hrs->free_suffix();
596 if (fs + x_size >= num_regions) {
597 expand((num_regions - fs) * HeapRegion::GrainBytes);
598 res = _hrs->obj_allocate(word_size);
599 assert(res != NULL, "This should have worked.");
600 } else {
601 // Expansion won't help. Are there enough free regions if we get rid
602 // of reservations?
603 size_t avail = free_regions();
604 if (avail >= num_regions) {
605 res = _hrs->obj_allocate(word_size);
606 if (res != NULL) {
607 remove_allocated_regions_from_lists();
608 eliminated_allocated_from_lists = true;
609 }
610 }
611 }
612 }
613 if (res != NULL) {
614 // Increment by the number of regions allocated.
615 // FIXME: Assumes regions all of size GrainBytes.
616 #ifndef PRODUCT
617 mr_bs()->verify_clean_region(MemRegion(res, res + num_regions *
618 HeapRegion::GrainWords));
619 #endif
620 if (!eliminated_allocated_from_lists)
621 remove_allocated_regions_from_lists();
622 _summary_bytes_used += word_size * HeapWordSize;
623 _free_regions -= num_regions;
624 _num_humongous_regions += (int) num_regions;
625 }
626 assert(regions_accounted_for(), "Region Leakage");
627 return res;
628 }
629
630 HeapWord*
631 G1CollectedHeap::attempt_allocation_slow(size_t word_size,
632 bool permit_collection_pause) {
633 HeapWord* res = NULL;
634 HeapRegion* allocated_young_region = NULL;
635
636 assert( SafepointSynchronize::is_at_safepoint() ||
637 Heap_lock->owned_by_self(), "pre condition of the call" );
638
639 if (isHumongous(word_size)) {
640 // Allocation of a humongous object can, in a sense, complete a
641 // partial region, if the previous alloc was also humongous, and
642 // caused the test below to succeed.
643 if (permit_collection_pause)
644 do_collection_pause_if_appropriate(word_size);
645 res = humongousObjAllocate(word_size);
646 assert(_cur_alloc_region == NULL
647 || !_cur_alloc_region->isHumongous(),
648 "Prevent a regression of this bug.");
649
650 } else {
651 // We may have concurrent cleanup working at the time. Wait for it
652 // to complete. In the future we would probably want to make the
653 // concurrent cleanup truly concurrent by decoupling it from the
654 // allocation.
655 if (!SafepointSynchronize::is_at_safepoint())
656 wait_for_cleanup_complete();
657 // If we do a collection pause, this will be reset to a non-NULL
658 // value. If we don't, nulling here ensures that we allocate a new
659 // region below.
660 if (_cur_alloc_region != NULL) {
661 // We're finished with the _cur_alloc_region.
662 _summary_bytes_used += _cur_alloc_region->used();
663 _cur_alloc_region = NULL;
664 }
665 assert(_cur_alloc_region == NULL, "Invariant.");
666 // Completion of a heap region is perhaps a good point at which to do
667 // a collection pause.
668 if (permit_collection_pause)
669 do_collection_pause_if_appropriate(word_size);
670 // Make sure we have an allocation region available.
671 if (_cur_alloc_region == NULL) {
672 if (!SafepointSynchronize::is_at_safepoint())
673 wait_for_cleanup_complete();
674 bool next_is_young = should_set_young_locked();
675 // If the next region is not young, make sure it's zero-filled.
676 _cur_alloc_region = newAllocRegion(word_size, !next_is_young);
677 if (_cur_alloc_region != NULL) {
678 _summary_bytes_used -= _cur_alloc_region->used();
679 if (next_is_young) {
680 set_region_short_lived_locked(_cur_alloc_region);
681 allocated_young_region = _cur_alloc_region;
682 }
683 }
684 }
685 assert(_cur_alloc_region == NULL || !_cur_alloc_region->isHumongous(),
686 "Prevent a regression of this bug.");
687
688 // Now retry the allocation.
689 if (_cur_alloc_region != NULL) {
690 res = _cur_alloc_region->allocate(word_size);
691 }
692 }
693
694 // NOTE: fails frequently in PRT
695 assert(regions_accounted_for(), "Region leakage!");
696
697 if (res != NULL) {
698 if (!SafepointSynchronize::is_at_safepoint()) {
699 assert( permit_collection_pause, "invariant" );
700 assert( Heap_lock->owned_by_self(), "invariant" );
701 Heap_lock->unlock();
702 }
703
704 if (allocated_young_region != NULL) {
705 HeapRegion* hr = allocated_young_region;
706 HeapWord* bottom = hr->bottom();
707 HeapWord* end = hr->end();
708 MemRegion mr(bottom, end);
709 ((CardTableModRefBS*)_g1h->barrier_set())->dirty(mr);
710 }
711 }
712
713 assert( SafepointSynchronize::is_at_safepoint() ||
714 (res == NULL && Heap_lock->owned_by_self()) ||
715 (res != NULL && !Heap_lock->owned_by_self()),
716 "post condition of the call" );
717
718 return res;
719 }
720
721 HeapWord*
722 G1CollectedHeap::mem_allocate(size_t word_size,
723 bool is_noref,
724 bool is_tlab,
725 bool* gc_overhead_limit_was_exceeded) {
726 debug_only(check_for_valid_allocation_state());
727 assert(no_gc_in_progress(), "Allocation during gc not allowed");
728 HeapWord* result = NULL;
729
730 // Loop until the allocation is satisified,
731 // or unsatisfied after GC.
732 for (int try_count = 1; /* return or throw */; try_count += 1) {
733 int gc_count_before;
734 {
735 Heap_lock->lock();
736 result = attempt_allocation(word_size);
737 if (result != NULL) {
738 // attempt_allocation should have unlocked the heap lock
739 assert(is_in(result), "result not in heap");
740 return result;
741 }
742 // Read the gc count while the heap lock is held.
743 gc_count_before = SharedHeap::heap()->total_collections();
744 Heap_lock->unlock();
745 }
746
747 // Create the garbage collection operation...
748 VM_G1CollectForAllocation op(word_size,
749 gc_count_before);
750
751 // ...and get the VM thread to execute it.
752 VMThread::execute(&op);
753 if (op.prologue_succeeded()) {
754 result = op.result();
755 assert(result == NULL || is_in(result), "result not in heap");
756 return result;
757 }
758
759 // Give a warning if we seem to be looping forever.
760 if ((QueuedAllocationWarningCount > 0) &&
761 (try_count % QueuedAllocationWarningCount == 0)) {
762 warning("G1CollectedHeap::mem_allocate_work retries %d times",
763 try_count);
764 }
765 }
766 }
767
768 void G1CollectedHeap::abandon_cur_alloc_region() {
769 if (_cur_alloc_region != NULL) {
770 // We're finished with the _cur_alloc_region.
771 if (_cur_alloc_region->is_empty()) {
772 _free_regions++;
773 free_region(_cur_alloc_region);
774 } else {
775 _summary_bytes_used += _cur_alloc_region->used();
776 }
777 _cur_alloc_region = NULL;
778 }
779 }
780
781 class PostMCRemSetClearClosure: public HeapRegionClosure {
782 ModRefBarrierSet* _mr_bs;
783 public:
784 PostMCRemSetClearClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
785 bool doHeapRegion(HeapRegion* r) {
786 r->reset_gc_time_stamp();
787 if (r->continuesHumongous())
788 return false;
789 HeapRegionRemSet* hrrs = r->rem_set();
790 if (hrrs != NULL) hrrs->clear();
791 // You might think here that we could clear just the cards
792 // corresponding to the used region. But no: if we leave a dirty card
793 // in a region we might allocate into, then it would prevent that card
794 // from being enqueued, and cause it to be missed.
795 // Re: the performance cost: we shouldn't be doing full GC anyway!
796 _mr_bs->clear(MemRegion(r->bottom(), r->end()));
797 return false;
798 }
799 };
800
801
802 class PostMCRemSetInvalidateClosure: public HeapRegionClosure {
803 ModRefBarrierSet* _mr_bs;
804 public:
805 PostMCRemSetInvalidateClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
806 bool doHeapRegion(HeapRegion* r) {
807 if (r->continuesHumongous()) return false;
808 if (r->used_region().word_size() != 0) {
809 _mr_bs->invalidate(r->used_region(), true /*whole heap*/);
810 }
811 return false;
812 }
813 };
814
815 void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs,
816 size_t word_size) {
817 ResourceMark rm;
818
819 if (full && DisableExplicitGC) {
820 gclog_or_tty->print("\n\n\nDisabling Explicit GC\n\n\n");
821 return;
822 }
823
824 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
825 assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
826
827 if (GC_locker::is_active()) {
828 return; // GC is disabled (e.g. JNI GetXXXCritical operation)
829 }
830
831 {
832 IsGCActiveMark x;
833
834 // Timing
835 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
836 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
837 TraceTime t(full ? "Full GC (System.gc())" : "Full GC", PrintGC, true, gclog_or_tty);
838
839 double start = os::elapsedTime();
840 GCOverheadReporter::recordSTWStart(start);
841 g1_policy()->record_full_collection_start();
842
843 gc_prologue(true);
844 increment_total_collections();
845
846 size_t g1h_prev_used = used();
847 assert(used() == recalculate_used(), "Should be equal");
848
849 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
850 HandleMark hm; // Discard invalid handles created during verification
851 prepare_for_verify();
852 gclog_or_tty->print(" VerifyBeforeGC:");
853 Universe::verify(true);
854 }
855 assert(regions_accounted_for(), "Region leakage!");
856
857 COMPILER2_PRESENT(DerivedPointerTable::clear());
858
859 // We want to discover references, but not process them yet.
860 // This mode is disabled in
861 // instanceRefKlass::process_discovered_references if the
862 // generation does some collection work, or
863 // instanceRefKlass::enqueue_discovered_references if the
864 // generation returns without doing any work.
865 ref_processor()->disable_discovery();
866 ref_processor()->abandon_partial_discovery();
867 ref_processor()->verify_no_references_recorded();
868
869 // Abandon current iterations of concurrent marking and concurrent
870 // refinement, if any are in progress.
871 concurrent_mark()->abort();
872
873 // Make sure we'll choose a new allocation region afterwards.
874 abandon_cur_alloc_region();
875 assert(_cur_alloc_region == NULL, "Invariant.");
876 g1_rem_set()->as_HRInto_G1RemSet()->cleanupHRRS();
877 tear_down_region_lists();
878 set_used_regions_to_need_zero_fill();
879 if (g1_policy()->in_young_gc_mode()) {
880 empty_young_list();
881 g1_policy()->set_full_young_gcs(true);
882 }
883
884 // Temporarily make reference _discovery_ single threaded (non-MT).
885 ReferenceProcessorMTMutator rp_disc_ser(ref_processor(), false);
886
887 // Temporarily make refs discovery atomic
888 ReferenceProcessorAtomicMutator rp_disc_atomic(ref_processor(), true);
889
890 // Temporarily clear _is_alive_non_header
891 ReferenceProcessorIsAliveMutator rp_is_alive_null(ref_processor(), NULL);
892
893 ref_processor()->enable_discovery();
894
895 // Do collection work
896 {
897 HandleMark hm; // Discard invalid handles created during gc
898 G1MarkSweep::invoke_at_safepoint(ref_processor(), clear_all_soft_refs);
899 }
900 // Because freeing humongous regions may have added some unclean
901 // regions, it is necessary to tear down again before rebuilding.
902 tear_down_region_lists();
903 rebuild_region_lists();
904
905 _summary_bytes_used = recalculate_used();
906
907 ref_processor()->enqueue_discovered_references();
908
909 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
910
911 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
912 HandleMark hm; // Discard invalid handles created during verification
913 gclog_or_tty->print(" VerifyAfterGC:");
914 Universe::verify(false);
915 }
916 NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
917
918 reset_gc_time_stamp();
919 // Since everything potentially moved, we will clear all remembered
920 // sets, and clear all cards. Later we will also cards in the used
921 // portion of the heap after the resizing (which could be a shrinking.)
922 // We will also reset the GC time stamps of the regions.
923 PostMCRemSetClearClosure rs_clear(mr_bs());
924 heap_region_iterate(&rs_clear);
925
926 // Resize the heap if necessary.
927 resize_if_necessary_after_full_collection(full ? 0 : word_size);
928
929 // Since everything potentially moved, we will clear all remembered
930 // sets, but also dirty all cards corresponding to used regions.
931 PostMCRemSetInvalidateClosure rs_invalidate(mr_bs());
932 heap_region_iterate(&rs_invalidate);
933 if (_cg1r->use_cache()) {
934 _cg1r->clear_and_record_card_counts();
935 _cg1r->clear_hot_cache();
936 }
937
938 if (PrintGC) {
939 print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity());
940 }
941
942 if (true) { // FIXME
943 // Ask the permanent generation to adjust size for full collections
944 perm()->compute_new_size();
945 }
946
947 double end = os::elapsedTime();
948 GCOverheadReporter::recordSTWEnd(end);
949 g1_policy()->record_full_collection_end();
950
951 gc_epilogue(true);
952
953 // Abandon concurrent refinement. This must happen last: in the
954 // dirty-card logging system, some cards may be dirty by weak-ref
955 // processing, and may be enqueued. But the whole card table is
956 // dirtied, so this should abandon those logs, and set "do_traversal"
957 // to true.
958 concurrent_g1_refine()->set_pya_restart();
959
960 assert(regions_accounted_for(), "Region leakage!");
961 }
962
963 if (g1_policy()->in_young_gc_mode()) {
964 _young_list->reset_sampled_info();
965 assert( check_young_list_empty(false, false),
966 "young list should be empty at this point");
967 }
968 }
969
970 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
971 do_collection(true, clear_all_soft_refs, 0);
972 }
973
974 // This code is mostly copied from TenuredGeneration.
975 void
976 G1CollectedHeap::
977 resize_if_necessary_after_full_collection(size_t word_size) {
978 assert(MinHeapFreeRatio <= MaxHeapFreeRatio, "sanity check");
979
980 // Include the current allocation, if any, and bytes that will be
981 // pre-allocated to support collections, as "used".
982 const size_t used_after_gc = used();
983 const size_t capacity_after_gc = capacity();
984 const size_t free_after_gc = capacity_after_gc - used_after_gc;
985
986 // We don't have floating point command-line arguments
987 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100;
988 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
989 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100;
990 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
991
992 size_t minimum_desired_capacity = (size_t) (used_after_gc / maximum_used_percentage);
993 size_t maximum_desired_capacity = (size_t) (used_after_gc / minimum_used_percentage);
994
995 // Don't shrink less than the initial size.
996 minimum_desired_capacity =
997 MAX2(minimum_desired_capacity,
998 collector_policy()->initial_heap_byte_size());
999 maximum_desired_capacity =
1000 MAX2(maximum_desired_capacity,
1001 collector_policy()->initial_heap_byte_size());
1002
1003 // We are failing here because minimum_desired_capacity is
1004 assert(used_after_gc <= minimum_desired_capacity, "sanity check");
1005 assert(minimum_desired_capacity <= maximum_desired_capacity, "sanity check");
1006
1007 if (PrintGC && Verbose) {
1008 const double free_percentage = ((double)free_after_gc) / capacity();
1009 gclog_or_tty->print_cr("Computing new size after full GC ");
1010 gclog_or_tty->print_cr(" "
1011 " minimum_free_percentage: %6.2f",
1012 minimum_free_percentage);
1013 gclog_or_tty->print_cr(" "
1014 " maximum_free_percentage: %6.2f",
1015 maximum_free_percentage);
1016 gclog_or_tty->print_cr(" "
1017 " capacity: %6.1fK"
1018 " minimum_desired_capacity: %6.1fK"
1019 " maximum_desired_capacity: %6.1fK",
1020 capacity() / (double) K,
1021 minimum_desired_capacity / (double) K,
1022 maximum_desired_capacity / (double) K);
1023 gclog_or_tty->print_cr(" "
1024 " free_after_gc : %6.1fK"
1025 " used_after_gc : %6.1fK",
1026 free_after_gc / (double) K,
1027 used_after_gc / (double) K);
1028 gclog_or_tty->print_cr(" "
1029 " free_percentage: %6.2f",
1030 free_percentage);
1031 }
1032 if (capacity() < minimum_desired_capacity) {
1033 // Don't expand unless it's significant
1034 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1035 expand(expand_bytes);
1036 if (PrintGC && Verbose) {
1037 gclog_or_tty->print_cr(" expanding:"
1038 " minimum_desired_capacity: %6.1fK"
1039 " expand_bytes: %6.1fK",
1040 minimum_desired_capacity / (double) K,
1041 expand_bytes / (double) K);
1042 }
1043
1044 // No expansion, now see if we want to shrink
1045 } else if (capacity() > maximum_desired_capacity) {
1046 // Capacity too large, compute shrinking size
1047 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1048 shrink(shrink_bytes);
1049 if (PrintGC && Verbose) {
1050 gclog_or_tty->print_cr(" "
1051 " shrinking:"
1052 " initSize: %.1fK"
1053 " maximum_desired_capacity: %.1fK",
1054 collector_policy()->initial_heap_byte_size() / (double) K,
1055 maximum_desired_capacity / (double) K);
1056 gclog_or_tty->print_cr(" "
1057 " shrink_bytes: %.1fK",
1058 shrink_bytes / (double) K);
1059 }
1060 }
1061 }
1062
1063
1064 HeapWord*
1065 G1CollectedHeap::satisfy_failed_allocation(size_t word_size) {
1066 HeapWord* result = NULL;
1067
1068 // In a G1 heap, we're supposed to keep allocation from failing by
1069 // incremental pauses. Therefore, at least for now, we'll favor
1070 // expansion over collection. (This might change in the future if we can
1071 // do something smarter than full collection to satisfy a failed alloc.)
1072
1073 result = expand_and_allocate(word_size);
1074 if (result != NULL) {
1075 assert(is_in(result), "result not in heap");
1076 return result;
1077 }
1078
1079 // OK, I guess we have to try collection.
1080
1081 do_collection(false, false, word_size);
1082
1083 result = attempt_allocation(word_size, /*permit_collection_pause*/false);
1084
1085 if (result != NULL) {
1086 assert(is_in(result), "result not in heap");
1087 return result;
1088 }
1089
1090 // Try collecting soft references.
1091 do_collection(false, true, word_size);
1092 result = attempt_allocation(word_size, /*permit_collection_pause*/false);
1093 if (result != NULL) {
1094 assert(is_in(result), "result not in heap");
1095 return result;
1096 }
1097
1098 // What else? We might try synchronous finalization later. If the total
1099 // space available is large enough for the allocation, then a more
1100 // complete compaction phase than we've tried so far might be
1101 // appropriate.
1102 return NULL;
1103 }
1104
1105 // Attempting to expand the heap sufficiently
1106 // to support an allocation of the given "word_size". If
1107 // successful, perform the allocation and return the address of the
1108 // allocated block, or else "NULL".
1109
1110 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1111 size_t expand_bytes = word_size * HeapWordSize;
1112 if (expand_bytes < MinHeapDeltaBytes) {
1113 expand_bytes = MinHeapDeltaBytes;
1114 }
1115 expand(expand_bytes);
1116 assert(regions_accounted_for(), "Region leakage!");
1117 HeapWord* result = attempt_allocation(word_size, false /* permit_collection_pause */);
1118 return result;
1119 }
1120
1121 size_t G1CollectedHeap::free_region_if_totally_empty(HeapRegion* hr) {
1122 size_t pre_used = 0;
1123 size_t cleared_h_regions = 0;
1124 size_t freed_regions = 0;
1125 UncleanRegionList local_list;
1126 free_region_if_totally_empty_work(hr, pre_used, cleared_h_regions,
1127 freed_regions, &local_list);
1128
1129 finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
1130 &local_list);
1131 return pre_used;
1132 }
1133
1134 void
1135 G1CollectedHeap::free_region_if_totally_empty_work(HeapRegion* hr,
1136 size_t& pre_used,
1137 size_t& cleared_h,
1138 size_t& freed_regions,
1139 UncleanRegionList* list,
1140 bool par) {
1141 assert(!hr->continuesHumongous(), "should have filtered these out");
1142 size_t res = 0;
1143 if (!hr->popular() && hr->used() > 0 && hr->garbage_bytes() == hr->used()) {
1144 if (!hr->is_young()) {
1145 if (G1PolicyVerbose > 0)
1146 gclog_or_tty->print_cr("Freeing empty region "PTR_FORMAT "(" SIZE_FORMAT " bytes)"
1147 " during cleanup", hr, hr->used());
1148 free_region_work(hr, pre_used, cleared_h, freed_regions, list, par);
1149 }
1150 }
1151 }
1152
1153 // FIXME: both this and shrink could probably be more efficient by
1154 // doing one "VirtualSpace::expand_by" call rather than several.
1155 void G1CollectedHeap::expand(size_t expand_bytes) {
1156 size_t old_mem_size = _g1_storage.committed_size();
1157 // We expand by a minimum of 1K.
1158 expand_bytes = MAX2(expand_bytes, (size_t)K);
1159 size_t aligned_expand_bytes =
1160 ReservedSpace::page_align_size_up(expand_bytes);
1161 aligned_expand_bytes = align_size_up(aligned_expand_bytes,
1162 HeapRegion::GrainBytes);
1163 expand_bytes = aligned_expand_bytes;
1164 while (expand_bytes > 0) {
1165 HeapWord* base = (HeapWord*)_g1_storage.high();
1166 // Commit more storage.
1167 bool successful = _g1_storage.expand_by(HeapRegion::GrainBytes);
1168 if (!successful) {
1169 expand_bytes = 0;
1170 } else {
1171 expand_bytes -= HeapRegion::GrainBytes;
1172 // Expand the committed region.
1173 HeapWord* high = (HeapWord*) _g1_storage.high();
1174 _g1_committed.set_end(high);
1175 // Create a new HeapRegion.
1176 MemRegion mr(base, high);
1177 bool is_zeroed = !_g1_max_committed.contains(base);
1178 HeapRegion* hr = new HeapRegion(_bot_shared, mr, is_zeroed);
1179
1180 // Now update max_committed if necessary.
1181 _g1_max_committed.set_end(MAX2(_g1_max_committed.end(), high));
1182
1183 // Add it to the HeapRegionSeq.
1184 _hrs->insert(hr);
1185 // Set the zero-fill state, according to whether it's already
1186 // zeroed.
1187 {
1188 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
1189 if (is_zeroed) {
1190 hr->set_zero_fill_complete();
1191 put_free_region_on_list_locked(hr);
1192 } else {
1193 hr->set_zero_fill_needed();
1194 put_region_on_unclean_list_locked(hr);
1195 }
1196 }
1197 _free_regions++;
1198 // And we used up an expansion region to create it.
1199 _expansion_regions--;
1200 // Tell the cardtable about it.
1201 Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1202 // And the offset table as well.
1203 _bot_shared->resize(_g1_committed.word_size());
1204 }
1205 }
1206 if (Verbose && PrintGC) {
1207 size_t new_mem_size = _g1_storage.committed_size();
1208 gclog_or_tty->print_cr("Expanding garbage-first heap from %ldK by %ldK to %ldK",
1209 old_mem_size/K, aligned_expand_bytes/K,
1210 new_mem_size/K);
1211 }
1212 }
1213
1214 void G1CollectedHeap::shrink_helper(size_t shrink_bytes)
1215 {
1216 size_t old_mem_size = _g1_storage.committed_size();
1217 size_t aligned_shrink_bytes =
1218 ReservedSpace::page_align_size_down(shrink_bytes);
1219 aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
1220 HeapRegion::GrainBytes);
1221 size_t num_regions_deleted = 0;
1222 MemRegion mr = _hrs->shrink_by(aligned_shrink_bytes, num_regions_deleted);
1223
1224 assert(mr.end() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
1225 if (mr.byte_size() > 0)
1226 _g1_storage.shrink_by(mr.byte_size());
1227 assert(mr.start() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
1228
1229 _g1_committed.set_end(mr.start());
1230 _free_regions -= num_regions_deleted;
1231 _expansion_regions += num_regions_deleted;
1232
1233 // Tell the cardtable about it.
1234 Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1235
1236 // And the offset table as well.
1237 _bot_shared->resize(_g1_committed.word_size());
1238
1239 HeapRegionRemSet::shrink_heap(n_regions());
1240
1241 if (Verbose && PrintGC) {
1242 size_t new_mem_size = _g1_storage.committed_size();
1243 gclog_or_tty->print_cr("Shrinking garbage-first heap from %ldK by %ldK to %ldK",
1244 old_mem_size/K, aligned_shrink_bytes/K,
1245 new_mem_size/K);
1246 }
1247 }
1248
1249 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1250 release_gc_alloc_regions();
1251 tear_down_region_lists(); // We will rebuild them in a moment.
1252 shrink_helper(shrink_bytes);
1253 rebuild_region_lists();
1254 }
1255
1256 // Public methods.
1257
1258 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
1259 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
1260 #endif // _MSC_VER
1261
1262
1263 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
1264 SharedHeap(policy_),
1265 _g1_policy(policy_),
1266 _ref_processor(NULL),
1267 _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
1268 _bot_shared(NULL),
1269 _par_alloc_during_gc_lock(Mutex::leaf, "par alloc during GC lock"),
1270 _objs_with_preserved_marks(NULL), _preserved_marks_of_objs(NULL),
1271 _evac_failure_scan_stack(NULL) ,
1272 _mark_in_progress(false),
1273 _cg1r(NULL), _czft(NULL), _summary_bytes_used(0),
1274 _cur_alloc_region(NULL),
1275 _refine_cte_cl(NULL),
1276 _free_region_list(NULL), _free_region_list_size(0),
1277 _free_regions(0),
1278 _popular_object_boundary(NULL),
1279 _cur_pop_hr_index(0),
1280 _popular_regions_to_be_evacuated(NULL),
1281 _pop_obj_rc_at_copy(),
1282 _full_collection(false),
1283 _unclean_region_list(),
1284 _unclean_regions_coming(false),
1285 _young_list(new YoungList(this)),
1286 _gc_time_stamp(0),
1287 _surviving_young_words(NULL)
1288 {
1289 _g1h = this; // To catch bugs.
1290 if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
1291 vm_exit_during_initialization("Failed necessary allocation.");
1292 }
1293 int n_queues = MAX2((int)ParallelGCThreads, 1);
1294 _task_queues = new RefToScanQueueSet(n_queues);
1295
1296 int n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
1297 assert(n_rem_sets > 0, "Invariant.");
1298
1299 HeapRegionRemSetIterator** iter_arr =
1300 NEW_C_HEAP_ARRAY(HeapRegionRemSetIterator*, n_queues);
1301 for (int i = 0; i < n_queues; i++) {
1302 iter_arr[i] = new HeapRegionRemSetIterator();
1303 }
1304 _rem_set_iterator = iter_arr;
1305
1306 for (int i = 0; i < n_queues; i++) {
1307 RefToScanQueue* q = new RefToScanQueue();
1308 q->initialize();
1309 _task_queues->register_queue(i, q);
1310 }
1311
1312 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
1313 _gc_alloc_regions[ap] = NULL;
1314 _gc_alloc_region_counts[ap] = 0;
1315 }
1316 guarantee(_task_queues != NULL, "task_queues allocation failure.");
1317 }
1318
1319 jint G1CollectedHeap::initialize() {
1320 os::enable_vtime();
1321
1322 // Necessary to satisfy locking discipline assertions.
1323
1324 MutexLocker x(Heap_lock);
1325
1326 // While there are no constraints in the GC code that HeapWordSize
1327 // be any particular value, there are multiple other areas in the
1328 // system which believe this to be true (e.g. oop->object_size in some
1329 // cases incorrectly returns the size in wordSize units rather than
1330 // HeapWordSize).
1331 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1332
1333 size_t init_byte_size = collector_policy()->initial_heap_byte_size();
1334 size_t max_byte_size = collector_policy()->max_heap_byte_size();
1335
1336 // Ensure that the sizes are properly aligned.
1337 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1338 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
1339
1340 // We allocate this in any case, but only do no work if the command line
1341 // param is off.
1342 _cg1r = new ConcurrentG1Refine();
1343
1344 // Reserve the maximum.
1345 PermanentGenerationSpec* pgs = collector_policy()->permanent_generation();
1346 // Includes the perm-gen.
1347 ReservedSpace heap_rs(max_byte_size + pgs->max_size(),
1348 HeapRegion::GrainBytes,
1349 false /*ism*/);
1350
1351 if (!heap_rs.is_reserved()) {
1352 vm_exit_during_initialization("Could not reserve enough space for object heap");
1353 return JNI_ENOMEM;
1354 }
1355
1356 // It is important to do this in a way such that concurrent readers can't
1357 // temporarily think somethings in the heap. (I've actually seen this
1358 // happen in asserts: DLD.)
1359 _reserved.set_word_size(0);
1360 _reserved.set_start((HeapWord*)heap_rs.base());
1361 _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
1362
1363 _expansion_regions = max_byte_size/HeapRegion::GrainBytes;
1364
1365 _num_humongous_regions = 0;
1366
1367 // Create the gen rem set (and barrier set) for the entire reserved region.
1368 _rem_set = collector_policy()->create_rem_set(_reserved, 2);
1369 set_barrier_set(rem_set()->bs());
1370 if (barrier_set()->is_a(BarrierSet::ModRef)) {
1371 _mr_bs = (ModRefBarrierSet*)_barrier_set;
1372 } else {
1373 vm_exit_during_initialization("G1 requires a mod ref bs.");
1374 return JNI_ENOMEM;
1375 }
1376
1377 // Also create a G1 rem set.
1378 if (G1UseHRIntoRS) {
1379 if (mr_bs()->is_a(BarrierSet::CardTableModRef)) {
1380 _g1_rem_set = new HRInto_G1RemSet(this, (CardTableModRefBS*)mr_bs());
1381 } else {
1382 vm_exit_during_initialization("G1 requires a cardtable mod ref bs.");
1383 return JNI_ENOMEM;
1384 }
1385 } else {
1386 _g1_rem_set = new StupidG1RemSet(this);
1387 }
1388
1389 // Carve out the G1 part of the heap.
1390
1391 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size);
1392 _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
1393 g1_rs.size()/HeapWordSize);
1394 ReservedSpace perm_gen_rs = heap_rs.last_part(max_byte_size);
1395
1396 _perm_gen = pgs->init(perm_gen_rs, pgs->init_size(), rem_set());
1397
1398 _g1_storage.initialize(g1_rs, 0);
1399 _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
1400 _g1_max_committed = _g1_committed;
1401 _hrs = new HeapRegionSeq();
1402 guarantee(_hrs != NULL, "Couldn't allocate HeapRegionSeq");
1403 guarantee(_cur_alloc_region == NULL, "from constructor");
1404
1405 _bot_shared = new G1BlockOffsetSharedArray(_reserved,
1406 heap_word_size(init_byte_size));
1407
1408 _g1h = this;
1409
1410 // Create the ConcurrentMark data structure and thread.
1411 // (Must do this late, so that "max_regions" is defined.)
1412 _cm = new ConcurrentMark(heap_rs, (int) max_regions());
1413 _cmThread = _cm->cmThread();
1414
1415 // ...and the concurrent zero-fill thread, if necessary.
1416 if (G1ConcZeroFill) {
1417 _czft = new ConcurrentZFThread();
1418 }
1419
1420
1421
1422 // Allocate the popular regions; take them off free lists.
1423 size_t pop_byte_size = G1NumPopularRegions * HeapRegion::GrainBytes;
1424 expand(pop_byte_size);
1425 _popular_object_boundary =
1426 _g1_reserved.start() + (G1NumPopularRegions * HeapRegion::GrainWords);
1427 for (int i = 0; i < G1NumPopularRegions; i++) {
1428 HeapRegion* hr = newAllocRegion(HeapRegion::GrainWords);
1429 // assert(hr != NULL && hr->bottom() < _popular_object_boundary,
1430 // "Should be enough, and all should be below boundary.");
1431 hr->set_popular(true);
1432 }
1433 assert(_cur_pop_hr_index == 0, "Start allocating at the first region.");
1434
1435 // Initialize the from_card cache structure of HeapRegionRemSet.
1436 HeapRegionRemSet::init_heap(max_regions());
1437
1438 // Now expand into the rest of the initial heap size.
1439 expand(init_byte_size - pop_byte_size);
1440
1441 // Perform any initialization actions delegated to the policy.
1442 g1_policy()->init();
1443
1444 g1_policy()->note_start_of_mark_thread();
1445
1446 _refine_cte_cl =
1447 new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
1448 g1_rem_set(),
1449 concurrent_g1_refine());
1450 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
1451
1452 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
1453 SATB_Q_FL_lock,
1454 0,
1455 Shared_SATB_Q_lock);
1456 if (G1RSBarrierUseQueue) {
1457 JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
1458 DirtyCardQ_FL_lock,
1459 G1DirtyCardQueueMax,
1460 Shared_DirtyCardQ_lock);
1461 }
1462 // In case we're keeping closure specialization stats, initialize those
1463 // counts and that mechanism.
1464 SpecializationStats::clear();
1465
1466 _gc_alloc_region_list = NULL;
1467
1468 // Do later initialization work for concurrent refinement.
1469 _cg1r->init();
1470
1471 const char* group_names[] = { "CR", "ZF", "CM", "CL" };
1472 GCOverheadReporter::initGCOverheadReporter(4, group_names);
1473
1474 return JNI_OK;
1475 }
1476
1477 void G1CollectedHeap::ref_processing_init() {
1478 SharedHeap::ref_processing_init();
1479 MemRegion mr = reserved_region();
1480 _ref_processor = ReferenceProcessor::create_ref_processor(
1481 mr, // span
1482 false, // Reference discovery is not atomic
1483 // (though it shouldn't matter here.)
1484 true, // mt_discovery
1485 NULL, // is alive closure: need to fill this in for efficiency
1486 ParallelGCThreads,
1487 ParallelRefProcEnabled,
1488 true); // Setting next fields of discovered
1489 // lists requires a barrier.
1490 }
1491
1492 size_t G1CollectedHeap::capacity() const {
1493 return _g1_committed.byte_size();
1494 }
1495
1496 void G1CollectedHeap::iterate_dirty_card_closure(bool concurrent,
1497 int worker_i) {
1498 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
1499 int n_completed_buffers = 0;
1500 while (dcqs.apply_closure_to_completed_buffer(worker_i, 0, true)) {
1501 n_completed_buffers++;
1502 }
1503 g1_policy()->record_update_rs_processed_buffers(worker_i,
1504 (double) n_completed_buffers);
1505 dcqs.clear_n_completed_buffers();
1506 // Finish up the queue...
1507 if (worker_i == 0) concurrent_g1_refine()->clean_up_cache(worker_i,
1508 g1_rem_set());
1509 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
1510 }
1511
1512
1513 // Computes the sum of the storage used by the various regions.
1514
1515 size_t G1CollectedHeap::used() const {
1516 assert(Heap_lock->owner() != NULL,
1517 "Should be owned on this thread's behalf.");
1518 size_t result = _summary_bytes_used;
1519 if (_cur_alloc_region != NULL)
1520 result += _cur_alloc_region->used();
1521 return result;
1522 }
1523
1524 class SumUsedClosure: public HeapRegionClosure {
1525 size_t _used;
1526 public:
1527 SumUsedClosure() : _used(0) {}
1528 bool doHeapRegion(HeapRegion* r) {
1529 if (!r->continuesHumongous()) {
1530 _used += r->used();
1531 }
1532 return false;
1533 }
1534 size_t result() { return _used; }
1535 };
1536
1537 size_t G1CollectedHeap::recalculate_used() const {
1538 SumUsedClosure blk;
1539 _hrs->iterate(&blk);
1540 return blk.result();
1541 }
1542
1543 #ifndef PRODUCT
1544 class SumUsedRegionsClosure: public HeapRegionClosure {
1545 size_t _num;
1546 public:
1547 // _num is set to 1 to account for the popular region
1548 SumUsedRegionsClosure() : _num(G1NumPopularRegions) {}
1549 bool doHeapRegion(HeapRegion* r) {
1550 if (r->continuesHumongous() || r->used() > 0 || r->is_gc_alloc_region()) {
1551 _num += 1;
1552 }
1553 return false;
1554 }
1555 size_t result() { return _num; }
1556 };
1557
1558 size_t G1CollectedHeap::recalculate_used_regions() const {
1559 SumUsedRegionsClosure blk;
1560 _hrs->iterate(&blk);
1561 return blk.result();
1562 }
1563 #endif // PRODUCT
1564
1565 size_t G1CollectedHeap::unsafe_max_alloc() {
1566 if (_free_regions > 0) return HeapRegion::GrainBytes;
1567 // otherwise, is there space in the current allocation region?
1568
1569 // We need to store the current allocation region in a local variable
1570 // here. The problem is that this method doesn't take any locks and
1571 // there may be other threads which overwrite the current allocation
1572 // region field. attempt_allocation(), for example, sets it to NULL
1573 // and this can happen *after* the NULL check here but before the call
1574 // to free(), resulting in a SIGSEGV. Note that this doesn't appear
1575 // to be a problem in the optimized build, since the two loads of the
1576 // current allocation region field are optimized away.
1577 HeapRegion* car = _cur_alloc_region;
1578
1579 // FIXME: should iterate over all regions?
1580 if (car == NULL) {
1581 return 0;
1582 }
1583 return car->free();
1584 }
1585
1586 void G1CollectedHeap::collect(GCCause::Cause cause) {
1587 // The caller doesn't have the Heap_lock
1588 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
1589 MutexLocker ml(Heap_lock);
1590 collect_locked(cause);
1591 }
1592
1593 void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
1594 assert(Thread::current()->is_VM_thread(), "Precondition#1");
1595 assert(Heap_lock->is_locked(), "Precondition#2");
1596 GCCauseSetter gcs(this, cause);
1597 switch (cause) {
1598 case GCCause::_heap_inspection:
1599 case GCCause::_heap_dump: {
1600 HandleMark hm;
1601 do_full_collection(false); // don't clear all soft refs
1602 break;
1603 }
1604 default: // XXX FIX ME
1605 ShouldNotReachHere(); // Unexpected use of this function
1606 }
1607 }
1608
1609
1610 void G1CollectedHeap::collect_locked(GCCause::Cause cause) {
1611 // Don't want to do a GC until cleanup is completed.
1612 wait_for_cleanup_complete();
1613
1614 // Read the GC count while holding the Heap_lock
1615 int gc_count_before = SharedHeap::heap()->total_collections();
1616 {
1617 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back
1618 VM_G1CollectFull op(gc_count_before, cause);
1619 VMThread::execute(&op);
1620 }
1621 }
1622
1623 bool G1CollectedHeap::is_in(const void* p) const {
1624 if (_g1_committed.contains(p)) {
1625 HeapRegion* hr = _hrs->addr_to_region(p);
1626 return hr->is_in(p);
1627 } else {
1628 return _perm_gen->as_gen()->is_in(p);
1629 }
1630 }
1631
1632 // Iteration functions.
1633
1634 // Iterates an OopClosure over all ref-containing fields of objects
1635 // within a HeapRegion.
1636
1637 class IterateOopClosureRegionClosure: public HeapRegionClosure {
1638 MemRegion _mr;
1639 OopClosure* _cl;
1640 public:
1641 IterateOopClosureRegionClosure(MemRegion mr, OopClosure* cl)
1642 : _mr(mr), _cl(cl) {}
1643 bool doHeapRegion(HeapRegion* r) {
1644 if (! r->continuesHumongous()) {
1645 r->oop_iterate(_cl);
1646 }
1647 return false;
1648 }
1649 };
1650
1651 void G1CollectedHeap::oop_iterate(OopClosure* cl) {
1652 IterateOopClosureRegionClosure blk(_g1_committed, cl);
1653 _hrs->iterate(&blk);
1654 }
1655
1656 void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl) {
1657 IterateOopClosureRegionClosure blk(mr, cl);
1658 _hrs->iterate(&blk);
1659 }
1660
1661 // Iterates an ObjectClosure over all objects within a HeapRegion.
1662
1663 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
1664 ObjectClosure* _cl;
1665 public:
1666 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
1667 bool doHeapRegion(HeapRegion* r) {
1668 if (! r->continuesHumongous()) {
1669 r->object_iterate(_cl);
1670 }
1671 return false;
1672 }
1673 };
1674
1675 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
1676 IterateObjectClosureRegionClosure blk(cl);
1677 _hrs->iterate(&blk);
1678 }
1679
1680 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
1681 // FIXME: is this right?
1682 guarantee(false, "object_iterate_since_last_GC not supported by G1 heap");
1683 }
1684
1685 // Calls a SpaceClosure on a HeapRegion.
1686
1687 class SpaceClosureRegionClosure: public HeapRegionClosure {
1688 SpaceClosure* _cl;
1689 public:
1690 SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
1691 bool doHeapRegion(HeapRegion* r) {
1692 _cl->do_space(r);
1693 return false;
1694 }
1695 };
1696
1697 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
1698 SpaceClosureRegionClosure blk(cl);
1699 _hrs->iterate(&blk);
1700 }
1701
1702 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) {
1703 _hrs->iterate(cl);
1704 }
1705
1706 void G1CollectedHeap::heap_region_iterate_from(HeapRegion* r,
1707 HeapRegionClosure* cl) {
1708 _hrs->iterate_from(r, cl);
1709 }
1710
1711 void
1712 G1CollectedHeap::heap_region_iterate_from(int idx, HeapRegionClosure* cl) {
1713 _hrs->iterate_from(idx, cl);
1714 }
1715
1716 HeapRegion* G1CollectedHeap::region_at(size_t idx) { return _hrs->at(idx); }
1717
1718 void
1719 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
1720 int worker,
1721 jint claim_value) {
1722 const size_t regions = n_regions();
1723 const size_t worker_num = (ParallelGCThreads > 0 ? ParallelGCThreads : 1);
1724 // try to spread out the starting points of the workers
1725 const size_t start_index = regions / worker_num * (size_t) worker;
1726
1727 // each worker will actually look at all regions
1728 for (size_t count = 0; count < regions; ++count) {
1729 const size_t index = (start_index + count) % regions;
1730 assert(0 <= index && index < regions, "sanity");
1731 HeapRegion* r = region_at(index);
1732 // we'll ignore "continues humongous" regions (we'll process them
1733 // when we come across their corresponding "start humongous"
1734 // region) and regions already claimed
1735 if (r->claim_value() == claim_value || r->continuesHumongous()) {
1736 continue;
1737 }
1738 // OK, try to claim it
1739 if (r->claimHeapRegion(claim_value)) {
1740 // success!
1741 assert(!r->continuesHumongous(), "sanity");
1742 if (r->startsHumongous()) {
1743 // If the region is "starts humongous" we'll iterate over its
1744 // "continues humongous" first; in fact we'll do them
1745 // first. The order is important. In on case, calling the
1746 // closure on the "starts humongous" region might de-allocate
1747 // and clear all its "continues humongous" regions and, as a
1748 // result, we might end up processing them twice. So, we'll do
1749 // them first (notice: most closures will ignore them anyway) and
1750 // then we'll do the "starts humongous" region.
1751 for (size_t ch_index = index + 1; ch_index < regions; ++ch_index) {
1752 HeapRegion* chr = region_at(ch_index);
1753
1754 // if the region has already been claimed or it's not
1755 // "continues humongous" we're done
1756 if (chr->claim_value() == claim_value ||
1757 !chr->continuesHumongous()) {
1758 break;
1759 }
1760
1761 // Noone should have claimed it directly. We can given
1762 // that we claimed its "starts humongous" region.
1763 assert(chr->claim_value() != claim_value, "sanity");
1764 assert(chr->humongous_start_region() == r, "sanity");
1765
1766 if (chr->claimHeapRegion(claim_value)) {
1767 // we should always be able to claim it; noone else should
1768 // be trying to claim this region
1769
1770 bool res2 = cl->doHeapRegion(chr);
1771 assert(!res2, "Should not abort");
1772
1773 // Right now, this holds (i.e., no closure that actually
1774 // does something with "continues humongous" regions
1775 // clears them). We might have to weaken it in the future,
1776 // but let's leave these two asserts here for extra safety.
1777 assert(chr->continuesHumongous(), "should still be the case");
1778 assert(chr->humongous_start_region() == r, "sanity");
1779 } else {
1780 guarantee(false, "we should not reach here");
1781 }
1782 }
1783 }
1784
1785 assert(!r->continuesHumongous(), "sanity");
1786 bool res = cl->doHeapRegion(r);
1787 assert(!res, "Should not abort");
1788 }
1789 }
1790 }
1791
1792 #ifdef ASSERT
1793 // This checks whether all regions in the heap have the correct claim
1794 // value. I also piggy-backed on this a check to ensure that the
1795 // humongous_start_region() information on "continues humongous"
1796 // regions is correct.
1797
1798 class CheckClaimValuesClosure : public HeapRegionClosure {
1799 private:
1800 jint _claim_value;
1801 size_t _failures;
1802 HeapRegion* _sh_region;
1803 public:
1804 CheckClaimValuesClosure(jint claim_value) :
1805 _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
1806 bool doHeapRegion(HeapRegion* r) {
1807 if (r->claim_value() != _claim_value) {
1808 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
1809 "claim value = %d, should be %d",
1810 r->bottom(), r->end(), r->claim_value(),
1811 _claim_value);
1812 ++_failures;
1813 }
1814 if (!r->isHumongous()) {
1815 _sh_region = NULL;
1816 } else if (r->startsHumongous()) {
1817 _sh_region = r;
1818 } else if (r->continuesHumongous()) {
1819 if (r->humongous_start_region() != _sh_region) {
1820 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
1821 "HS = "PTR_FORMAT", should be "PTR_FORMAT,
1822 r->bottom(), r->end(),
1823 r->humongous_start_region(),
1824 _sh_region);
1825 ++_failures;
1826 }
1827 }
1828 return false;
1829 }
1830 size_t failures() {
1831 return _failures;
1832 }
1833 };
1834
1835 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
1836 CheckClaimValuesClosure cl(claim_value);
1837 heap_region_iterate(&cl);
1838 return cl.failures() == 0;
1839 }
1840 #endif // ASSERT
1841
1842 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
1843 HeapRegion* r = g1_policy()->collection_set();
1844 while (r != NULL) {
1845 HeapRegion* next = r->next_in_collection_set();
1846 if (cl->doHeapRegion(r)) {
1847 cl->incomplete();
1848 return;
1849 }
1850 r = next;
1851 }
1852 }
1853
1854 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
1855 HeapRegionClosure *cl) {
1856 assert(r->in_collection_set(),
1857 "Start region must be a member of the collection set.");
1858 HeapRegion* cur = r;
1859 while (cur != NULL) {
1860 HeapRegion* next = cur->next_in_collection_set();
1861 if (cl->doHeapRegion(cur) && false) {
1862 cl->incomplete();
1863 return;
1864 }
1865 cur = next;
1866 }
1867 cur = g1_policy()->collection_set();
1868 while (cur != r) {
1869 HeapRegion* next = cur->next_in_collection_set();
1870 if (cl->doHeapRegion(cur) && false) {
1871 cl->incomplete();
1872 return;
1873 }
1874 cur = next;
1875 }
1876 }
1877
1878 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
1879 return _hrs->length() > 0 ? _hrs->at(0) : NULL;
1880 }
1881
1882
1883 Space* G1CollectedHeap::space_containing(const void* addr) const {
1884 Space* res = heap_region_containing(addr);
1885 if (res == NULL)
1886 res = perm_gen()->space_containing(addr);
1887 return res;
1888 }
1889
1890 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
1891 Space* sp = space_containing(addr);
1892 if (sp != NULL) {
1893 return sp->block_start(addr);
1894 }
1895 return NULL;
1896 }
1897
1898 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
1899 Space* sp = space_containing(addr);
1900 assert(sp != NULL, "block_size of address outside of heap");
1901 return sp->block_size(addr);
1902 }
1903
1904 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
1905 Space* sp = space_containing(addr);
1906 return sp->block_is_obj(addr);
1907 }
1908
1909 bool G1CollectedHeap::supports_tlab_allocation() const {
1910 return true;
1911 }
1912
1913 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
1914 return HeapRegion::GrainBytes;
1915 }
1916
1917 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
1918 // Return the remaining space in the cur alloc region, but not less than
1919 // the min TLAB size.
1920 // Also, no more than half the region size, since we can't allow tlabs to
1921 // grow big enough to accomodate humongous objects.
1922
1923 // We need to story it locally, since it might change between when we
1924 // test for NULL and when we use it later.
1925 ContiguousSpace* cur_alloc_space = _cur_alloc_region;
1926 if (cur_alloc_space == NULL) {
1927 return HeapRegion::GrainBytes/2;
1928 } else {
1929 return MAX2(MIN2(cur_alloc_space->free(),
1930 (size_t)(HeapRegion::GrainBytes/2)),
1931 (size_t)MinTLABSize);
1932 }
1933 }
1934
1935 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t size) {
1936 bool dummy;
1937 return G1CollectedHeap::mem_allocate(size, false, true, &dummy);
1938 }
1939
1940 bool G1CollectedHeap::allocs_are_zero_filled() {
1941 return false;
1942 }
1943
1944 size_t G1CollectedHeap::large_typearray_limit() {
1945 // FIXME
1946 return HeapRegion::GrainBytes/HeapWordSize;
1947 }
1948
1949 size_t G1CollectedHeap::max_capacity() const {
1950 return _g1_committed.byte_size();
1951 }
1952
1953 jlong G1CollectedHeap::millis_since_last_gc() {
1954 // assert(false, "NYI");
1955 return 0;
1956 }
1957
1958
1959 void G1CollectedHeap::prepare_for_verify() {
1960 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1961 ensure_parsability(false);
1962 }
1963 g1_rem_set()->prepare_for_verify();
1964 }
1965
1966 class VerifyLivenessOopClosure: public OopClosure {
1967 G1CollectedHeap* g1h;
1968 public:
1969 VerifyLivenessOopClosure(G1CollectedHeap* _g1h) {
1970 g1h = _g1h;
1971 }
1972 void do_oop(narrowOop *p) {
1973 guarantee(false, "NYI");
1974 }
1975 void do_oop(oop *p) {
1976 oop obj = *p;
1977 assert(obj == NULL || !g1h->is_obj_dead(obj),
1978 "Dead object referenced by a not dead object");
1979 }
1980 };
1981
1982 class VerifyObjsInRegionClosure: public ObjectClosure {
1983 G1CollectedHeap* _g1h;
1984 size_t _live_bytes;
1985 HeapRegion *_hr;
1986 public:
1987 VerifyObjsInRegionClosure(HeapRegion *hr) : _live_bytes(0), _hr(hr) {
1988 _g1h = G1CollectedHeap::heap();
1989 }
1990 void do_object(oop o) {
1991 VerifyLivenessOopClosure isLive(_g1h);
1992 assert(o != NULL, "Huh?");
1993 if (!_g1h->is_obj_dead(o)) {
1994 o->oop_iterate(&isLive);
1995 if (!_hr->obj_allocated_since_prev_marking(o))
1996 _live_bytes += (o->size() * HeapWordSize);
1997 }
1998 }
1999 size_t live_bytes() { return _live_bytes; }
2000 };
2001
2002 class PrintObjsInRegionClosure : public ObjectClosure {
2003 HeapRegion *_hr;
2004 G1CollectedHeap *_g1;
2005 public:
2006 PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
2007 _g1 = G1CollectedHeap::heap();
2008 };
2009
2010 void do_object(oop o) {
2011 if (o != NULL) {
2012 HeapWord *start = (HeapWord *) o;
2013 size_t word_sz = o->size();
2014 gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
2015 " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
2016 (void*) o, word_sz,
2017 _g1->isMarkedPrev(o),
2018 _g1->isMarkedNext(o),
2019 _hr->obj_allocated_since_prev_marking(o));
2020 HeapWord *end = start + word_sz;
2021 HeapWord *cur;
2022 int *val;
2023 for (cur = start; cur < end; cur++) {
2024 val = (int *) cur;
2025 gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
2026 }
2027 }
2028 }
2029 };
2030
2031 class VerifyRegionClosure: public HeapRegionClosure {
2032 public:
2033 bool _allow_dirty;
2034 VerifyRegionClosure(bool allow_dirty)
2035 : _allow_dirty(allow_dirty) {}
2036 bool doHeapRegion(HeapRegion* r) {
2037 guarantee(r->claim_value() == 0, "Should be unclaimed at verify points.");
2038 if (r->isHumongous()) {
2039 if (r->startsHumongous()) {
2040 // Verify the single H object.
2041 oop(r->bottom())->verify();
2042 size_t word_sz = oop(r->bottom())->size();
2043 guarantee(r->top() == r->bottom() + word_sz,
2044 "Only one object in a humongous region");
2045 }
2046 } else {
2047 VerifyObjsInRegionClosure not_dead_yet_cl(r);
2048 r->verify(_allow_dirty);
2049 r->object_iterate(&not_dead_yet_cl);
2050 guarantee(r->max_live_bytes() >= not_dead_yet_cl.live_bytes(),
2051 "More live objects than counted in last complete marking.");
2052 }
2053 return false;
2054 }
2055 };
2056
2057 class VerifyRootsClosure: public OopsInGenClosure {
2058 private:
2059 G1CollectedHeap* _g1h;
2060 bool _failures;
2061
2062 public:
2063 VerifyRootsClosure() :
2064 _g1h(G1CollectedHeap::heap()), _failures(false) { }
2065
2066 bool failures() { return _failures; }
2067
2068 void do_oop(narrowOop* p) {
2069 guarantee(false, "NYI");
2070 }
2071
2072 void do_oop(oop* p) {
2073 oop obj = *p;
2074 if (obj != NULL) {
2075 if (_g1h->is_obj_dead(obj)) {
2076 gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
2077 "points to dead obj "PTR_FORMAT, p, (void*) obj);
2078 obj->print_on(gclog_or_tty);
2079 _failures = true;
2080 }
2081 }
2082 }
2083 };
2084
2085 void G1CollectedHeap::verify(bool allow_dirty, bool silent) {
2086 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2087 if (!silent) { gclog_or_tty->print("roots "); }
2088 VerifyRootsClosure rootsCl;
2089 process_strong_roots(false,
2090 SharedHeap::SO_AllClasses,
2091 &rootsCl,
2092 &rootsCl);
2093 rem_set()->invalidate(perm_gen()->used_region(), false);
2094 if (!silent) { gclog_or_tty->print("heapRegions "); }
2095 VerifyRegionClosure blk(allow_dirty);
2096 _hrs->iterate(&blk);
2097 if (!silent) gclog_or_tty->print("remset ");
2098 rem_set()->verify();
2099 guarantee(!rootsCl.failures(), "should not have had failures");
2100 } else {
2101 if (!silent) gclog_or_tty->print("(SKIPPING roots, heapRegions, remset) ");
2102 }
2103 }
2104
2105 class PrintRegionClosure: public HeapRegionClosure {
2106 outputStream* _st;
2107 public:
2108 PrintRegionClosure(outputStream* st) : _st(st) {}
2109 bool doHeapRegion(HeapRegion* r) {
2110 r->print_on(_st);
2111 return false;
2112 }
2113 };
2114
2115 void G1CollectedHeap::print() const { print_on(gclog_or_tty); }
2116
2117 void G1CollectedHeap::print_on(outputStream* st) const {
2118 PrintRegionClosure blk(st);
2119 _hrs->iterate(&blk);
2120 }
2121
2122 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
2123 if (ParallelGCThreads > 0) {
2124 workers()->print_worker_threads();
2125 }
2126 st->print("\"G1 concurrent mark GC Thread\" ");
2127 _cmThread->print();
2128 st->cr();
2129 st->print("\"G1 concurrent refinement GC Thread\" ");
2130 _cg1r->cg1rThread()->print_on(st);
2131 st->cr();
2132 st->print("\"G1 zero-fill GC Thread\" ");
2133 _czft->print_on(st);
2134 st->cr();
2135 }
2136
2137 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2138 if (ParallelGCThreads > 0) {
2139 workers()->threads_do(tc);
2140 }
2141 tc->do_thread(_cmThread);
2142 tc->do_thread(_cg1r->cg1rThread());
2143 tc->do_thread(_czft);
2144 }
2145
2146 void G1CollectedHeap::print_tracing_info() const {
2147 concurrent_g1_refine()->print_final_card_counts();
2148
2149 // We'll overload this to mean "trace GC pause statistics."
2150 if (TraceGen0Time || TraceGen1Time) {
2151 // The "G1CollectorPolicy" is keeping track of these stats, so delegate
2152 // to that.
2153 g1_policy()->print_tracing_info();
2154 }
2155 if (SummarizeG1RSStats) {
2156 g1_rem_set()->print_summary_info();
2157 }
2158 if (SummarizeG1ConcMark) {
2159 concurrent_mark()->print_summary_info();
2160 }
2161 if (SummarizeG1ZFStats) {
2162 ConcurrentZFThread::print_summary_info();
2163 }
2164 if (G1SummarizePopularity) {
2165 print_popularity_summary_info();
2166 }
2167 g1_policy()->print_yg_surv_rate_info();
2168
2169 GCOverheadReporter::printGCOverhead();
2170
2171 SpecializationStats::print();
2172 }
2173
2174
2175 int G1CollectedHeap::addr_to_arena_id(void* addr) const {
2176 HeapRegion* hr = heap_region_containing(addr);
2177 if (hr == NULL) {
2178 return 0;
2179 } else {
2180 return 1;
2181 }
2182 }
2183
2184 G1CollectedHeap* G1CollectedHeap::heap() {
2185 assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
2186 "not a garbage-first heap");
2187 return _g1h;
2188 }
2189
2190 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
2191 if (PrintHeapAtGC){
2192 gclog_or_tty->print_cr(" {Heap before GC collections=%d:", total_collections());
2193 Universe::print();
2194 }
2195 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2196 // Call allocation profiler
2197 AllocationProfiler::iterate_since_last_gc();
2198 // Fill TLAB's and such
2199 ensure_parsability(true);
2200 }
2201
2202 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
2203 // FIXME: what is this about?
2204 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
2205 // is set.
2206 COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
2207 "derived pointer present"));
2208
2209 if (PrintHeapAtGC){
2210 gclog_or_tty->print_cr(" Heap after GC collections=%d:", total_collections());
2211 Universe::print();
2212 gclog_or_tty->print("} ");
2213 }
2214 }
2215
2216 void G1CollectedHeap::do_collection_pause() {
2217 // Read the GC count while holding the Heap_lock
2218 // we need to do this _before_ wait_for_cleanup_complete(), to
2219 // ensure that we do not give up the heap lock and potentially
2220 // pick up the wrong count
2221 int gc_count_before = SharedHeap::heap()->total_collections();
2222
2223 // Don't want to do a GC pause while cleanup is being completed!
2224 wait_for_cleanup_complete();
2225
2226 g1_policy()->record_stop_world_start();
2227 {
2228 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back
2229 VM_G1IncCollectionPause op(gc_count_before);
2230 VMThread::execute(&op);
2231 }
2232 }
2233
2234 void
2235 G1CollectedHeap::doConcurrentMark() {
2236 if (G1ConcMark) {
2237 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2238 if (!_cmThread->in_progress()) {
2239 _cmThread->set_started();
2240 CGC_lock->notify();
2241 }
2242 }
2243 }
2244
2245 class VerifyMarkedObjsClosure: public ObjectClosure {
2246 G1CollectedHeap* _g1h;
2247 public:
2248 VerifyMarkedObjsClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
2249 void do_object(oop obj) {
2250 assert(obj->mark()->is_marked() ? !_g1h->is_obj_dead(obj) : true,
2251 "markandsweep mark should agree with concurrent deadness");
2252 }
2253 };
2254
2255 void
2256 G1CollectedHeap::checkConcurrentMark() {
2257 VerifyMarkedObjsClosure verifycl(this);
2258 doConcurrentMark();
2259 // MutexLockerEx x(getMarkBitMapLock(),
2260 // Mutex::_no_safepoint_check_flag);
2261 object_iterate(&verifycl);
2262 }
2263
2264 void G1CollectedHeap::do_sync_mark() {
2265 _cm->checkpointRootsInitial();
2266 _cm->markFromRoots();
2267 _cm->checkpointRootsFinal(false);
2268 }
2269
2270 // <NEW PREDICTION>
2271
2272 double G1CollectedHeap::predict_region_elapsed_time_ms(HeapRegion *hr,
2273 bool young) {
2274 return _g1_policy->predict_region_elapsed_time_ms(hr, young);
2275 }
2276
2277 void G1CollectedHeap::check_if_region_is_too_expensive(double
2278 predicted_time_ms) {
2279 _g1_policy->check_if_region_is_too_expensive(predicted_time_ms);
2280 }
2281
2282 size_t G1CollectedHeap::pending_card_num() {
2283 size_t extra_cards = 0;
2284 JavaThread *curr = Threads::first();
2285 while (curr != NULL) {
2286 DirtyCardQueue& dcq = curr->dirty_card_queue();
2287 extra_cards += dcq.size();
2288 curr = curr->next();
2289 }
2290 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2291 size_t buffer_size = dcqs.buffer_size();
2292 size_t buffer_num = dcqs.completed_buffers_num();
2293 return buffer_size * buffer_num + extra_cards;
2294 }
2295
2296 size_t G1CollectedHeap::max_pending_card_num() {
2297 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2298 size_t buffer_size = dcqs.buffer_size();
2299 size_t buffer_num = dcqs.completed_buffers_num();
2300 int thread_num = Threads::number_of_threads();
2301 return (buffer_num + thread_num) * buffer_size;
2302 }
2303
2304 size_t G1CollectedHeap::cards_scanned() {
2305 HRInto_G1RemSet* g1_rset = (HRInto_G1RemSet*) g1_rem_set();
2306 return g1_rset->cardsScanned();
2307 }
2308
2309 void
2310 G1CollectedHeap::setup_surviving_young_words() {
2311 guarantee( _surviving_young_words == NULL, "pre-condition" );
2312 size_t array_length = g1_policy()->young_cset_length();
2313 _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, array_length);
2314 if (_surviving_young_words == NULL) {
2315 vm_exit_out_of_memory(sizeof(size_t) * array_length,
2316 "Not enough space for young surv words summary.");
2317 }
2318 memset(_surviving_young_words, 0, array_length * sizeof(size_t));
2319 for (size_t i = 0; i < array_length; ++i) {
2320 guarantee( _surviving_young_words[i] == 0, "invariant" );
2321 }
2322 }
2323
2324 void
2325 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
2326 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
2327 size_t array_length = g1_policy()->young_cset_length();
2328 for (size_t i = 0; i < array_length; ++i)
2329 _surviving_young_words[i] += surv_young_words[i];
2330 }
2331
2332 void
2333 G1CollectedHeap::cleanup_surviving_young_words() {
2334 guarantee( _surviving_young_words != NULL, "pre-condition" );
2335 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words);
2336 _surviving_young_words = NULL;
2337 }
2338
2339 // </NEW PREDICTION>
2340
2341 void
2342 G1CollectedHeap::do_collection_pause_at_safepoint(HeapRegion* popular_region) {
2343 char verbose_str[128];
2344 sprintf(verbose_str, "GC pause ");
2345 if (popular_region != NULL)
2346 strcat(verbose_str, "(popular)");
2347 else if (g1_policy()->in_young_gc_mode()) {
2348 if (g1_policy()->full_young_gcs())
2349 strcat(verbose_str, "(young)");
2350 else
2351 strcat(verbose_str, "(partial)");
2352 }
2353 bool reset_should_initiate_conc_mark = false;
2354 if (popular_region != NULL && g1_policy()->should_initiate_conc_mark()) {
2355 // we currently do not allow an initial mark phase to be piggy-backed
2356 // on a popular pause
2357 reset_should_initiate_conc_mark = true;
2358 g1_policy()->unset_should_initiate_conc_mark();
2359 }
2360 if (g1_policy()->should_initiate_conc_mark())
2361 strcat(verbose_str, " (initial-mark)");
2362
2363 GCCauseSetter x(this, (popular_region == NULL ?
2364 GCCause::_g1_inc_collection_pause :
2365 GCCause::_g1_pop_region_collection_pause));
2366
2367 // if PrintGCDetails is on, we'll print long statistics information
2368 // in the collector policy code, so let's not print this as the output
2369 // is messy if we do.
2370 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
2371 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
2372 TraceTime t(verbose_str, PrintGC && !PrintGCDetails, true, gclog_or_tty);
2373
2374 ResourceMark rm;
2375 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
2376 assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
2377 guarantee(!is_gc_active(), "collection is not reentrant");
2378 assert(regions_accounted_for(), "Region leakage!");
2379
2380 increment_gc_time_stamp();
2381
2382 if (g1_policy()->in_young_gc_mode()) {
2383 assert(check_young_list_well_formed(),
2384 "young list should be well formed");
2385 }
2386
2387 if (GC_locker::is_active()) {
2388 return; // GC is disabled (e.g. JNI GetXXXCritical operation)
2389 }
2390
2391 bool abandoned = false;
2392 { // Call to jvmpi::post_class_unload_events must occur outside of active GC
2393 IsGCActiveMark x;
2394
2395 gc_prologue(false);
2396 increment_total_collections();
2397
2398 #if G1_REM_SET_LOGGING
2399 gclog_or_tty->print_cr("\nJust chose CS, heap:");
2400 print();
2401 #endif
2402
2403 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
2404 HandleMark hm; // Discard invalid handles created during verification
2405 prepare_for_verify();
2406 gclog_or_tty->print(" VerifyBeforeGC:");
2407 Universe::verify(false);
2408 }
2409
2410 COMPILER2_PRESENT(DerivedPointerTable::clear());
2411
2412 // We want to turn off ref discovere, if necessary, and turn it back on
2413 // on again later if we do.
2414 bool was_enabled = ref_processor()->discovery_enabled();
2415 if (was_enabled) ref_processor()->disable_discovery();
2416
2417 // Forget the current alloc region (we might even choose it to be part
2418 // of the collection set!).
2419 abandon_cur_alloc_region();
2420
2421 // The elapsed time induced by the start time below deliberately elides
2422 // the possible verification above.
2423 double start_time_sec = os::elapsedTime();
2424 GCOverheadReporter::recordSTWStart(start_time_sec);
2425 size_t start_used_bytes = used();
2426 if (!G1ConcMark) {
2427 do_sync_mark();
2428 }
2429
2430 g1_policy()->record_collection_pause_start(start_time_sec,
2431 start_used_bytes);
2432
2433 #if SCAN_ONLY_VERBOSE
2434 _young_list->print();
2435 #endif // SCAN_ONLY_VERBOSE
2436
2437 if (g1_policy()->should_initiate_conc_mark()) {
2438 concurrent_mark()->checkpointRootsInitialPre();
2439 }
2440 save_marks();
2441
2442 // We must do this before any possible evacuation that should propogate
2443 // marks, including evacuation of popular objects in a popular pause.
2444 if (mark_in_progress()) {
2445 double start_time_sec = os::elapsedTime();
2446
2447 _cm->drainAllSATBBuffers();
2448 double finish_mark_ms = (os::elapsedTime() - start_time_sec) * 1000.0;
2449 g1_policy()->record_satb_drain_time(finish_mark_ms);
2450
2451 }
2452 // Record the number of elements currently on the mark stack, so we
2453 // only iterate over these. (Since evacuation may add to the mark
2454 // stack, doing more exposes race conditions.) If no mark is in
2455 // progress, this will be zero.
2456 _cm->set_oops_do_bound();
2457
2458 assert(regions_accounted_for(), "Region leakage.");
2459
2460 bool abandoned = false;
2461
2462 if (mark_in_progress())
2463 concurrent_mark()->newCSet();
2464
2465 // Now choose the CS.
2466 if (popular_region == NULL) {
2467 g1_policy()->choose_collection_set();
2468 } else {
2469 // We may be evacuating a single region (for popularity).
2470 g1_policy()->record_popular_pause_preamble_start();
2471 popularity_pause_preamble(popular_region);
2472 g1_policy()->record_popular_pause_preamble_end();
2473 abandoned = (g1_policy()->collection_set() == NULL);
2474 // Now we allow more regions to be added (we have to collect
2475 // all popular regions).
2476 if (!abandoned) {
2477 g1_policy()->choose_collection_set(popular_region);
2478 }
2479 }
2480 // We may abandon a pause if we find no region that will fit in the MMU
2481 // pause.
2482 abandoned = (g1_policy()->collection_set() == NULL);
2483
2484 // Nothing to do if we were unable to choose a collection set.
2485 if (!abandoned) {
2486 #if G1_REM_SET_LOGGING
2487 gclog_or_tty->print_cr("\nAfter pause, heap:");
2488 print();
2489 #endif
2490
2491 setup_surviving_young_words();
2492
2493 // Set up the gc allocation regions.
2494 get_gc_alloc_regions();
2495
2496 // Actually do the work...
2497 evacuate_collection_set();
2498 free_collection_set(g1_policy()->collection_set());
2499 g1_policy()->clear_collection_set();
2500
2501 if (popular_region != NULL) {
2502 // We have to wait until now, because we don't want the region to
2503 // be rescheduled for pop-evac during RS update.
2504 popular_region->set_popular_pending(false);
2505 }
2506
2507 release_gc_alloc_regions();
2508
2509 cleanup_surviving_young_words();
2510
2511 if (g1_policy()->in_young_gc_mode()) {
2512 _young_list->reset_sampled_info();
2513 assert(check_young_list_empty(true),
2514 "young list should be empty");
2515
2516 #if SCAN_ONLY_VERBOSE
2517 _young_list->print();
2518 #endif // SCAN_ONLY_VERBOSE
2519
2520 _young_list->reset_auxilary_lists();
2521 }
2522 } else {
2523 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
2524 }
2525
2526 if (evacuation_failed()) {
2527 _summary_bytes_used = recalculate_used();
2528 } else {
2529 // The "used" of the the collection set have already been subtracted
2530 // when they were freed. Add in the bytes evacuated.
2531 _summary_bytes_used += g1_policy()->bytes_in_to_space();
2532 }
2533
2534 if (g1_policy()->in_young_gc_mode() &&
2535 g1_policy()->should_initiate_conc_mark()) {
2536 concurrent_mark()->checkpointRootsInitialPost();
2537 set_marking_started();
2538 doConcurrentMark();
2539 }
2540
2541 #if SCAN_ONLY_VERBOSE
2542 _young_list->print();
2543 #endif // SCAN_ONLY_VERBOSE
2544
2545 double end_time_sec = os::elapsedTime();
2546 g1_policy()->record_pause_time((end_time_sec - start_time_sec)*1000.0);
2547 GCOverheadReporter::recordSTWEnd(end_time_sec);
2548 g1_policy()->record_collection_pause_end(popular_region != NULL,
2549 abandoned);
2550
2551 assert(regions_accounted_for(), "Region leakage.");
2552
2553 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
2554 HandleMark hm; // Discard invalid handles created during verification
2555 gclog_or_tty->print(" VerifyAfterGC:");
2556 Universe::verify(false);
2557 }
2558
2559 if (was_enabled) ref_processor()->enable_discovery();
2560
2561 {
2562 size_t expand_bytes = g1_policy()->expansion_amount();
2563 if (expand_bytes > 0) {
2564 size_t bytes_before = capacity();
2565 expand(expand_bytes);
2566 }
2567 }
2568
2569 if (mark_in_progress())
2570 concurrent_mark()->update_g1_committed();
2571
2572 gc_epilogue(false);
2573 }
2574
2575 assert(verify_region_lists(), "Bad region lists.");
2576
2577 if (reset_should_initiate_conc_mark)
2578 g1_policy()->set_should_initiate_conc_mark();
2579
2580 if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) {
2581 gclog_or_tty->print_cr("Stopping after GC #%d", ExitAfterGCNum);
2582 print_tracing_info();
2583 vm_exit(-1);
2584 }
2585 }
2586
2587 void G1CollectedHeap::set_gc_alloc_region(int purpose, HeapRegion* r) {
2588 assert(purpose >= 0 && purpose < GCAllocPurposeCount, "invalid purpose");
2589 HeapWord* original_top = NULL;
2590 if (r != NULL)
2591 original_top = r->top();
2592
2593 // We will want to record the used space in r as being there before gc.
2594 // One we install it as a GC alloc region it's eligible for allocation.
2595 // So record it now and use it later.
2596 size_t r_used = 0;
2597 if (r != NULL) {
2598 r_used = r->used();
2599
2600 if (ParallelGCThreads > 0) {
2601 // need to take the lock to guard against two threads calling
2602 // get_gc_alloc_region concurrently (very unlikely but...)
2603 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
2604 r->save_marks();
2605 }
2606 }
2607 HeapRegion* old_alloc_region = _gc_alloc_regions[purpose];
2608 _gc_alloc_regions[purpose] = r;
2609 if (old_alloc_region != NULL) {
2610 // Replace aliases too.
2611 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2612 if (_gc_alloc_regions[ap] == old_alloc_region) {
2613 _gc_alloc_regions[ap] = r;
2614 }
2615 }
2616 }
2617 if (r != NULL) {
2618 push_gc_alloc_region(r);
2619 if (mark_in_progress() && original_top != r->next_top_at_mark_start()) {
2620 // We are using a region as a GC alloc region after it has been used
2621 // as a mutator allocation region during the current marking cycle.
2622 // The mutator-allocated objects are currently implicitly marked, but
2623 // when we move hr->next_top_at_mark_start() forward at the the end
2624 // of the GC pause, they won't be. We therefore mark all objects in
2625 // the "gap". We do this object-by-object, since marking densely
2626 // does not currently work right with marking bitmap iteration. This
2627 // means we rely on TLAB filling at the start of pauses, and no
2628 // "resuscitation" of filled TLAB's. If we want to do this, we need
2629 // to fix the marking bitmap iteration.
2630 HeapWord* curhw = r->next_top_at_mark_start();
2631 HeapWord* t = original_top;
2632
2633 while (curhw < t) {
2634 oop cur = (oop)curhw;
2635 // We'll assume parallel for generality. This is rare code.
2636 concurrent_mark()->markAndGrayObjectIfNecessary(cur); // can't we just mark them?
2637 curhw = curhw + cur->size();
2638 }
2639 assert(curhw == t, "Should have parsed correctly.");
2640 }
2641 if (G1PolicyVerbose > 1) {
2642 gclog_or_tty->print("New alloc region ["PTR_FORMAT", "PTR_FORMAT", " PTR_FORMAT") "
2643 "for survivors:", r->bottom(), original_top, r->end());
2644 r->print();
2645 }
2646 g1_policy()->record_before_bytes(r_used);
2647 }
2648 }
2649
2650 void G1CollectedHeap::push_gc_alloc_region(HeapRegion* hr) {
2651 assert(Thread::current()->is_VM_thread() ||
2652 par_alloc_during_gc_lock()->owned_by_self(), "Precondition");
2653 assert(!hr->is_gc_alloc_region() && !hr->in_collection_set(),
2654 "Precondition.");
2655 hr->set_is_gc_alloc_region(true);
2656 hr->set_next_gc_alloc_region(_gc_alloc_region_list);
2657 _gc_alloc_region_list = hr;
2658 }
2659
2660 #ifdef G1_DEBUG
2661 class FindGCAllocRegion: public HeapRegionClosure {
2662 public:
2663 bool doHeapRegion(HeapRegion* r) {
2664 if (r->is_gc_alloc_region()) {
2665 gclog_or_tty->print_cr("Region %d ["PTR_FORMAT"...] is still a gc_alloc_region.",
2666 r->hrs_index(), r->bottom());
2667 }
2668 return false;
2669 }
2670 };
2671 #endif // G1_DEBUG
2672
2673 void G1CollectedHeap::forget_alloc_region_list() {
2674 assert(Thread::current()->is_VM_thread(), "Precondition");
2675 while (_gc_alloc_region_list != NULL) {
2676 HeapRegion* r = _gc_alloc_region_list;
2677 assert(r->is_gc_alloc_region(), "Invariant.");
2678 _gc_alloc_region_list = r->next_gc_alloc_region();
2679 r->set_next_gc_alloc_region(NULL);
2680 r->set_is_gc_alloc_region(false);
2681 if (r->is_empty()) {
2682 ++_free_regions;
2683 }
2684 }
2685 #ifdef G1_DEBUG
2686 FindGCAllocRegion fa;
2687 heap_region_iterate(&fa);
2688 #endif // G1_DEBUG
2689 }
2690
2691
2692 bool G1CollectedHeap::check_gc_alloc_regions() {
2693 // TODO: allocation regions check
2694 return true;
2695 }
2696
2697 void G1CollectedHeap::get_gc_alloc_regions() {
2698 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2699 // Create new GC alloc regions.
2700 HeapRegion* alloc_region = _gc_alloc_regions[ap];
2701 // Clear this alloc region, so that in case it turns out to be
2702 // unacceptable, we end up with no allocation region, rather than a bad
2703 // one.
2704 _gc_alloc_regions[ap] = NULL;
2705 if (alloc_region == NULL || alloc_region->in_collection_set()) {
2706 // Can't re-use old one. Allocate a new one.
2707 alloc_region = newAllocRegionWithExpansion(ap, 0);
2708 }
2709 if (alloc_region != NULL) {
2710 set_gc_alloc_region(ap, alloc_region);
2711 }
2712 }
2713 // Set alternative regions for allocation purposes that have reached
2714 // thier limit.
2715 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2716 GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(ap);
2717 if (_gc_alloc_regions[ap] == NULL && alt_purpose != ap) {
2718 _gc_alloc_regions[ap] = _gc_alloc_regions[alt_purpose];
2719 }
2720 }
2721 assert(check_gc_alloc_regions(), "alloc regions messed up");
2722 }
2723
2724 void G1CollectedHeap::release_gc_alloc_regions() {
2725 // We keep a separate list of all regions that have been alloc regions in
2726 // the current collection pause. Forget that now.
2727 forget_alloc_region_list();
2728
2729 // The current alloc regions contain objs that have survived
2730 // collection. Make them no longer GC alloc regions.
2731 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2732 HeapRegion* r = _gc_alloc_regions[ap];
2733 if (r != NULL && r->is_empty()) {
2734 {
2735 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
2736 r->set_zero_fill_complete();
2737 put_free_region_on_list_locked(r);
2738 }
2739 }
2740 // set_gc_alloc_region will also NULLify all aliases to the region
2741 set_gc_alloc_region(ap, NULL);
2742 _gc_alloc_region_counts[ap] = 0;
2743 }
2744 }
2745
2746 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
2747 _drain_in_progress = false;
2748 set_evac_failure_closure(cl);
2749 _evac_failure_scan_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
2750 }
2751
2752 void G1CollectedHeap::finalize_for_evac_failure() {
2753 assert(_evac_failure_scan_stack != NULL &&
2754 _evac_failure_scan_stack->length() == 0,
2755 "Postcondition");
2756 assert(!_drain_in_progress, "Postcondition");
2757 // Don't have to delete, since the scan stack is a resource object.
2758 _evac_failure_scan_stack = NULL;
2759 }
2760
2761
2762
2763 // *** Sequential G1 Evacuation
2764
2765 HeapWord* G1CollectedHeap::allocate_during_gc(GCAllocPurpose purpose, size_t word_size) {
2766 HeapRegion* alloc_region = _gc_alloc_regions[purpose];
2767 // let the caller handle alloc failure
2768 if (alloc_region == NULL) return NULL;
2769 assert(isHumongous(word_size) || !alloc_region->isHumongous(),
2770 "Either the object is humongous or the region isn't");
2771 HeapWord* block = alloc_region->allocate(word_size);
2772 if (block == NULL) {
2773 block = allocate_during_gc_slow(purpose, alloc_region, false, word_size);
2774 }
2775 return block;
2776 }
2777
2778 class G1IsAliveClosure: public BoolObjectClosure {
2779 G1CollectedHeap* _g1;
2780 public:
2781 G1IsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
2782 void do_object(oop p) { assert(false, "Do not call."); }
2783 bool do_object_b(oop p) {
2784 // It is reachable if it is outside the collection set, or is inside
2785 // and forwarded.
2786
2787 #ifdef G1_DEBUG
2788 gclog_or_tty->print_cr("is alive "PTR_FORMAT" in CS %d forwarded %d overall %d",
2789 (void*) p, _g1->obj_in_cs(p), p->is_forwarded(),
2790 !_g1->obj_in_cs(p) || p->is_forwarded());
2791 #endif // G1_DEBUG
2792
2793 return !_g1->obj_in_cs(p) || p->is_forwarded();
2794 }
2795 };
2796
2797 class G1KeepAliveClosure: public OopClosure {
2798 G1CollectedHeap* _g1;
2799 public:
2800 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
2801 void do_oop(narrowOop* p) {
2802 guarantee(false, "NYI");
2803 }
2804 void do_oop(oop* p) {
2805 oop obj = *p;
2806 #ifdef G1_DEBUG
2807 if (PrintGC && Verbose) {
2808 gclog_or_tty->print_cr("keep alive *"PTR_FORMAT" = "PTR_FORMAT" "PTR_FORMAT,
2809 p, (void*) obj, (void*) *p);
2810 }
2811 #endif // G1_DEBUG
2812
2813 if (_g1->obj_in_cs(obj)) {
2814 assert( obj->is_forwarded(), "invariant" );
2815 *p = obj->forwardee();
2816
2817 #ifdef G1_DEBUG
2818 gclog_or_tty->print_cr(" in CSet: moved "PTR_FORMAT" -> "PTR_FORMAT,
2819 (void*) obj, (void*) *p);
2820 #endif // G1_DEBUG
2821 }
2822 }
2823 };
2824
2825 class RecreateRSetEntriesClosure: public OopClosure {
2826 private:
2827 G1CollectedHeap* _g1;
2828 G1RemSet* _g1_rem_set;
2829 HeapRegion* _from;
2830 public:
2831 RecreateRSetEntriesClosure(G1CollectedHeap* g1, HeapRegion* from) :
2832 _g1(g1), _g1_rem_set(g1->g1_rem_set()), _from(from)
2833 {}
2834
2835 void do_oop(narrowOop* p) {
2836 guarantee(false, "NYI");
2837 }
2838 void do_oop(oop* p) {
2839 assert(_from->is_in_reserved(p), "paranoia");
2840 if (*p != NULL) {
2841 _g1_rem_set->write_ref(_from, p);
2842 }
2843 }
2844 };
2845
2846 class RemoveSelfPointerClosure: public ObjectClosure {
2847 private:
2848 G1CollectedHeap* _g1;
2849 ConcurrentMark* _cm;
2850 HeapRegion* _hr;
2851 size_t _prev_marked_bytes;
2852 size_t _next_marked_bytes;
2853 public:
2854 RemoveSelfPointerClosure(G1CollectedHeap* g1, HeapRegion* hr) :
2855 _g1(g1), _cm(_g1->concurrent_mark()), _hr(hr),
2856 _prev_marked_bytes(0), _next_marked_bytes(0)
2857 {}
2858
2859 size_t prev_marked_bytes() { return _prev_marked_bytes; }
2860 size_t next_marked_bytes() { return _next_marked_bytes; }
2861
2862 // The original idea here was to coalesce evacuated and dead objects.
2863 // However that caused complications with the block offset table (BOT).
2864 // In particular if there were two TLABs, one of them partially refined.
2865 // |----- TLAB_1--------|----TLAB_2-~~~(partially refined part)~~~|
2866 // The BOT entries of the unrefined part of TLAB_2 point to the start
2867 // of TLAB_2. If the last object of the TLAB_1 and the first object
2868 // of TLAB_2 are coalesced, then the cards of the unrefined part
2869 // would point into middle of the filler object.
2870 //
2871 // The current approach is to not coalesce and leave the BOT contents intact.
2872 void do_object(oop obj) {
2873 if (obj->is_forwarded() && obj->forwardee() == obj) {
2874 // The object failed to move.
2875 assert(!_g1->is_obj_dead(obj), "We should not be preserving dead objs.");
2876 _cm->markPrev(obj);
2877 assert(_cm->isPrevMarked(obj), "Should be marked!");
2878 _prev_marked_bytes += (obj->size() * HeapWordSize);
2879 if (_g1->mark_in_progress() && !_g1->is_obj_ill(obj)) {
2880 _cm->markAndGrayObjectIfNecessary(obj);
2881 }
2882 obj->set_mark(markOopDesc::prototype());
2883 // While we were processing RSet buffers during the
2884 // collection, we actually didn't scan any cards on the
2885 // collection set, since we didn't want to update remebered
2886 // sets with entries that point into the collection set, given
2887 // that live objects fromthe collection set are about to move
2888 // and such entries will be stale very soon. This change also
2889 // dealt with a reliability issue which involved scanning a
2890 // card in the collection set and coming across an array that
2891 // was being chunked and looking malformed. The problem is
2892 // that, if evacuation fails, we might have remembered set
2893 // entries missing given that we skipped cards on the
2894 // collection set. So, we'll recreate such entries now.
2895 RecreateRSetEntriesClosure cl(_g1, _hr);
2896 obj->oop_iterate(&cl);
2897 assert(_cm->isPrevMarked(obj), "Should be marked!");
2898 } else {
2899 // The object has been either evacuated or is dead. Fill it with a
2900 // dummy object.
2901 MemRegion mr((HeapWord*)obj, obj->size());
2902 SharedHeap::fill_region_with_object(mr);
2903 _cm->clearRangeBothMaps(mr);
2904 }
2905 }
2906 };
2907
2908 void G1CollectedHeap::remove_self_forwarding_pointers() {
2909 HeapRegion* cur = g1_policy()->collection_set();
2910
2911 while (cur != NULL) {
2912 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
2913
2914 if (cur->evacuation_failed()) {
2915 RemoveSelfPointerClosure rspc(_g1h, cur);
2916 assert(cur->in_collection_set(), "bad CS");
2917 cur->object_iterate(&rspc);
2918
2919 // A number of manipulations to make the TAMS be the current top,
2920 // and the marked bytes be the ones observed in the iteration.
2921 if (_g1h->concurrent_mark()->at_least_one_mark_complete()) {
2922 // The comments below are the postconditions achieved by the
2923 // calls. Note especially the last such condition, which says that
2924 // the count of marked bytes has been properly restored.
2925 cur->note_start_of_marking(false);
2926 // _next_top_at_mark_start == top, _next_marked_bytes == 0
2927 cur->add_to_marked_bytes(rspc.prev_marked_bytes());
2928 // _next_marked_bytes == prev_marked_bytes.
2929 cur->note_end_of_marking();
2930 // _prev_top_at_mark_start == top(),
2931 // _prev_marked_bytes == prev_marked_bytes
2932 }
2933 // If there is no mark in progress, we modified the _next variables
2934 // above needlessly, but harmlessly.
2935 if (_g1h->mark_in_progress()) {
2936 cur->note_start_of_marking(false);
2937 // _next_top_at_mark_start == top, _next_marked_bytes == 0
2938 // _next_marked_bytes == next_marked_bytes.
2939 }
2940
2941 // Now make sure the region has the right index in the sorted array.
2942 g1_policy()->note_change_in_marked_bytes(cur);
2943 }
2944 cur = cur->next_in_collection_set();
2945 }
2946 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
2947
2948 // Now restore saved marks, if any.
2949 if (_objs_with_preserved_marks != NULL) {
2950 assert(_preserved_marks_of_objs != NULL, "Both or none.");
2951 assert(_objs_with_preserved_marks->length() ==
2952 _preserved_marks_of_objs->length(), "Both or none.");
2953 guarantee(_objs_with_preserved_marks->length() ==
2954 _preserved_marks_of_objs->length(), "Both or none.");
2955 for (int i = 0; i < _objs_with_preserved_marks->length(); i++) {
2956 oop obj = _objs_with_preserved_marks->at(i);
2957 markOop m = _preserved_marks_of_objs->at(i);
2958 obj->set_mark(m);
2959 }
2960 // Delete the preserved marks growable arrays (allocated on the C heap).
2961 delete _objs_with_preserved_marks;
2962 delete _preserved_marks_of_objs;
2963 _objs_with_preserved_marks = NULL;
2964 _preserved_marks_of_objs = NULL;
2965 }
2966 }
2967
2968 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
2969 _evac_failure_scan_stack->push(obj);
2970 }
2971
2972 void G1CollectedHeap::drain_evac_failure_scan_stack() {
2973 assert(_evac_failure_scan_stack != NULL, "precondition");
2974
2975 while (_evac_failure_scan_stack->length() > 0) {
2976 oop obj = _evac_failure_scan_stack->pop();
2977 _evac_failure_closure->set_region(heap_region_containing(obj));
2978 obj->oop_iterate_backwards(_evac_failure_closure);
2979 }
2980 }
2981
2982 void G1CollectedHeap::handle_evacuation_failure(oop old) {
2983 markOop m = old->mark();
2984 // forward to self
2985 assert(!old->is_forwarded(), "precondition");
2986
2987 old->forward_to(old);
2988 handle_evacuation_failure_common(old, m);
2989 }
2990
2991 oop
2992 G1CollectedHeap::handle_evacuation_failure_par(OopsInHeapRegionClosure* cl,
2993 oop old) {
2994 markOop m = old->mark();
2995 oop forward_ptr = old->forward_to_atomic(old);
2996 if (forward_ptr == NULL) {
2997 // Forward-to-self succeeded.
2998 if (_evac_failure_closure != cl) {
2999 MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
3000 assert(!_drain_in_progress,
3001 "Should only be true while someone holds the lock.");
3002 // Set the global evac-failure closure to the current thread's.
3003 assert(_evac_failure_closure == NULL, "Or locking has failed.");
3004 set_evac_failure_closure(cl);
3005 // Now do the common part.
3006 handle_evacuation_failure_common(old, m);
3007 // Reset to NULL.
3008 set_evac_failure_closure(NULL);
3009 } else {
3010 // The lock is already held, and this is recursive.
3011 assert(_drain_in_progress, "This should only be the recursive case.");
3012 handle_evacuation_failure_common(old, m);
3013 }
3014 return old;
3015 } else {
3016 // Someone else had a place to copy it.
3017 return forward_ptr;
3018 }
3019 }
3020
3021 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
3022 set_evacuation_failed(true);
3023
3024 preserve_mark_if_necessary(old, m);
3025
3026 HeapRegion* r = heap_region_containing(old);
3027 if (!r->evacuation_failed()) {
3028 r->set_evacuation_failed(true);
3029 if (G1TraceRegions) {
3030 gclog_or_tty->print("evacuation failed in heap region "PTR_FORMAT" "
3031 "["PTR_FORMAT","PTR_FORMAT")\n",
3032 r, r->bottom(), r->end());
3033 }
3034 }
3035
3036 push_on_evac_failure_scan_stack(old);
3037
3038 if (!_drain_in_progress) {
3039 // prevent recursion in copy_to_survivor_space()
3040 _drain_in_progress = true;
3041 drain_evac_failure_scan_stack();
3042 _drain_in_progress = false;
3043 }
3044 }
3045
3046 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
3047 if (m != markOopDesc::prototype()) {
3048 if (_objs_with_preserved_marks == NULL) {
3049 assert(_preserved_marks_of_objs == NULL, "Both or none.");
3050 _objs_with_preserved_marks =
3051 new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
3052 _preserved_marks_of_objs =
3053 new (ResourceObj::C_HEAP) GrowableArray<markOop>(40, true);
3054 }
3055 _objs_with_preserved_marks->push(obj);
3056 _preserved_marks_of_objs->push(m);
3057 }
3058 }
3059
3060 // *** Parallel G1 Evacuation
3061
3062 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
3063 size_t word_size) {
3064 HeapRegion* alloc_region = _gc_alloc_regions[purpose];
3065 // let the caller handle alloc failure
3066 if (alloc_region == NULL) return NULL;
3067
3068 HeapWord* block = alloc_region->par_allocate(word_size);
3069 if (block == NULL) {
3070 MutexLockerEx x(par_alloc_during_gc_lock(),
3071 Mutex::_no_safepoint_check_flag);
3072 block = allocate_during_gc_slow(purpose, alloc_region, true, word_size);
3073 }
3074 return block;
3075 }
3076
3077 HeapWord*
3078 G1CollectedHeap::allocate_during_gc_slow(GCAllocPurpose purpose,
3079 HeapRegion* alloc_region,
3080 bool par,
3081 size_t word_size) {
3082 HeapWord* block = NULL;
3083 // In the parallel case, a previous thread to obtain the lock may have
3084 // already assigned a new gc_alloc_region.
3085 if (alloc_region != _gc_alloc_regions[purpose]) {
3086 assert(par, "But should only happen in parallel case.");
3087 alloc_region = _gc_alloc_regions[purpose];
3088 if (alloc_region == NULL) return NULL;
3089 block = alloc_region->par_allocate(word_size);
3090 if (block != NULL) return block;
3091 // Otherwise, continue; this new region is empty, too.
3092 }
3093 assert(alloc_region != NULL, "We better have an allocation region");
3094 // Another thread might have obtained alloc_region for the given
3095 // purpose, and might be attempting to allocate in it, and might
3096 // succeed. Therefore, we can't do the "finalization" stuff on the
3097 // region below until we're sure the last allocation has happened.
3098 // We ensure this by allocating the remaining space with a garbage
3099 // object.
3100 if (par) par_allocate_remaining_space(alloc_region);
3101 // Now we can do the post-GC stuff on the region.
3102 alloc_region->note_end_of_copying();
3103 g1_policy()->record_after_bytes(alloc_region->used());
3104
3105 if (_gc_alloc_region_counts[purpose] >= g1_policy()->max_regions(purpose)) {
3106 // Cannot allocate more regions for the given purpose.
3107 GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(purpose);
3108 // Is there an alternative?
3109 if (purpose != alt_purpose) {
3110 HeapRegion* alt_region = _gc_alloc_regions[alt_purpose];
3111 // Has not the alternative region been aliased?
3112 if (alloc_region != alt_region) {
3113 // Try to allocate in the alternative region.
3114 if (par) {
3115 block = alt_region->par_allocate(word_size);
3116 } else {
3117 block = alt_region->allocate(word_size);
3118 }
3119 // Make an alias.
3120 _gc_alloc_regions[purpose] = _gc_alloc_regions[alt_purpose];
3121 }
3122 if (block != NULL) {
3123 return block;
3124 }
3125 // Both the allocation region and the alternative one are full
3126 // and aliased, replace them with a new allocation region.
3127 purpose = alt_purpose;
3128 } else {
3129 set_gc_alloc_region(purpose, NULL);
3130 return NULL;
3131 }
3132 }
3133
3134 // Now allocate a new region for allocation.
3135 alloc_region = newAllocRegionWithExpansion(purpose, word_size, false /*zero_filled*/);
3136
3137 // let the caller handle alloc failure
3138 if (alloc_region != NULL) {
3139
3140 assert(check_gc_alloc_regions(), "alloc regions messed up");
3141 assert(alloc_region->saved_mark_at_top(),
3142 "Mark should have been saved already.");
3143 // We used to assert that the region was zero-filled here, but no
3144 // longer.
3145
3146 // This must be done last: once it's installed, other regions may
3147 // allocate in it (without holding the lock.)
3148 set_gc_alloc_region(purpose, alloc_region);
3149
3150 if (par) {
3151 block = alloc_region->par_allocate(word_size);
3152 } else {
3153 block = alloc_region->allocate(word_size);
3154 }
3155 // Caller handles alloc failure.
3156 } else {
3157 // This sets other apis using the same old alloc region to NULL, also.
3158 set_gc_alloc_region(purpose, NULL);
3159 }
3160 return block; // May be NULL.
3161 }
3162
3163 void G1CollectedHeap::par_allocate_remaining_space(HeapRegion* r) {
3164 HeapWord* block = NULL;
3165 size_t free_words;
3166 do {
3167 free_words = r->free()/HeapWordSize;
3168 // If there's too little space, no one can allocate, so we're done.
3169 if (free_words < (size_t)oopDesc::header_size()) return;
3170 // Otherwise, try to claim it.
3171 block = r->par_allocate(free_words);
3172 } while (block == NULL);
3173 SharedHeap::fill_region_with_object(MemRegion(block, free_words));
3174 }
3175
3176 #define use_local_bitmaps 1
3177 #define verify_local_bitmaps 0
3178
3179 #ifndef PRODUCT
3180
3181 class GCLabBitMap;
3182 class GCLabBitMapClosure: public BitMapClosure {
3183 private:
3184 ConcurrentMark* _cm;
3185 GCLabBitMap* _bitmap;
3186
3187 public:
3188 GCLabBitMapClosure(ConcurrentMark* cm,
3189 GCLabBitMap* bitmap) {
3190 _cm = cm;
3191 _bitmap = bitmap;
3192 }
3193
3194 virtual bool do_bit(size_t offset);
3195 };
3196
3197 #endif // PRODUCT
3198
3199 #define oop_buffer_length 256
3200
3201 class GCLabBitMap: public BitMap {
3202 private:
3203 ConcurrentMark* _cm;
3204
3205 int _shifter;
3206 size_t _bitmap_word_covers_words;
3207
3208 // beginning of the heap
3209 HeapWord* _heap_start;
3210
3211 // this is the actual start of the GCLab
3212 HeapWord* _real_start_word;
3213
3214 // this is the actual end of the GCLab
3215 HeapWord* _real_end_word;
3216
3217 // this is the first word, possibly located before the actual start
3218 // of the GCLab, that corresponds to the first bit of the bitmap
3219 HeapWord* _start_word;
3220
3221 // size of a GCLab in words
3222 size_t _gclab_word_size;
3223
3224 static int shifter() {
3225 return MinObjAlignment - 1;
3226 }
3227
3228 // how many heap words does a single bitmap word corresponds to?
3229 static size_t bitmap_word_covers_words() {
3230 return BitsPerWord << shifter();
3231 }
3232
3233 static size_t gclab_word_size() {
3234 return ParallelGCG1AllocBufferSize / HeapWordSize;
3235 }
3236
3237 static size_t bitmap_size_in_bits() {
3238 size_t bits_in_bitmap = gclab_word_size() >> shifter();
3239 // We are going to ensure that the beginning of a word in this
3240 // bitmap also corresponds to the beginning of a word in the
3241 // global marking bitmap. To handle the case where a GCLab
3242 // starts from the middle of the bitmap, we need to add enough
3243 // space (i.e. up to a bitmap word) to ensure that we have
3244 // enough bits in the bitmap.
3245 return bits_in_bitmap + BitsPerWord - 1;
3246 }
3247 public:
3248 GCLabBitMap(HeapWord* heap_start)
3249 : BitMap(bitmap_size_in_bits()),
3250 _cm(G1CollectedHeap::heap()->concurrent_mark()),
3251 _shifter(shifter()),
3252 _bitmap_word_covers_words(bitmap_word_covers_words()),
3253 _heap_start(heap_start),
3254 _gclab_word_size(gclab_word_size()),
3255 _real_start_word(NULL),
3256 _real_end_word(NULL),
3257 _start_word(NULL)
3258 {
3259 guarantee( size_in_words() >= bitmap_size_in_words(),
3260 "just making sure");
3261 }
3262
3263 inline unsigned heapWordToOffset(HeapWord* addr) {
3264 unsigned offset = (unsigned) pointer_delta(addr, _start_word) >> _shifter;
3265 assert(offset < size(), "offset should be within bounds");
3266 return offset;
3267 }
3268
3269 inline HeapWord* offsetToHeapWord(size_t offset) {
3270 HeapWord* addr = _start_word + (offset << _shifter);
3271 assert(_real_start_word <= addr && addr < _real_end_word, "invariant");
3272 return addr;
3273 }
3274
3275 bool fields_well_formed() {
3276 bool ret1 = (_real_start_word == NULL) &&
3277 (_real_end_word == NULL) &&
3278 (_start_word == NULL);
3279 if (ret1)
3280 return true;
3281
3282 bool ret2 = _real_start_word >= _start_word &&
3283 _start_word < _real_end_word &&
3284 (_real_start_word + _gclab_word_size) == _real_end_word &&
3285 (_start_word + _gclab_word_size + _bitmap_word_covers_words)
3286 > _real_end_word;
3287 return ret2;
3288 }
3289
3290 inline bool mark(HeapWord* addr) {
3291 guarantee(use_local_bitmaps, "invariant");
3292 assert(fields_well_formed(), "invariant");
3293
3294 if (addr >= _real_start_word && addr < _real_end_word) {
3295 assert(!isMarked(addr), "should not have already been marked");
3296
3297 // first mark it on the bitmap
3298 at_put(heapWordToOffset(addr), true);
3299
3300 return true;
3301 } else {
3302 return false;
3303 }
3304 }
3305
3306 inline bool isMarked(HeapWord* addr) {
3307 guarantee(use_local_bitmaps, "invariant");
3308 assert(fields_well_formed(), "invariant");
3309
3310 return at(heapWordToOffset(addr));
3311 }
3312
3313 void set_buffer(HeapWord* start) {
3314 guarantee(use_local_bitmaps, "invariant");
3315 clear();
3316
3317 assert(start != NULL, "invariant");
3318 _real_start_word = start;
3319 _real_end_word = start + _gclab_word_size;
3320
3321 size_t diff =
3322 pointer_delta(start, _heap_start) % _bitmap_word_covers_words;
3323 _start_word = start - diff;
3324
3325 assert(fields_well_formed(), "invariant");
3326 }
3327
3328 #ifndef PRODUCT
3329 void verify() {
3330 // verify that the marks have been propagated
3331 GCLabBitMapClosure cl(_cm, this);
3332 iterate(&cl);
3333 }
3334 #endif // PRODUCT
3335
3336 void retire() {
3337 guarantee(use_local_bitmaps, "invariant");
3338 assert(fields_well_formed(), "invariant");
3339
3340 if (_start_word != NULL) {
3341 CMBitMap* mark_bitmap = _cm->nextMarkBitMap();
3342
3343 // this means that the bitmap was set up for the GCLab
3344 assert(_real_start_word != NULL && _real_end_word != NULL, "invariant");
3345
3346 mark_bitmap->mostly_disjoint_range_union(this,
3347 0, // always start from the start of the bitmap
3348 _start_word,
3349 size_in_words());
3350 _cm->grayRegionIfNecessary(MemRegion(_real_start_word, _real_end_word));
3351
3352 #ifndef PRODUCT
3353 if (use_local_bitmaps && verify_local_bitmaps)
3354 verify();
3355 #endif // PRODUCT
3356 } else {
3357 assert(_real_start_word == NULL && _real_end_word == NULL, "invariant");
3358 }
3359 }
3360
3361 static size_t bitmap_size_in_words() {
3362 return (bitmap_size_in_bits() + BitsPerWord - 1) / BitsPerWord;
3363 }
3364 };
3365
3366 #ifndef PRODUCT
3367
3368 bool GCLabBitMapClosure::do_bit(size_t offset) {
3369 HeapWord* addr = _bitmap->offsetToHeapWord(offset);
3370 guarantee(_cm->isMarked(oop(addr)), "it should be!");
3371 return true;
3372 }
3373
3374 #endif // PRODUCT
3375
3376 class G1ParGCAllocBuffer: public ParGCAllocBuffer {
3377 private:
3378 bool _retired;
3379 bool _during_marking;
3380 GCLabBitMap _bitmap;
3381
3382 public:
3383 G1ParGCAllocBuffer() :
3384 ParGCAllocBuffer(ParallelGCG1AllocBufferSize / HeapWordSize),
3385 _during_marking(G1CollectedHeap::heap()->mark_in_progress()),
3386 _bitmap(G1CollectedHeap::heap()->reserved_region().start()),
3387 _retired(false)
3388 { }
3389
3390 inline bool mark(HeapWord* addr) {
3391 guarantee(use_local_bitmaps, "invariant");
3392 assert(_during_marking, "invariant");
3393 return _bitmap.mark(addr);
3394 }
3395
3396 inline void set_buf(HeapWord* buf) {
3397 if (use_local_bitmaps && _during_marking)
3398 _bitmap.set_buffer(buf);
3399 ParGCAllocBuffer::set_buf(buf);
3400 _retired = false;
3401 }
3402
3403 inline void retire(bool end_of_gc, bool retain) {
3404 if (_retired)
3405 return;
3406 if (use_local_bitmaps && _during_marking) {
3407 _bitmap.retire();
3408 }
3409 ParGCAllocBuffer::retire(end_of_gc, retain);
3410 _retired = true;
3411 }
3412 };
3413
3414
3415 class G1ParScanThreadState : public StackObj {
3416 protected:
3417 G1CollectedHeap* _g1h;
3418 RefToScanQueue* _refs;
3419
3420 typedef GrowableArray<oop*> OverflowQueue;
3421 OverflowQueue* _overflowed_refs;
3422
3423 G1ParGCAllocBuffer _alloc_buffers[GCAllocPurposeCount];
3424
3425 size_t _alloc_buffer_waste;
3426 size_t _undo_waste;
3427
3428 OopsInHeapRegionClosure* _evac_failure_cl;
3429 G1ParScanHeapEvacClosure* _evac_cl;
3430 G1ParScanPartialArrayClosure* _partial_scan_cl;
3431
3432 int _hash_seed;
3433 int _queue_num;
3434
3435 int _term_attempts;
3436 #if G1_DETAILED_STATS
3437 int _pushes, _pops, _steals, _steal_attempts;
3438 int _overflow_pushes;
3439 #endif
3440
3441 double _start;
3442 double _start_strong_roots;
3443 double _strong_roots_time;
3444 double _start_term;
3445 double _term_time;
3446
3447 // Map from young-age-index (0 == not young, 1 is youngest) to
3448 // surviving words. base is what we get back from the malloc call
3449 size_t* _surviving_young_words_base;
3450 // this points into the array, as we use the first few entries for padding
3451 size_t* _surviving_young_words;
3452
3453 #define PADDING_ELEM_NUM (64 / sizeof(size_t))
3454
3455 void add_to_alloc_buffer_waste(size_t waste) { _alloc_buffer_waste += waste; }
3456
3457 void add_to_undo_waste(size_t waste) { _undo_waste += waste; }
3458
3459 public:
3460 G1ParScanThreadState(G1CollectedHeap* g1h, int queue_num)
3461 : _g1h(g1h),
3462 _refs(g1h->task_queue(queue_num)),
3463 _hash_seed(17), _queue_num(queue_num),
3464 _term_attempts(0),
3465 #if G1_DETAILED_STATS
3466 _pushes(0), _pops(0), _steals(0),
3467 _steal_attempts(0), _overflow_pushes(0),
3468 #endif
3469 _strong_roots_time(0), _term_time(0),
3470 _alloc_buffer_waste(0), _undo_waste(0)
3471 {
3472 // we allocate G1YoungSurvRateNumRegions plus one entries, since
3473 // we "sacrifice" entry 0 to keep track of surviving bytes for
3474 // non-young regions (where the age is -1)
3475 // We also add a few elements at the beginning and at the end in
3476 // an attempt to eliminate cache contention
3477 size_t real_length = 1 + _g1h->g1_policy()->young_cset_length();
3478 size_t array_length = PADDING_ELEM_NUM +
3479 real_length +
3480 PADDING_ELEM_NUM;
3481 _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length);
3482 if (_surviving_young_words_base == NULL)
3483 vm_exit_out_of_memory(array_length * sizeof(size_t),
3484 "Not enough space for young surv histo.");
3485 _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
3486 memset(_surviving_young_words, 0, real_length * sizeof(size_t));
3487
3488 _overflowed_refs = new OverflowQueue(10);
3489
3490 _start = os::elapsedTime();
3491 }
3492
3493 ~G1ParScanThreadState() {
3494 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base);
3495 }
3496
3497 RefToScanQueue* refs() { return _refs; }
3498 OverflowQueue* overflowed_refs() { return _overflowed_refs; }
3499
3500 inline G1ParGCAllocBuffer* alloc_buffer(GCAllocPurpose purpose) {
3501 return &_alloc_buffers[purpose];
3502 }
3503
3504 size_t alloc_buffer_waste() { return _alloc_buffer_waste; }
3505 size_t undo_waste() { return _undo_waste; }
3506
3507 void push_on_queue(oop* ref) {
3508 if (!refs()->push(ref)) {
3509 overflowed_refs()->push(ref);
3510 IF_G1_DETAILED_STATS(note_overflow_push());
3511 } else {
3512 IF_G1_DETAILED_STATS(note_push());
3513 }
3514 }
3515
3516 void pop_from_queue(oop*& ref) {
3517 if (!refs()->pop_local(ref)) {
3518 ref = NULL;
3519 } else {
3520 IF_G1_DETAILED_STATS(note_pop());
3521 }
3522 }
3523
3524 void pop_from_overflow_queue(oop*& ref) {
3525 ref = overflowed_refs()->pop();
3526 }
3527
3528 int refs_to_scan() { return refs()->size(); }
3529 int overflowed_refs_to_scan() { return overflowed_refs()->length(); }
3530
3531 HeapWord* allocate_slow(GCAllocPurpose purpose, size_t word_sz) {
3532
3533 HeapWord* obj = NULL;
3534 if (word_sz * 100 <
3535 (size_t)(ParallelGCG1AllocBufferSize / HeapWordSize) *
3536 ParallelGCBufferWastePct) {
3537 G1ParGCAllocBuffer* alloc_buf = alloc_buffer(purpose);
3538 add_to_alloc_buffer_waste(alloc_buf->words_remaining());
3539 alloc_buf->retire(false, false);
3540
3541 HeapWord* buf =
3542 _g1h->par_allocate_during_gc(purpose, ParallelGCG1AllocBufferSize / HeapWordSize);
3543 if (buf == NULL) return NULL; // Let caller handle allocation failure.
3544 // Otherwise.
3545 alloc_buf->set_buf(buf);
3546
3547 obj = alloc_buf->allocate(word_sz);
3548 assert(obj != NULL, "buffer was definitely big enough...");
3549 }
3550 else {
3551 obj = _g1h->par_allocate_during_gc(purpose, word_sz);
3552 }
3553 return obj;
3554 }
3555
3556 HeapWord* allocate(GCAllocPurpose purpose, size_t word_sz) {
3557 HeapWord* obj = alloc_buffer(purpose)->allocate(word_sz);
3558 if (obj != NULL) return obj;
3559 return allocate_slow(purpose, word_sz);
3560 }
3561
3562 void undo_allocation(GCAllocPurpose purpose, HeapWord* obj, size_t word_sz) {
3563 if (alloc_buffer(purpose)->contains(obj)) {
3564 guarantee(alloc_buffer(purpose)->contains(obj + word_sz - 1),
3565 "should contain whole object");
3566 alloc_buffer(purpose)->undo_allocation(obj, word_sz);
3567 }
3568 else {
3569 SharedHeap::fill_region_with_object(MemRegion(obj, word_sz));
3570 add_to_undo_waste(word_sz);
3571 }
3572 }
3573
3574 void set_evac_failure_closure(OopsInHeapRegionClosure* evac_failure_cl) {
3575 _evac_failure_cl = evac_failure_cl;
3576 }
3577 OopsInHeapRegionClosure* evac_failure_closure() {
3578 return _evac_failure_cl;
3579 }
3580
3581 void set_evac_closure(G1ParScanHeapEvacClosure* evac_cl) {
3582 _evac_cl = evac_cl;
3583 }
3584
3585 void set_partial_scan_closure(G1ParScanPartialArrayClosure* partial_scan_cl) {
3586 _partial_scan_cl = partial_scan_cl;
3587 }
3588
3589 int* hash_seed() { return &_hash_seed; }
3590 int queue_num() { return _queue_num; }
3591
3592 int term_attempts() { return _term_attempts; }
3593 void note_term_attempt() { _term_attempts++; }
3594
3595 #if G1_DETAILED_STATS
3596 int pushes() { return _pushes; }
3597 int pops() { return _pops; }
3598 int steals() { return _steals; }
3599 int steal_attempts() { return _steal_attempts; }
3600 int overflow_pushes() { return _overflow_pushes; }
3601
3602 void note_push() { _pushes++; }
3603 void note_pop() { _pops++; }
3604 void note_steal() { _steals++; }
3605 void note_steal_attempt() { _steal_attempts++; }
3606 void note_overflow_push() { _overflow_pushes++; }
3607 #endif
3608
3609 void start_strong_roots() {
3610 _start_strong_roots = os::elapsedTime();
3611 }
3612 void end_strong_roots() {
3613 _strong_roots_time += (os::elapsedTime() - _start_strong_roots);
3614 }
3615 double strong_roots_time() { return _strong_roots_time; }
3616
3617 void start_term_time() {
3618 note_term_attempt();
3619 _start_term = os::elapsedTime();
3620 }
3621 void end_term_time() {
3622 _term_time += (os::elapsedTime() - _start_term);
3623 }
3624 double term_time() { return _term_time; }
3625
3626 double elapsed() {
3627 return os::elapsedTime() - _start;
3628 }
3629
3630 size_t* surviving_young_words() {
3631 // We add on to hide entry 0 which accumulates surviving words for
3632 // age -1 regions (i.e. non-young ones)
3633 return _surviving_young_words;
3634 }
3635
3636 void retire_alloc_buffers() {
3637 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
3638 size_t waste = _alloc_buffers[ap].words_remaining();
3639 add_to_alloc_buffer_waste(waste);
3640 _alloc_buffers[ap].retire(true, false);
3641 }
3642 }
3643
3644 void trim_queue() {
3645 while (refs_to_scan() > 0 || overflowed_refs_to_scan() > 0) {
3646 oop *ref_to_scan = NULL;
3647 if (overflowed_refs_to_scan() == 0) {
3648 pop_from_queue(ref_to_scan);
3649 } else {
3650 pop_from_overflow_queue(ref_to_scan);
3651 }
3652 if (ref_to_scan != NULL) {
3653 if ((intptr_t)ref_to_scan & G1_PARTIAL_ARRAY_MASK) {
3654 _partial_scan_cl->do_oop_nv(ref_to_scan);
3655 } else {
3656 // Note: we can use "raw" versions of "region_containing" because
3657 // "obj_to_scan" is definitely in the heap, and is not in a
3658 // humongous region.
3659 HeapRegion* r = _g1h->heap_region_containing_raw(ref_to_scan);
3660 _evac_cl->set_region(r);
3661 _evac_cl->do_oop_nv(ref_to_scan);
3662 }
3663 }
3664 }
3665 }
3666 };
3667
3668
3669 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
3670 _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()),
3671 _par_scan_state(par_scan_state) { }
3672
3673 // This closure is applied to the fields of the objects that have just been copied.
3674 // Should probably be made inline and moved in g1OopClosures.inline.hpp.
3675 void G1ParScanClosure::do_oop_nv(oop* p) {
3676 oop obj = *p;
3677 if (obj != NULL) {
3678 if (_g1->obj_in_cs(obj)) {
3679 if (obj->is_forwarded()) {
3680 *p = obj->forwardee();
3681 } else {
3682 _par_scan_state->push_on_queue(p);
3683 return;
3684 }
3685 }
3686 _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
3687 }
3688 }
3689
3690 void G1ParCopyHelper::mark_forwardee(oop* p) {
3691 // This is called _after_ do_oop_work has been called, hence after
3692 // the object has been relocated to its new location and *p points
3693 // to its new location.
3694
3695 oop thisOop = *p;
3696 if (thisOop != NULL) {
3697 assert((_g1->evacuation_failed()) || (!_g1->obj_in_cs(thisOop)),
3698 "shouldn't still be in the CSet if evacuation didn't fail.");
3699 HeapWord* addr = (HeapWord*)thisOop;
3700 if (_g1->is_in_g1_reserved(addr))
3701 _cm->grayRoot(oop(addr));
3702 }
3703 }
3704
3705 oop G1ParCopyHelper::copy_to_survivor_space(oop old) {
3706 size_t word_sz = old->size();
3707 HeapRegion* from_region = _g1->heap_region_containing_raw(old);
3708 // +1 to make the -1 indexes valid...
3709 int young_index = from_region->young_index_in_cset()+1;
3710 assert( (from_region->is_young() && young_index > 0) ||
3711 (!from_region->is_young() && young_index == 0), "invariant" );
3712 G1CollectorPolicy* g1p = _g1->g1_policy();
3713 markOop m = old->mark();
3714 GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, m->age(),
3715 word_sz);
3716 HeapWord* obj_ptr = _par_scan_state->allocate(alloc_purpose, word_sz);
3717 oop obj = oop(obj_ptr);
3718
3719 if (obj_ptr == NULL) {
3720 // This will either forward-to-self, or detect that someone else has
3721 // installed a forwarding pointer.
3722 OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
3723 return _g1->handle_evacuation_failure_par(cl, old);
3724 }
3725
3726 oop forward_ptr = old->forward_to_atomic(obj);
3727 if (forward_ptr == NULL) {
3728 Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
3729 obj->set_mark(m);
3730 if (g1p->track_object_age(alloc_purpose)) {
3731 obj->incr_age();
3732 }
3733 // preserve "next" mark bit
3734 if (_g1->mark_in_progress() && !_g1->is_obj_ill(old)) {
3735 if (!use_local_bitmaps ||
3736 !_par_scan_state->alloc_buffer(alloc_purpose)->mark(obj_ptr)) {
3737 // if we couldn't mark it on the local bitmap (this happens when
3738 // the object was not allocated in the GCLab), we have to bite
3739 // the bullet and do the standard parallel mark
3740 _cm->markAndGrayObjectIfNecessary(obj);
3741 }
3742 #if 1
3743 if (_g1->isMarkedNext(old)) {
3744 _cm->nextMarkBitMap()->parClear((HeapWord*)old);
3745 }
3746 #endif
3747 }
3748
3749 size_t* surv_young_words = _par_scan_state->surviving_young_words();
3750 surv_young_words[young_index] += word_sz;
3751
3752 if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
3753 arrayOop(old)->set_length(0);
3754 _par_scan_state->push_on_queue((oop*) ((intptr_t)old | G1_PARTIAL_ARRAY_MASK));
3755 } else {
3756 _scanner->set_region(_g1->heap_region_containing(obj));
3757 obj->oop_iterate_backwards(_scanner);
3758 }
3759 } else {
3760 _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz);
3761 obj = forward_ptr;
3762 }
3763 return obj;
3764 }
3765
3766 template<bool do_gen_barrier, G1Barrier barrier, bool do_mark_forwardee>
3767 void G1ParCopyClosure<do_gen_barrier, barrier, do_mark_forwardee>::do_oop_work(oop* p) {
3768 oop obj = *p;
3769 assert(barrier != G1BarrierRS || obj != NULL,
3770 "Precondition: G1BarrierRS implies obj is nonNull");
3771
3772 if (obj != NULL) {
3773 if (_g1->obj_in_cs(obj)) {
3774 #if G1_REM_SET_LOGGING
3775 gclog_or_tty->print_cr("Loc "PTR_FORMAT" contains pointer "PTR_FORMAT" into CS.",
3776 p, (void*) obj);
3777 #endif
3778 if (obj->is_forwarded()) {
3779 *p = obj->forwardee();
3780 } else {
3781 *p = copy_to_survivor_space(obj);
3782 }
3783 // When scanning the RS, we only care about objs in CS.
3784 if (barrier == G1BarrierRS) {
3785 _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
3786 }
3787 }
3788 // When scanning moved objs, must look at all oops.
3789 if (barrier == G1BarrierEvac) {
3790 _g1_rem->par_write_ref(_from, p, _par_scan_state->queue_num());
3791 }
3792
3793 if (do_gen_barrier) {
3794 par_do_barrier(p);
3795 }
3796 }
3797 }
3798
3799 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(oop* p);
3800
3801 template <class T> void G1ParScanPartialArrayClosure::process_array_chunk(
3802 oop obj, int start, int end) {
3803 // process our set of indices (include header in first chunk)
3804 assert(start < end, "invariant");
3805 T* const base = (T*)objArrayOop(obj)->base();
3806 T* const start_addr = base + start;
3807 T* const end_addr = base + end;
3808 MemRegion mr((HeapWord*)start_addr, (HeapWord*)end_addr);
3809 _scanner.set_region(_g1->heap_region_containing(obj));
3810 obj->oop_iterate(&_scanner, mr);
3811 }
3812
3813 void G1ParScanPartialArrayClosure::do_oop_nv(oop* p) {
3814 assert(!UseCompressedOops, "Needs to be fixed to work with compressed oops");
3815 oop old = oop((intptr_t)p & ~G1_PARTIAL_ARRAY_MASK);
3816 assert(old->is_objArray(), "must be obj array");
3817 assert(old->is_forwarded(), "must be forwarded");
3818 assert(Universe::heap()->is_in_reserved(old), "must be in heap.");
3819
3820 objArrayOop obj = objArrayOop(old->forwardee());
3821 assert((void*)old != (void*)old->forwardee(), "self forwarding here?");
3822 // Process ParGCArrayScanChunk elements now
3823 // and push the remainder back onto queue
3824 int start = arrayOop(old)->length();
3825 int end = obj->length();
3826 int remainder = end - start;
3827 assert(start <= end, "just checking");
3828 if (remainder > 2 * ParGCArrayScanChunk) {
3829 // Test above combines last partial chunk with a full chunk
3830 end = start + ParGCArrayScanChunk;
3831 arrayOop(old)->set_length(end);
3832 // Push remainder.
3833 _par_scan_state->push_on_queue((oop*) ((intptr_t) old | G1_PARTIAL_ARRAY_MASK));
3834 } else {
3835 // Restore length so that the heap remains parsable in
3836 // case of evacuation failure.
3837 arrayOop(old)->set_length(end);
3838 }
3839
3840 // process our set of indices (include header in first chunk)
3841 process_array_chunk<oop>(obj, start, end);
3842 oop* start_addr = start == 0 ? (oop*)obj : obj->obj_at_addr<oop>(start);
3843 oop* end_addr = (oop*)(obj->base()) + end; // obj_at_addr(end) asserts end < length
3844 MemRegion mr((HeapWord*)start_addr, (HeapWord*)end_addr);
3845 _scanner.set_region(_g1->heap_region_containing(obj));
3846 obj->oop_iterate(&_scanner, mr);
3847 }
3848
3849 int G1ScanAndBalanceClosure::_nq = 0;
3850
3851 class G1ParEvacuateFollowersClosure : public VoidClosure {
3852 protected:
3853 G1CollectedHeap* _g1h;
3854 G1ParScanThreadState* _par_scan_state;
3855 RefToScanQueueSet* _queues;
3856 ParallelTaskTerminator* _terminator;
3857
3858 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
3859 RefToScanQueueSet* queues() { return _queues; }
3860 ParallelTaskTerminator* terminator() { return _terminator; }
3861
3862 public:
3863 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
3864 G1ParScanThreadState* par_scan_state,
3865 RefToScanQueueSet* queues,
3866 ParallelTaskTerminator* terminator)
3867 : _g1h(g1h), _par_scan_state(par_scan_state),
3868 _queues(queues), _terminator(terminator) {}
3869
3870 void do_void() {
3871 G1ParScanThreadState* pss = par_scan_state();
3872 while (true) {
3873 oop* ref_to_scan;
3874 pss->trim_queue();
3875 IF_G1_DETAILED_STATS(pss->note_steal_attempt());
3876 if (queues()->steal(pss->queue_num(),
3877 pss->hash_seed(),
3878 ref_to_scan)) {
3879 IF_G1_DETAILED_STATS(pss->note_steal());
3880 pss->push_on_queue(ref_to_scan);
3881 continue;
3882 }
3883 pss->start_term_time();
3884 if (terminator()->offer_termination()) break;
3885 pss->end_term_time();
3886 }
3887 pss->end_term_time();
3888 pss->retire_alloc_buffers();
3889 }
3890 };
3891
3892 class G1ParTask : public AbstractGangTask {
3893 protected:
3894 G1CollectedHeap* _g1h;
3895 RefToScanQueueSet *_queues;
3896 ParallelTaskTerminator _terminator;
3897
3898 Mutex _stats_lock;
3899 Mutex* stats_lock() { return &_stats_lock; }
3900
3901 size_t getNCards() {
3902 return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
3903 / G1BlockOffsetSharedArray::N_bytes;
3904 }
3905
3906 public:
3907 G1ParTask(G1CollectedHeap* g1h, int workers, RefToScanQueueSet *task_queues)
3908 : AbstractGangTask("G1 collection"),
3909 _g1h(g1h),
3910 _queues(task_queues),
3911 _terminator(workers, _queues),
3912 _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
3913 {}
3914
3915 RefToScanQueueSet* queues() { return _queues; }
3916
3917 RefToScanQueue *work_queue(int i) {
3918 return queues()->queue(i);
3919 }
3920
3921 void work(int i) {
3922 ResourceMark rm;
3923 HandleMark hm;
3924
3925 G1ParScanThreadState pss(_g1h, i);
3926 G1ParScanHeapEvacClosure scan_evac_cl(_g1h, &pss);
3927 G1ParScanHeapEvacClosure evac_failure_cl(_g1h, &pss);
3928 G1ParScanPartialArrayClosure partial_scan_cl(_g1h, &pss);
3929
3930 pss.set_evac_closure(&scan_evac_cl);
3931 pss.set_evac_failure_closure(&evac_failure_cl);
3932 pss.set_partial_scan_closure(&partial_scan_cl);
3933
3934 G1ParScanExtRootClosure only_scan_root_cl(_g1h, &pss);
3935 G1ParScanPermClosure only_scan_perm_cl(_g1h, &pss);
3936 G1ParScanHeapRSClosure only_scan_heap_rs_cl(_g1h, &pss);
3937 G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss);
3938 G1ParScanAndMarkPermClosure scan_mark_perm_cl(_g1h, &pss);
3939 G1ParScanAndMarkHeapRSClosure scan_mark_heap_rs_cl(_g1h, &pss);
3940
3941 OopsInHeapRegionClosure *scan_root_cl;
3942 OopsInHeapRegionClosure *scan_perm_cl;
3943 OopsInHeapRegionClosure *scan_so_cl;
3944
3945 if (_g1h->g1_policy()->should_initiate_conc_mark()) {
3946 scan_root_cl = &scan_mark_root_cl;
3947 scan_perm_cl = &scan_mark_perm_cl;
3948 scan_so_cl = &scan_mark_heap_rs_cl;
3949 } else {
3950 scan_root_cl = &only_scan_root_cl;
3951 scan_perm_cl = &only_scan_perm_cl;
3952 scan_so_cl = &only_scan_heap_rs_cl;
3953 }
3954
3955 pss.start_strong_roots();
3956 _g1h->g1_process_strong_roots(/* not collecting perm */ false,
3957 SharedHeap::SO_AllClasses,
3958 scan_root_cl,
3959 &only_scan_heap_rs_cl,
3960 scan_so_cl,
3961 scan_perm_cl,
3962 i);
3963 pss.end_strong_roots();
3964 {
3965 double start = os::elapsedTime();
3966 G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
3967 evac.do_void();
3968 double elapsed_ms = (os::elapsedTime()-start)*1000.0;
3969 double term_ms = pss.term_time()*1000.0;
3970 _g1h->g1_policy()->record_obj_copy_time(i, elapsed_ms-term_ms);
3971 _g1h->g1_policy()->record_termination_time(i, term_ms);
3972 }
3973 _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
3974
3975 // Clean up any par-expanded rem sets.
3976 HeapRegionRemSet::par_cleanup();
3977
3978 MutexLocker x(stats_lock());
3979 if (ParallelGCVerbose) {
3980 gclog_or_tty->print("Thread %d complete:\n", i);
3981 #if G1_DETAILED_STATS
3982 gclog_or_tty->print(" Pushes: %7d Pops: %7d Overflows: %7d Steals %7d (in %d attempts)\n",
3983 pss.pushes(),
3984 pss.pops(),
3985 pss.overflow_pushes(),
3986 pss.steals(),
3987 pss.steal_attempts());
3988 #endif
3989 double elapsed = pss.elapsed();
3990 double strong_roots = pss.strong_roots_time();
3991 double term = pss.term_time();
3992 gclog_or_tty->print(" Elapsed: %7.2f ms.\n"
3993 " Strong roots: %7.2f ms (%6.2f%%)\n"
3994 " Termination: %7.2f ms (%6.2f%%) (in %d entries)\n",
3995 elapsed * 1000.0,
3996 strong_roots * 1000.0, (strong_roots*100.0/elapsed),
3997 term * 1000.0, (term*100.0/elapsed),
3998 pss.term_attempts());
3999 size_t total_waste = pss.alloc_buffer_waste() + pss.undo_waste();
4000 gclog_or_tty->print(" Waste: %8dK\n"
4001 " Alloc Buffer: %8dK\n"
4002 " Undo: %8dK\n",
4003 (total_waste * HeapWordSize) / K,
4004 (pss.alloc_buffer_waste() * HeapWordSize) / K,
4005 (pss.undo_waste() * HeapWordSize) / K);
4006 }
4007
4008 assert(pss.refs_to_scan() == 0, "Task queue should be empty");
4009 assert(pss.overflowed_refs_to_scan() == 0, "Overflow queue should be empty");
4010 }
4011 };
4012
4013 // *** Common G1 Evacuation Stuff
4014
4015 class G1CountClosure: public OopsInHeapRegionClosure {
4016 public:
4017 int n;
4018 G1CountClosure() : n(0) {}
4019 void do_oop(narrowOop* p) {
4020 guarantee(false, "NYI");
4021 }
4022 void do_oop(oop* p) {
4023 oop obj = *p;
4024 assert(obj != NULL && G1CollectedHeap::heap()->obj_in_cs(obj),
4025 "Rem set closure called on non-rem-set pointer.");
4026 n++;
4027 }
4028 };
4029
4030 static G1CountClosure count_closure;
4031
4032 void
4033 G1CollectedHeap::
4034 g1_process_strong_roots(bool collecting_perm_gen,
4035 SharedHeap::ScanningOption so,
4036 OopClosure* scan_non_heap_roots,
4037 OopsInHeapRegionClosure* scan_rs,
4038 OopsInHeapRegionClosure* scan_so,
4039 OopsInGenClosure* scan_perm,
4040 int worker_i) {
4041 // First scan the strong roots, including the perm gen.
4042 double ext_roots_start = os::elapsedTime();
4043 double closure_app_time_sec = 0.0;
4044
4045 BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
4046 BufferingOopsInGenClosure buf_scan_perm(scan_perm);
4047 buf_scan_perm.set_generation(perm_gen());
4048
4049 process_strong_roots(collecting_perm_gen, so,
4050 &buf_scan_non_heap_roots,
4051 &buf_scan_perm);
4052 // Finish up any enqueued closure apps.
4053 buf_scan_non_heap_roots.done();
4054 buf_scan_perm.done();
4055 double ext_roots_end = os::elapsedTime();
4056 g1_policy()->reset_obj_copy_time(worker_i);
4057 double obj_copy_time_sec =
4058 buf_scan_non_heap_roots.closure_app_seconds() +
4059 buf_scan_perm.closure_app_seconds();
4060 g1_policy()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
4061 double ext_root_time_ms =
4062 ((ext_roots_end - ext_roots_start) - obj_copy_time_sec) * 1000.0;
4063 g1_policy()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
4064
4065 // Scan strong roots in mark stack.
4066 if (!_process_strong_tasks->is_task_claimed(G1H_PS_mark_stack_oops_do)) {
4067 concurrent_mark()->oops_do(scan_non_heap_roots);
4068 }
4069 double mark_stack_scan_ms = (os::elapsedTime() - ext_roots_end) * 1000.0;
4070 g1_policy()->record_mark_stack_scan_time(worker_i, mark_stack_scan_ms);
4071
4072 // XXX What should this be doing in the parallel case?
4073 g1_policy()->record_collection_pause_end_CH_strong_roots();
4074 if (G1VerifyRemSet) {
4075 // :::: FIXME ::::
4076 // The stupid remembered set doesn't know how to filter out dead
4077 // objects, which the smart one does, and so when it is created
4078 // and then compared the number of entries in each differs and
4079 // the verification code fails.
4080 guarantee(false, "verification code is broken, see note");
4081
4082 // Let's make sure that the current rem set agrees with the stupidest
4083 // one possible!
4084 bool refs_enabled = ref_processor()->discovery_enabled();
4085 if (refs_enabled) ref_processor()->disable_discovery();
4086 StupidG1RemSet stupid(this);
4087 count_closure.n = 0;
4088 stupid.oops_into_collection_set_do(&count_closure, worker_i);
4089 int stupid_n = count_closure.n;
4090 count_closure.n = 0;
4091 g1_rem_set()->oops_into_collection_set_do(&count_closure, worker_i);
4092 guarantee(count_closure.n == stupid_n, "Old and new rem sets differ.");
4093 gclog_or_tty->print_cr("\nFound %d pointers in heap RS.", count_closure.n);
4094 if (refs_enabled) ref_processor()->enable_discovery();
4095 }
4096 if (scan_so != NULL) {
4097 scan_scan_only_set(scan_so, worker_i);
4098 }
4099 // Now scan the complement of the collection set.
4100 if (scan_rs != NULL) {
4101 g1_rem_set()->oops_into_collection_set_do(scan_rs, worker_i);
4102 }
4103 // Finish with the ref_processor roots.
4104 if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
4105 ref_processor()->oops_do(scan_non_heap_roots);
4106 }
4107 g1_policy()->record_collection_pause_end_G1_strong_roots();
4108 _process_strong_tasks->all_tasks_completed();
4109 }
4110
4111 void
4112 G1CollectedHeap::scan_scan_only_region(HeapRegion* r,
4113 OopsInHeapRegionClosure* oc,
4114 int worker_i) {
4115 HeapWord* startAddr = r->bottom();
4116 HeapWord* endAddr = r->used_region().end();
4117
4118 oc->set_region(r);
4119
4120 HeapWord* p = r->bottom();
4121 HeapWord* t = r->top();
4122 guarantee( p == r->next_top_at_mark_start(), "invariant" );
4123 while (p < t) {
4124 oop obj = oop(p);
4125 p += obj->oop_iterate(oc);
4126 }
4127 }
4128
4129 void
4130 G1CollectedHeap::scan_scan_only_set(OopsInHeapRegionClosure* oc,
4131 int worker_i) {
4132 double start = os::elapsedTime();
4133
4134 BufferingOopsInHeapRegionClosure boc(oc);
4135
4136 FilterInHeapRegionAndIntoCSClosure scan_only(this, &boc);
4137 FilterAndMarkInHeapRegionAndIntoCSClosure scan_and_mark(this, &boc, concurrent_mark());
4138
4139 OopsInHeapRegionClosure *foc;
4140 if (g1_policy()->should_initiate_conc_mark())
4141 foc = &scan_and_mark;
4142 else
4143 foc = &scan_only;
4144
4145 HeapRegion* hr;
4146 int n = 0;
4147 while ((hr = _young_list->par_get_next_scan_only_region()) != NULL) {
4148 scan_scan_only_region(hr, foc, worker_i);
4149 ++n;
4150 }
4151 boc.done();
4152
4153 double closure_app_s = boc.closure_app_seconds();
4154 g1_policy()->record_obj_copy_time(worker_i, closure_app_s * 1000.0);
4155 double ms = (os::elapsedTime() - start - closure_app_s)*1000.0;
4156 g1_policy()->record_scan_only_time(worker_i, ms, n);
4157 }
4158
4159 void
4160 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure,
4161 OopClosure* non_root_closure) {
4162 SharedHeap::process_weak_roots(root_closure, non_root_closure);
4163 }
4164
4165
4166 class SaveMarksClosure: public HeapRegionClosure {
4167 public:
4168 bool doHeapRegion(HeapRegion* r) {
4169 r->save_marks();
4170 return false;
4171 }
4172 };
4173
4174 void G1CollectedHeap::save_marks() {
4175 if (ParallelGCThreads == 0) {
4176 SaveMarksClosure sm;
4177 heap_region_iterate(&sm);
4178 }
4179 // We do this even in the parallel case
4180 perm_gen()->save_marks();
4181 }
4182
4183 void G1CollectedHeap::evacuate_collection_set() {
4184 set_evacuation_failed(false);
4185
4186 g1_rem_set()->prepare_for_oops_into_collection_set_do();
4187 concurrent_g1_refine()->set_use_cache(false);
4188 int n_workers = (ParallelGCThreads > 0 ? workers()->total_workers() : 1);
4189
4190 set_par_threads(n_workers);
4191 G1ParTask g1_par_task(this, n_workers, _task_queues);
4192
4193 init_for_evac_failure(NULL);
4194
4195 change_strong_roots_parity(); // In preparation for parallel strong roots.
4196 rem_set()->prepare_for_younger_refs_iterate(true);
4197 double start_par = os::elapsedTime();
4198
4199 if (ParallelGCThreads > 0) {
4200 // The individual threads will set their evac-failure closures.
4201 workers()->run_task(&g1_par_task);
4202 } else {
4203 g1_par_task.work(0);
4204 }
4205
4206 double par_time = (os::elapsedTime() - start_par) * 1000.0;
4207 g1_policy()->record_par_time(par_time);
4208 set_par_threads(0);
4209 // Is this the right thing to do here? We don't save marks
4210 // on individual heap regions when we allocate from
4211 // them in parallel, so this seems like the correct place for this.
4212 all_alloc_regions_note_end_of_copying();
4213 {
4214 G1IsAliveClosure is_alive(this);
4215 G1KeepAliveClosure keep_alive(this);
4216 JNIHandles::weak_oops_do(&is_alive, &keep_alive);
4217 }
4218
4219 g1_rem_set()->cleanup_after_oops_into_collection_set_do();
4220 concurrent_g1_refine()->set_use_cache(true);
4221
4222 finalize_for_evac_failure();
4223
4224 // Must do this before removing self-forwarding pointers, which clears
4225 // the per-region evac-failure flags.
4226 concurrent_mark()->complete_marking_in_collection_set();
4227
4228 if (evacuation_failed()) {
4229 remove_self_forwarding_pointers();
4230
4231 if (PrintGCDetails) {
4232 gclog_or_tty->print(" (evacuation failed)");
4233 } else if (PrintGC) {
4234 gclog_or_tty->print("--");
4235 }
4236 }
4237
4238 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
4239 }
4240
4241 void G1CollectedHeap::free_region(HeapRegion* hr) {
4242 size_t pre_used = 0;
4243 size_t cleared_h_regions = 0;
4244 size_t freed_regions = 0;
4245 UncleanRegionList local_list;
4246
4247 HeapWord* start = hr->bottom();
4248 HeapWord* end = hr->prev_top_at_mark_start();
4249 size_t used_bytes = hr->used();
4250 size_t live_bytes = hr->max_live_bytes();
4251 if (used_bytes > 0) {
4252 guarantee( live_bytes <= used_bytes, "invariant" );
4253 } else {
4254 guarantee( live_bytes == 0, "invariant" );
4255 }
4256
4257 size_t garbage_bytes = used_bytes - live_bytes;
4258 if (garbage_bytes > 0)
4259 g1_policy()->decrease_known_garbage_bytes(garbage_bytes);
4260
4261 free_region_work(hr, pre_used, cleared_h_regions, freed_regions,
4262 &local_list);
4263 finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
4264 &local_list);
4265 }
4266
4267 void
4268 G1CollectedHeap::free_region_work(HeapRegion* hr,
4269 size_t& pre_used,
4270 size_t& cleared_h_regions,
4271 size_t& freed_regions,
4272 UncleanRegionList* list,
4273 bool par) {
4274 assert(!hr->popular(), "should not free popular regions");
4275 pre_used += hr->used();
4276 if (hr->isHumongous()) {
4277 assert(hr->startsHumongous(),
4278 "Only the start of a humongous region should be freed.");
4279 int ind = _hrs->find(hr);
4280 assert(ind != -1, "Should have an index.");
4281 // Clear the start region.
4282 hr->hr_clear(par, true /*clear_space*/);
4283 list->insert_before_head(hr);
4284 cleared_h_regions++;
4285 freed_regions++;
4286 // Clear any continued regions.
4287 ind++;
4288 while ((size_t)ind < n_regions()) {
4289 HeapRegion* hrc = _hrs->at(ind);
4290 if (!hrc->continuesHumongous()) break;
4291 // Otherwise, does continue the H region.
4292 assert(hrc->humongous_start_region() == hr, "Huh?");
4293 hrc->hr_clear(par, true /*clear_space*/);
4294 cleared_h_regions++;
4295 freed_regions++;
4296 list->insert_before_head(hrc);
4297 ind++;
4298 }
4299 } else {
4300 hr->hr_clear(par, true /*clear_space*/);
4301 list->insert_before_head(hr);
4302 freed_regions++;
4303 // If we're using clear2, this should not be enabled.
4304 // assert(!hr->in_cohort(), "Can't be both free and in a cohort.");
4305 }
4306 }
4307
4308 void G1CollectedHeap::finish_free_region_work(size_t pre_used,
4309 size_t cleared_h_regions,
4310 size_t freed_regions,
4311 UncleanRegionList* list) {
4312 if (list != NULL && list->sz() > 0) {
4313 prepend_region_list_on_unclean_list(list);
4314 }
4315 // Acquire a lock, if we're parallel, to update possibly-shared
4316 // variables.
4317 Mutex* lock = (n_par_threads() > 0) ? ParGCRareEvent_lock : NULL;
4318 {
4319 MutexLockerEx x(lock, Mutex::_no_safepoint_check_flag);
4320 _summary_bytes_used -= pre_used;
4321 _num_humongous_regions -= (int) cleared_h_regions;
4322 _free_regions += freed_regions;
4323 }
4324 }
4325
4326
4327 void G1CollectedHeap::dirtyCardsForYoungRegions(CardTableModRefBS* ct_bs, HeapRegion* list) {
4328 while (list != NULL) {
4329 guarantee( list->is_young(), "invariant" );
4330
4331 HeapWord* bottom = list->bottom();
4332 HeapWord* end = list->end();
4333 MemRegion mr(bottom, end);
4334 ct_bs->dirty(mr);
4335
4336 list = list->get_next_young_region();
4337 }
4338 }
4339
4340 void G1CollectedHeap::cleanUpCardTable() {
4341 CardTableModRefBS* ct_bs = (CardTableModRefBS*) (barrier_set());
4342 double start = os::elapsedTime();
4343
4344 ct_bs->clear(_g1_committed);
4345
4346 // now, redirty the cards of the scan-only and survivor regions
4347 // (it seemed faster to do it this way, instead of iterating over
4348 // all regions and then clearing / dirtying as approprite)
4349 dirtyCardsForYoungRegions(ct_bs, _young_list->first_scan_only_region());
4350 dirtyCardsForYoungRegions(ct_bs, _young_list->first_survivor_region());
4351
4352 double elapsed = os::elapsedTime() - start;
4353 g1_policy()->record_clear_ct_time( elapsed * 1000.0);
4354 }
4355
4356
4357 void G1CollectedHeap::do_collection_pause_if_appropriate(size_t word_size) {
4358 // First do any popular regions.
4359 HeapRegion* hr;
4360 while ((hr = popular_region_to_evac()) != NULL) {
4361 evac_popular_region(hr);
4362 }
4363 // Now do heuristic pauses.
4364 if (g1_policy()->should_do_collection_pause(word_size)) {
4365 do_collection_pause();
4366 }
4367 }
4368
4369 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head) {
4370 double young_time_ms = 0.0;
4371 double non_young_time_ms = 0.0;
4372
4373 G1CollectorPolicy* policy = g1_policy();
4374
4375 double start_sec = os::elapsedTime();
4376 bool non_young = true;
4377
4378 HeapRegion* cur = cs_head;
4379 int age_bound = -1;
4380 size_t rs_lengths = 0;
4381
4382 while (cur != NULL) {
4383 if (non_young) {
4384 if (cur->is_young()) {
4385 double end_sec = os::elapsedTime();
4386 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4387 non_young_time_ms += elapsed_ms;
4388
4389 start_sec = os::elapsedTime();
4390 non_young = false;
4391 }
4392 } else {
4393 if (!cur->is_on_free_list()) {
4394 double end_sec = os::elapsedTime();
4395 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4396 young_time_ms += elapsed_ms;
4397
4398 start_sec = os::elapsedTime();
4399 non_young = true;
4400 }
4401 }
4402
4403 rs_lengths += cur->rem_set()->occupied();
4404
4405 HeapRegion* next = cur->next_in_collection_set();
4406 assert(cur->in_collection_set(), "bad CS");
4407 cur->set_next_in_collection_set(NULL);
4408 cur->set_in_collection_set(false);
4409
4410 if (cur->is_young()) {
4411 int index = cur->young_index_in_cset();
4412 guarantee( index != -1, "invariant" );
4413 guarantee( (size_t)index < policy->young_cset_length(), "invariant" );
4414 size_t words_survived = _surviving_young_words[index];
4415 cur->record_surv_words_in_group(words_survived);
4416 } else {
4417 int index = cur->young_index_in_cset();
4418 guarantee( index == -1, "invariant" );
4419 }
4420
4421 assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
4422 (!cur->is_young() && cur->young_index_in_cset() == -1),
4423 "invariant" );
4424
4425 if (!cur->evacuation_failed()) {
4426 // And the region is empty.
4427 assert(!cur->is_empty(),
4428 "Should not have empty regions in a CS.");
4429 free_region(cur);
4430 } else {
4431 guarantee( !cur->is_scan_only(), "should not be scan only" );
4432 cur->uninstall_surv_rate_group();
4433 if (cur->is_young())
4434 cur->set_young_index_in_cset(-1);
4435 cur->set_not_young();
4436 cur->set_evacuation_failed(false);
4437 }
4438 cur = next;
4439 }
4440
4441 policy->record_max_rs_lengths(rs_lengths);
4442 policy->cset_regions_freed();
4443
4444 double end_sec = os::elapsedTime();
4445 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4446 if (non_young)
4447 non_young_time_ms += elapsed_ms;
4448 else
4449 young_time_ms += elapsed_ms;
4450
4451 policy->record_young_free_cset_time_ms(young_time_ms);
4452 policy->record_non_young_free_cset_time_ms(non_young_time_ms);
4453 }
4454
4455 HeapRegion*
4456 G1CollectedHeap::alloc_region_from_unclean_list_locked(bool zero_filled) {
4457 assert(ZF_mon->owned_by_self(), "Precondition");
4458 HeapRegion* res = pop_unclean_region_list_locked();
4459 if (res != NULL) {
4460 assert(!res->continuesHumongous() &&
4461 res->zero_fill_state() != HeapRegion::Allocated,
4462 "Only free regions on unclean list.");
4463 if (zero_filled) {
4464 res->ensure_zero_filled_locked();
4465 res->set_zero_fill_allocated();
4466 }
4467 }
4468 return res;
4469 }
4470
4471 HeapRegion* G1CollectedHeap::alloc_region_from_unclean_list(bool zero_filled) {
4472 MutexLockerEx zx(ZF_mon, Mutex::_no_safepoint_check_flag);
4473 return alloc_region_from_unclean_list_locked(zero_filled);
4474 }
4475
4476 void G1CollectedHeap::put_region_on_unclean_list(HeapRegion* r) {
4477 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4478 put_region_on_unclean_list_locked(r);
4479 if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
4480 }
4481
4482 void G1CollectedHeap::set_unclean_regions_coming(bool b) {
4483 MutexLockerEx x(Cleanup_mon);
4484 set_unclean_regions_coming_locked(b);
4485 }
4486
4487 void G1CollectedHeap::set_unclean_regions_coming_locked(bool b) {
4488 assert(Cleanup_mon->owned_by_self(), "Precondition");
4489 _unclean_regions_coming = b;
4490 // Wake up mutator threads that might be waiting for completeCleanup to
4491 // finish.
4492 if (!b) Cleanup_mon->notify_all();
4493 }
4494
4495 void G1CollectedHeap::wait_for_cleanup_complete() {
4496 MutexLockerEx x(Cleanup_mon);
4497 wait_for_cleanup_complete_locked();
4498 }
4499
4500 void G1CollectedHeap::wait_for_cleanup_complete_locked() {
4501 assert(Cleanup_mon->owned_by_self(), "precondition");
4502 while (_unclean_regions_coming) {
4503 Cleanup_mon->wait();
4504 }
4505 }
4506
4507 void
4508 G1CollectedHeap::put_region_on_unclean_list_locked(HeapRegion* r) {
4509 assert(ZF_mon->owned_by_self(), "precondition.");
4510 _unclean_region_list.insert_before_head(r);
4511 }
4512
4513 void
4514 G1CollectedHeap::prepend_region_list_on_unclean_list(UncleanRegionList* list) {
4515 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4516 prepend_region_list_on_unclean_list_locked(list);
4517 if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
4518 }
4519
4520 void
4521 G1CollectedHeap::
4522 prepend_region_list_on_unclean_list_locked(UncleanRegionList* list) {
4523 assert(ZF_mon->owned_by_self(), "precondition.");
4524 _unclean_region_list.prepend_list(list);
4525 }
4526
4527 HeapRegion* G1CollectedHeap::pop_unclean_region_list_locked() {
4528 assert(ZF_mon->owned_by_self(), "precondition.");
4529 HeapRegion* res = _unclean_region_list.pop();
4530 if (res != NULL) {
4531 // Inform ZF thread that there's a new unclean head.
4532 if (_unclean_region_list.hd() != NULL && should_zf())
4533 ZF_mon->notify_all();
4534 }
4535 return res;
4536 }
4537
4538 HeapRegion* G1CollectedHeap::peek_unclean_region_list_locked() {
4539 assert(ZF_mon->owned_by_self(), "precondition.");
4540 return _unclean_region_list.hd();
4541 }
4542
4543
4544 bool G1CollectedHeap::move_cleaned_region_to_free_list_locked() {
4545 assert(ZF_mon->owned_by_self(), "Precondition");
4546 HeapRegion* r = peek_unclean_region_list_locked();
4547 if (r != NULL && r->zero_fill_state() == HeapRegion::ZeroFilled) {
4548 // Result of below must be equal to "r", since we hold the lock.
4549 (void)pop_unclean_region_list_locked();
4550 put_free_region_on_list_locked(r);
4551 return true;
4552 } else {
4553 return false;
4554 }
4555 }
4556
4557 bool G1CollectedHeap::move_cleaned_region_to_free_list() {
4558 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4559 return move_cleaned_region_to_free_list_locked();
4560 }
4561
4562
4563 void G1CollectedHeap::put_free_region_on_list_locked(HeapRegion* r) {
4564 assert(ZF_mon->owned_by_self(), "precondition.");
4565 assert(_free_region_list_size == free_region_list_length(), "Inv");
4566 assert(r->zero_fill_state() == HeapRegion::ZeroFilled,
4567 "Regions on free list must be zero filled");
4568 assert(!r->isHumongous(), "Must not be humongous.");
4569 assert(r->is_empty(), "Better be empty");
4570 assert(!r->is_on_free_list(),
4571 "Better not already be on free list");
4572 assert(!r->is_on_unclean_list(),
4573 "Better not already be on unclean list");
4574 r->set_on_free_list(true);
4575 r->set_next_on_free_list(_free_region_list);
4576 _free_region_list = r;
4577 _free_region_list_size++;
4578 assert(_free_region_list_size == free_region_list_length(), "Inv");
4579 }
4580
4581 void G1CollectedHeap::put_free_region_on_list(HeapRegion* r) {
4582 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4583 put_free_region_on_list_locked(r);
4584 }
4585
4586 HeapRegion* G1CollectedHeap::pop_free_region_list_locked() {
4587 assert(ZF_mon->owned_by_self(), "precondition.");
4588 assert(_free_region_list_size == free_region_list_length(), "Inv");
4589 HeapRegion* res = _free_region_list;
4590 if (res != NULL) {
4591 _free_region_list = res->next_from_free_list();
4592 _free_region_list_size--;
4593 res->set_on_free_list(false);
4594 res->set_next_on_free_list(NULL);
4595 assert(_free_region_list_size == free_region_list_length(), "Inv");
4596 }
4597 return res;
4598 }
4599
4600
4601 HeapRegion* G1CollectedHeap::alloc_free_region_from_lists(bool zero_filled) {
4602 // By self, or on behalf of self.
4603 assert(Heap_lock->is_locked(), "Precondition");
4604 HeapRegion* res = NULL;
4605 bool first = true;
4606 while (res == NULL) {
4607 if (zero_filled || !first) {
4608 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4609 res = pop_free_region_list_locked();
4610 if (res != NULL) {
4611 assert(!res->zero_fill_is_allocated(),
4612 "No allocated regions on free list.");
4613 res->set_zero_fill_allocated();
4614 } else if (!first) {
4615 break; // We tried both, time to return NULL.
4616 }
4617 }
4618
4619 if (res == NULL) {
4620 res = alloc_region_from_unclean_list(zero_filled);
4621 }
4622 assert(res == NULL ||
4623 !zero_filled ||
4624 res->zero_fill_is_allocated(),
4625 "We must have allocated the region we're returning");
4626 first = false;
4627 }
4628 return res;
4629 }
4630
4631 void G1CollectedHeap::remove_allocated_regions_from_lists() {
4632 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4633 {
4634 HeapRegion* prev = NULL;
4635 HeapRegion* cur = _unclean_region_list.hd();
4636 while (cur != NULL) {
4637 HeapRegion* next = cur->next_from_unclean_list();
4638 if (cur->zero_fill_is_allocated()) {
4639 // Remove from the list.
4640 if (prev == NULL) {
4641 (void)_unclean_region_list.pop();
4642 } else {
4643 _unclean_region_list.delete_after(prev);
4644 }
4645 cur->set_on_unclean_list(false);
4646 cur->set_next_on_unclean_list(NULL);
4647 } else {
4648 prev = cur;
4649 }
4650 cur = next;
4651 }
4652 assert(_unclean_region_list.sz() == unclean_region_list_length(),
4653 "Inv");
4654 }
4655
4656 {
4657 HeapRegion* prev = NULL;
4658 HeapRegion* cur = _free_region_list;
4659 while (cur != NULL) {
4660 HeapRegion* next = cur->next_from_free_list();
4661 if (cur->zero_fill_is_allocated()) {
4662 // Remove from the list.
4663 if (prev == NULL) {
4664 _free_region_list = cur->next_from_free_list();
4665 } else {
4666 prev->set_next_on_free_list(cur->next_from_free_list());
4667 }
4668 cur->set_on_free_list(false);
4669 cur->set_next_on_free_list(NULL);
4670 _free_region_list_size--;
4671 } else {
4672 prev = cur;
4673 }
4674 cur = next;
4675 }
4676 assert(_free_region_list_size == free_region_list_length(), "Inv");
4677 }
4678 }
4679
4680 bool G1CollectedHeap::verify_region_lists() {
4681 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4682 return verify_region_lists_locked();
4683 }
4684
4685 bool G1CollectedHeap::verify_region_lists_locked() {
4686 HeapRegion* unclean = _unclean_region_list.hd();
4687 while (unclean != NULL) {
4688 guarantee(unclean->is_on_unclean_list(), "Well, it is!");
4689 guarantee(!unclean->is_on_free_list(), "Well, it shouldn't be!");
4690 guarantee(unclean->zero_fill_state() != HeapRegion::Allocated,
4691 "Everything else is possible.");
4692 unclean = unclean->next_from_unclean_list();
4693 }
4694 guarantee(_unclean_region_list.sz() == unclean_region_list_length(), "Inv");
4695
4696 HeapRegion* free_r = _free_region_list;
4697 while (free_r != NULL) {
4698 assert(free_r->is_on_free_list(), "Well, it is!");
4699 assert(!free_r->is_on_unclean_list(), "Well, it shouldn't be!");
4700 switch (free_r->zero_fill_state()) {
4701 case HeapRegion::NotZeroFilled:
4702 case HeapRegion::ZeroFilling:
4703 guarantee(false, "Should not be on free list.");
4704 break;
4705 default:
4706 // Everything else is possible.
4707 break;
4708 }
4709 free_r = free_r->next_from_free_list();
4710 }
4711 guarantee(_free_region_list_size == free_region_list_length(), "Inv");
4712 // If we didn't do an assertion...
4713 return true;
4714 }
4715
4716 size_t G1CollectedHeap::free_region_list_length() {
4717 assert(ZF_mon->owned_by_self(), "precondition.");
4718 size_t len = 0;
4719 HeapRegion* cur = _free_region_list;
4720 while (cur != NULL) {
4721 len++;
4722 cur = cur->next_from_free_list();
4723 }
4724 return len;
4725 }
4726
4727 size_t G1CollectedHeap::unclean_region_list_length() {
4728 assert(ZF_mon->owned_by_self(), "precondition.");
4729 return _unclean_region_list.length();
4730 }
4731
4732 size_t G1CollectedHeap::n_regions() {
4733 return _hrs->length();
4734 }
4735
4736 size_t G1CollectedHeap::max_regions() {
4737 return
4738 (size_t)align_size_up(g1_reserved_obj_bytes(), HeapRegion::GrainBytes) /
4739 HeapRegion::GrainBytes;
4740 }
4741
4742 size_t G1CollectedHeap::free_regions() {
4743 /* Possibly-expensive assert.
4744 assert(_free_regions == count_free_regions(),
4745 "_free_regions is off.");
4746 */
4747 return _free_regions;
4748 }
4749
4750 bool G1CollectedHeap::should_zf() {
4751 return _free_region_list_size < (size_t) G1ConcZFMaxRegions;
4752 }
4753
4754 class RegionCounter: public HeapRegionClosure {
4755 size_t _n;
4756 public:
4757 RegionCounter() : _n(0) {}
4758 bool doHeapRegion(HeapRegion* r) {
4759 if (r->is_empty() && !r->popular()) {
4760 assert(!r->isHumongous(), "H regions should not be empty.");
4761 _n++;
4762 }
4763 return false;
4764 }
4765 int res() { return (int) _n; }
4766 };
4767
4768 size_t G1CollectedHeap::count_free_regions() {
4769 RegionCounter rc;
4770 heap_region_iterate(&rc);
4771 size_t n = rc.res();
4772 if (_cur_alloc_region != NULL && _cur_alloc_region->is_empty())
4773 n--;
4774 return n;
4775 }
4776
4777 size_t G1CollectedHeap::count_free_regions_list() {
4778 size_t n = 0;
4779 size_t o = 0;
4780 ZF_mon->lock_without_safepoint_check();
4781 HeapRegion* cur = _free_region_list;
4782 while (cur != NULL) {
4783 cur = cur->next_from_free_list();
4784 n++;
4785 }
4786 size_t m = unclean_region_list_length();
4787 ZF_mon->unlock();
4788 return n + m;
4789 }
4790
4791 bool G1CollectedHeap::should_set_young_locked() {
4792 assert(heap_lock_held_for_gc(),
4793 "the heap lock should already be held by or for this thread");
4794 return (g1_policy()->in_young_gc_mode() &&
4795 g1_policy()->should_add_next_region_to_young_list());
4796 }
4797
4798 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
4799 assert(heap_lock_held_for_gc(),
4800 "the heap lock should already be held by or for this thread");
4801 _young_list->push_region(hr);
4802 g1_policy()->set_region_short_lived(hr);
4803 }
4804
4805 class NoYoungRegionsClosure: public HeapRegionClosure {
4806 private:
4807 bool _success;
4808 public:
4809 NoYoungRegionsClosure() : _success(true) { }
4810 bool doHeapRegion(HeapRegion* r) {
4811 if (r->is_young()) {
4812 gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
4813 r->bottom(), r->end());
4814 _success = false;
4815 }
4816 return false;
4817 }
4818 bool success() { return _success; }
4819 };
4820
4821 bool G1CollectedHeap::check_young_list_empty(bool ignore_scan_only_list,
4822 bool check_sample) {
4823 bool ret = true;
4824
4825 ret = _young_list->check_list_empty(ignore_scan_only_list, check_sample);
4826 if (!ignore_scan_only_list) {
4827 NoYoungRegionsClosure closure;
4828 heap_region_iterate(&closure);
4829 ret = ret && closure.success();
4830 }
4831
4832 return ret;
4833 }
4834
4835 void G1CollectedHeap::empty_young_list() {
4836 assert(heap_lock_held_for_gc(),
4837 "the heap lock should already be held by or for this thread");
4838 assert(g1_policy()->in_young_gc_mode(), "should be in young GC mode");
4839
4840 _young_list->empty_list();
4841 }
4842
4843 bool G1CollectedHeap::all_alloc_regions_no_allocs_since_save_marks() {
4844 bool no_allocs = true;
4845 for (int ap = 0; ap < GCAllocPurposeCount && no_allocs; ++ap) {
4846 HeapRegion* r = _gc_alloc_regions[ap];
4847 no_allocs = r == NULL || r->saved_mark_at_top();
4848 }
4849 return no_allocs;
4850 }
4851
4852 void G1CollectedHeap::all_alloc_regions_note_end_of_copying() {
4853 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
4854 HeapRegion* r = _gc_alloc_regions[ap];
4855 if (r != NULL) {
4856 // Check for aliases.
4857 bool has_processed_alias = false;
4858 for (int i = 0; i < ap; ++i) {
4859 if (_gc_alloc_regions[i] == r) {
4860 has_processed_alias = true;
4861 break;
4862 }
4863 }
4864 if (!has_processed_alias) {
4865 r->note_end_of_copying();
4866 g1_policy()->record_after_bytes(r->used());
4867 }
4868 }
4869 }
4870 }
4871
4872
4873 // Done at the start of full GC.
4874 void G1CollectedHeap::tear_down_region_lists() {
4875 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4876 while (pop_unclean_region_list_locked() != NULL) ;
4877 assert(_unclean_region_list.hd() == NULL && _unclean_region_list.sz() == 0,
4878 "Postconditions of loop.")
4879 while (pop_free_region_list_locked() != NULL) ;
4880 assert(_free_region_list == NULL, "Postcondition of loop.");
4881 if (_free_region_list_size != 0) {
4882 gclog_or_tty->print_cr("Size is %d.", _free_region_list_size);
4883 print();
4884 }
4885 assert(_free_region_list_size == 0, "Postconditions of loop.");
4886 }
4887
4888
4889 class RegionResetter: public HeapRegionClosure {
4890 G1CollectedHeap* _g1;
4891 int _n;
4892 public:
4893 RegionResetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
4894 bool doHeapRegion(HeapRegion* r) {
4895 if (r->continuesHumongous()) return false;
4896 if (r->top() > r->bottom()) {
4897 if (r->top() < r->end()) {
4898 Copy::fill_to_words(r->top(),
4899 pointer_delta(r->end(), r->top()));
4900 }
4901 r->set_zero_fill_allocated();
4902 } else {
4903 assert(r->is_empty(), "tautology");
4904 if (r->popular()) {
4905 if (r->zero_fill_state() != HeapRegion::Allocated) {
4906 r->ensure_zero_filled_locked();
4907 r->set_zero_fill_allocated();
4908 }
4909 } else {
4910 _n++;
4911 switch (r->zero_fill_state()) {
4912 case HeapRegion::NotZeroFilled:
4913 case HeapRegion::ZeroFilling:
4914 _g1->put_region_on_unclean_list_locked(r);
4915 break;
4916 case HeapRegion::Allocated:
4917 r->set_zero_fill_complete();
4918 // no break; go on to put on free list.
4919 case HeapRegion::ZeroFilled:
4920 _g1->put_free_region_on_list_locked(r);
4921 break;
4922 }
4923 }
4924 }
4925 return false;
4926 }
4927
4928 int getFreeRegionCount() {return _n;}
4929 };
4930
4931 // Done at the end of full GC.
4932 void G1CollectedHeap::rebuild_region_lists() {
4933 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4934 // This needs to go at the end of the full GC.
4935 RegionResetter rs;
4936 heap_region_iterate(&rs);
4937 _free_regions = rs.getFreeRegionCount();
4938 // Tell the ZF thread it may have work to do.
4939 if (should_zf()) ZF_mon->notify_all();
4940 }
4941
4942 class UsedRegionsNeedZeroFillSetter: public HeapRegionClosure {
4943 G1CollectedHeap* _g1;
4944 int _n;
4945 public:
4946 UsedRegionsNeedZeroFillSetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
4947 bool doHeapRegion(HeapRegion* r) {
4948 if (r->continuesHumongous()) return false;
4949 if (r->top() > r->bottom()) {
4950 // There are assertions in "set_zero_fill_needed()" below that
4951 // require top() == bottom(), so this is technically illegal.
4952 // We'll skirt the law here, by making that true temporarily.
4953 DEBUG_ONLY(HeapWord* save_top = r->top();
4954 r->set_top(r->bottom()));
4955 r->set_zero_fill_needed();
4956 DEBUG_ONLY(r->set_top(save_top));
4957 }
4958 return false;
4959 }
4960 };
4961
4962 // Done at the start of full GC.
4963 void G1CollectedHeap::set_used_regions_to_need_zero_fill() {
4964 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4965 // This needs to go at the end of the full GC.
4966 UsedRegionsNeedZeroFillSetter rs;
4967 heap_region_iterate(&rs);
4968 }
4969
4970 class CountObjClosure: public ObjectClosure {
4971 size_t _n;
4972 public:
4973 CountObjClosure() : _n(0) {}
4974 void do_object(oop obj) { _n++; }
4975 size_t n() { return _n; }
4976 };
4977
4978 size_t G1CollectedHeap::pop_object_used_objs() {
4979 size_t sum_objs = 0;
4980 for (int i = 0; i < G1NumPopularRegions; i++) {
4981 CountObjClosure cl;
4982 _hrs->at(i)->object_iterate(&cl);
4983 sum_objs += cl.n();
4984 }
4985 return sum_objs;
4986 }
4987
4988 size_t G1CollectedHeap::pop_object_used_bytes() {
4989 size_t sum_bytes = 0;
4990 for (int i = 0; i < G1NumPopularRegions; i++) {
4991 sum_bytes += _hrs->at(i)->used();
4992 }
4993 return sum_bytes;
4994 }
4995
4996
4997 static int nq = 0;
4998
4999 HeapWord* G1CollectedHeap::allocate_popular_object(size_t word_size) {
5000 while (_cur_pop_hr_index < G1NumPopularRegions) {
5001 HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
5002 HeapWord* res = cur_pop_region->allocate(word_size);
5003 if (res != NULL) {
5004 // We account for popular objs directly in the used summary:
5005 _summary_bytes_used += (word_size * HeapWordSize);
5006 return res;
5007 }
5008 // Otherwise, try the next region (first making sure that we remember
5009 // the last "top" value as the "next_top_at_mark_start", so that
5010 // objects made popular during markings aren't automatically considered
5011 // live).
5012 cur_pop_region->note_end_of_copying();
5013 // Otherwise, try the next region.
5014 _cur_pop_hr_index++;
5015 }
5016 // XXX: For now !!!
5017 vm_exit_out_of_memory(word_size,
5018 "Not enough pop obj space (To Be Fixed)");
5019 return NULL;
5020 }
5021
5022 class HeapRegionList: public CHeapObj {
5023 public:
5024 HeapRegion* hr;
5025 HeapRegionList* next;
5026 };
5027
5028 void G1CollectedHeap::schedule_popular_region_evac(HeapRegion* r) {
5029 // This might happen during parallel GC, so protect by this lock.
5030 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
5031 // We don't schedule regions whose evacuations are already pending, or
5032 // are already being evacuated.
5033 if (!r->popular_pending() && !r->in_collection_set()) {
5034 r->set_popular_pending(true);
5035 if (G1TracePopularity) {
5036 gclog_or_tty->print_cr("Scheduling region "PTR_FORMAT" "
5037 "["PTR_FORMAT", "PTR_FORMAT") for pop-object evacuation.",
5038 r, r->bottom(), r->end());
5039 }
5040 HeapRegionList* hrl = new HeapRegionList;
5041 hrl->hr = r;
5042 hrl->next = _popular_regions_to_be_evacuated;
5043 _popular_regions_to_be_evacuated = hrl;
5044 }
5045 }
5046
5047 HeapRegion* G1CollectedHeap::popular_region_to_evac() {
5048 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
5049 HeapRegion* res = NULL;
5050 while (_popular_regions_to_be_evacuated != NULL && res == NULL) {
5051 HeapRegionList* hrl = _popular_regions_to_be_evacuated;
5052 _popular_regions_to_be_evacuated = hrl->next;
5053 res = hrl->hr;
5054 // The G1RSPopLimit may have increased, so recheck here...
5055 if (res->rem_set()->occupied() < (size_t) G1RSPopLimit) {
5056 // Hah: don't need to schedule.
5057 if (G1TracePopularity) {
5058 gclog_or_tty->print_cr("Unscheduling region "PTR_FORMAT" "
5059 "["PTR_FORMAT", "PTR_FORMAT") "
5060 "for pop-object evacuation (size %d < limit %d)",
5061 res, res->bottom(), res->end(),
5062 res->rem_set()->occupied(), G1RSPopLimit);
5063 }
5064 res->set_popular_pending(false);
5065 res = NULL;
5066 }
5067 // We do not reset res->popular() here; if we did so, it would allow
5068 // the region to be "rescheduled" for popularity evacuation. Instead,
5069 // this is done in the collection pause, with the world stopped.
5070 // So the invariant is that the regions in the list have the popularity
5071 // boolean set, but having the boolean set does not imply membership
5072 // on the list (though there can at most one such pop-pending region
5073 // not on the list at any time).
5074 delete hrl;
5075 }
5076 return res;
5077 }
5078
5079 void G1CollectedHeap::evac_popular_region(HeapRegion* hr) {
5080 while (true) {
5081 // Don't want to do a GC pause while cleanup is being completed!
5082 wait_for_cleanup_complete();
5083
5084 // Read the GC count while holding the Heap_lock
5085 int gc_count_before = SharedHeap::heap()->total_collections();
5086 g1_policy()->record_stop_world_start();
5087
5088 {
5089 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back
5090 VM_G1PopRegionCollectionPause op(gc_count_before, hr);
5091 VMThread::execute(&op);
5092
5093 // If the prolog succeeded, we didn't do a GC for this.
5094 if (op.prologue_succeeded()) break;
5095 }
5096 // Otherwise we didn't. We should recheck the size, though, since
5097 // the limit may have increased...
5098 if (hr->rem_set()->occupied() < (size_t) G1RSPopLimit) {
5099 hr->set_popular_pending(false);
5100 break;
5101 }
5102 }
5103 }
5104
5105 void G1CollectedHeap::atomic_inc_obj_rc(oop obj) {
5106 Atomic::inc(obj_rc_addr(obj));
5107 }
5108
5109 class CountRCClosure: public OopsInHeapRegionClosure {
5110 G1CollectedHeap* _g1h;
5111 bool _parallel;
5112 public:
5113 CountRCClosure(G1CollectedHeap* g1h) :
5114 _g1h(g1h), _parallel(ParallelGCThreads > 0)
5115 {}
5116 void do_oop(narrowOop* p) {
5117 guarantee(false, "NYI");
5118 }
5119 void do_oop(oop* p) {
5120 oop obj = *p;
5121 assert(obj != NULL, "Precondition.");
5122 if (_parallel) {
5123 // We go sticky at the limit to avoid excess contention.
5124 // If we want to track the actual RC's further, we'll need to keep a
5125 // per-thread hash table or something for the popular objects.
5126 if (_g1h->obj_rc(obj) < G1ObjPopLimit) {
5127 _g1h->atomic_inc_obj_rc(obj);
5128 }
5129 } else {
5130 _g1h->inc_obj_rc(obj);
5131 }
5132 }
5133 };
5134
5135 class EvacPopObjClosure: public ObjectClosure {
5136 G1CollectedHeap* _g1h;
5137 size_t _pop_objs;
5138 size_t _max_rc;
5139 public:
5140 EvacPopObjClosure(G1CollectedHeap* g1h) :
5141 _g1h(g1h), _pop_objs(0), _max_rc(0) {}
5142
5143 void do_object(oop obj) {
5144 size_t rc = _g1h->obj_rc(obj);
5145 _max_rc = MAX2(rc, _max_rc);
5146 if (rc >= (size_t) G1ObjPopLimit) {
5147 _g1h->_pop_obj_rc_at_copy.add((double)rc);
5148 size_t word_sz = obj->size();
5149 HeapWord* new_pop_loc = _g1h->allocate_popular_object(word_sz);
5150 oop new_pop_obj = (oop)new_pop_loc;
5151 Copy::aligned_disjoint_words((HeapWord*)obj, new_pop_loc, word_sz);
5152 obj->forward_to(new_pop_obj);
5153 G1ScanAndBalanceClosure scan_and_balance(_g1h);
5154 new_pop_obj->oop_iterate_backwards(&scan_and_balance);
5155 // preserve "next" mark bit if marking is in progress.
5156 if (_g1h->mark_in_progress() && !_g1h->is_obj_ill(obj)) {
5157 _g1h->concurrent_mark()->markAndGrayObjectIfNecessary(new_pop_obj);
5158 }
5159
5160 if (G1TracePopularity) {
5161 gclog_or_tty->print_cr("Found obj " PTR_FORMAT " of word size " SIZE_FORMAT
5162 " pop (%d), move to " PTR_FORMAT,
5163 (void*) obj, word_sz,
5164 _g1h->obj_rc(obj), (void*) new_pop_obj);
5165 }
5166 _pop_objs++;
5167 }
5168 }
5169 size_t pop_objs() { return _pop_objs; }
5170 size_t max_rc() { return _max_rc; }
5171 };
5172
5173 class G1ParCountRCTask : public AbstractGangTask {
5174 G1CollectedHeap* _g1h;
5175 BitMap _bm;
5176
5177 size_t getNCards() {
5178 return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
5179 / G1BlockOffsetSharedArray::N_bytes;
5180 }
5181 CountRCClosure _count_rc_closure;
5182 public:
5183 G1ParCountRCTask(G1CollectedHeap* g1h) :
5184 AbstractGangTask("G1 Par RC Count task"),
5185 _g1h(g1h), _bm(getNCards()), _count_rc_closure(g1h)
5186 {}
5187
5188 void work(int i) {
5189 ResourceMark rm;
5190 HandleMark hm;
5191 _g1h->g1_rem_set()->oops_into_collection_set_do(&_count_rc_closure, i);
5192 }
5193 };
5194
5195 void G1CollectedHeap::popularity_pause_preamble(HeapRegion* popular_region) {
5196 // We're evacuating a single region (for popularity).
5197 if (G1TracePopularity) {
5198 gclog_or_tty->print_cr("Doing pop region pause for ["PTR_FORMAT", "PTR_FORMAT")",
5199 popular_region->bottom(), popular_region->end());
5200 }
5201 g1_policy()->set_single_region_collection_set(popular_region);
5202 size_t max_rc;
5203 if (!compute_reference_counts_and_evac_popular(popular_region,
5204 &max_rc)) {
5205 // We didn't evacuate any popular objects.
5206 // We increase the RS popularity limit, to prevent this from
5207 // happening in the future.
5208 if (G1RSPopLimit < (1 << 30)) {
5209 G1RSPopLimit *= 2;
5210 }
5211 // For now, interesting enough for a message:
5212 #if 1
5213 gclog_or_tty->print_cr("In pop region pause for ["PTR_FORMAT", "PTR_FORMAT"), "
5214 "failed to find a pop object (max = %d).",
5215 popular_region->bottom(), popular_region->end(),
5216 max_rc);
5217 gclog_or_tty->print_cr("Increased G1RSPopLimit to %d.", G1RSPopLimit);
5218 #endif // 0
5219 // Also, we reset the collection set to NULL, to make the rest of
5220 // the collection do nothing.
5221 assert(popular_region->next_in_collection_set() == NULL,
5222 "should be single-region.");
5223 popular_region->set_in_collection_set(false);
5224 popular_region->set_popular_pending(false);
5225 g1_policy()->clear_collection_set();
5226 }
5227 }
5228
5229 bool G1CollectedHeap::
5230 compute_reference_counts_and_evac_popular(HeapRegion* popular_region,
5231 size_t* max_rc) {
5232 HeapWord* rc_region_bot;
5233 HeapWord* rc_region_end;
5234
5235 // Set up the reference count region.
5236 HeapRegion* rc_region = newAllocRegion(HeapRegion::GrainWords);
5237 if (rc_region != NULL) {
5238 rc_region_bot = rc_region->bottom();
5239 rc_region_end = rc_region->end();
5240 } else {
5241 rc_region_bot = NEW_C_HEAP_ARRAY(HeapWord, HeapRegion::GrainWords);
5242 if (rc_region_bot == NULL) {
5243 vm_exit_out_of_memory(HeapRegion::GrainWords,
5244 "No space for RC region.");
5245 }
5246 rc_region_end = rc_region_bot + HeapRegion::GrainWords;
5247 }
5248
5249 if (G1TracePopularity)
5250 gclog_or_tty->print_cr("RC region is ["PTR_FORMAT", "PTR_FORMAT")",
5251 rc_region_bot, rc_region_end);
5252 if (rc_region_bot > popular_region->bottom()) {
5253 _rc_region_above = true;
5254 _rc_region_diff =
5255 pointer_delta(rc_region_bot, popular_region->bottom(), 1);
5256 } else {
5257 assert(rc_region_bot < popular_region->bottom(), "Can't be equal.");
5258 _rc_region_above = false;
5259 _rc_region_diff =
5260 pointer_delta(popular_region->bottom(), rc_region_bot, 1);
5261 }
5262 g1_policy()->record_pop_compute_rc_start();
5263 // Count external references.
5264 g1_rem_set()->prepare_for_oops_into_collection_set_do();
5265 if (ParallelGCThreads > 0) {
5266
5267 set_par_threads(workers()->total_workers());
5268 G1ParCountRCTask par_count_rc_task(this);
5269 workers()->run_task(&par_count_rc_task);
5270 set_par_threads(0);
5271
5272 } else {
5273 CountRCClosure count_rc_closure(this);
5274 g1_rem_set()->oops_into_collection_set_do(&count_rc_closure, 0);
5275 }
5276 g1_rem_set()->cleanup_after_oops_into_collection_set_do();
5277 g1_policy()->record_pop_compute_rc_end();
5278
5279 // Now evacuate popular objects.
5280 g1_policy()->record_pop_evac_start();
5281 EvacPopObjClosure evac_pop_obj_cl(this);
5282 popular_region->object_iterate(&evac_pop_obj_cl);
5283 *max_rc = evac_pop_obj_cl.max_rc();
5284
5285 // Make sure the last "top" value of the current popular region is copied
5286 // as the "next_top_at_mark_start", so that objects made popular during
5287 // markings aren't automatically considered live.
5288 HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
5289 cur_pop_region->note_end_of_copying();
5290
5291 if (rc_region != NULL) {
5292 free_region(rc_region);
5293 } else {
5294 FREE_C_HEAP_ARRAY(HeapWord, rc_region_bot);
5295 }
5296 g1_policy()->record_pop_evac_end();
5297
5298 return evac_pop_obj_cl.pop_objs() > 0;
5299 }
5300
5301 class CountPopObjInfoClosure: public HeapRegionClosure {
5302 size_t _objs;
5303 size_t _bytes;
5304
5305 class CountObjClosure: public ObjectClosure {
5306 int _n;
5307 public:
5308 CountObjClosure() : _n(0) {}
5309 void do_object(oop obj) { _n++; }
5310 size_t n() { return _n; }
5311 };
5312
5313 public:
5314 CountPopObjInfoClosure() : _objs(0), _bytes(0) {}
5315 bool doHeapRegion(HeapRegion* r) {
5316 _bytes += r->used();
5317 CountObjClosure blk;
5318 r->object_iterate(&blk);
5319 _objs += blk.n();
5320 return false;
5321 }
5322 size_t objs() { return _objs; }
5323 size_t bytes() { return _bytes; }
5324 };
5325
5326
5327 void G1CollectedHeap::print_popularity_summary_info() const {
5328 CountPopObjInfoClosure blk;
5329 for (int i = 0; i <= _cur_pop_hr_index; i++) {
5330 blk.doHeapRegion(_hrs->at(i));
5331 }
5332 gclog_or_tty->print_cr("\nPopular objects: %d objs, %d bytes.",
5333 blk.objs(), blk.bytes());
5334 gclog_or_tty->print_cr(" RC at copy = [avg = %5.2f, max = %5.2f, sd = %5.2f].",
5335 _pop_obj_rc_at_copy.avg(),
5336 _pop_obj_rc_at_copy.maximum(),
5337 _pop_obj_rc_at_copy.sd());
5338 }
5339
5340 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
5341 _refine_cte_cl->set_concurrent(concurrent);
5342 }
5343
5344 #ifndef PRODUCT
5345
5346 class PrintHeapRegionClosure: public HeapRegionClosure {
5347 public:
5348 bool doHeapRegion(HeapRegion *r) {
5349 gclog_or_tty->print("Region: "PTR_FORMAT":", r);
5350 if (r != NULL) {
5351 if (r->is_on_free_list())
5352 gclog_or_tty->print("Free ");
5353 if (r->is_young())
5354 gclog_or_tty->print("Young ");
5355 if (r->isHumongous())
5356 gclog_or_tty->print("Is Humongous ");
5357 r->print();
5358 }
5359 return false;
5360 }
5361 };
5362
5363 class SortHeapRegionClosure : public HeapRegionClosure {
5364 size_t young_regions,free_regions, unclean_regions;
5365 size_t hum_regions, count;
5366 size_t unaccounted, cur_unclean, cur_alloc;
5367 size_t total_free;
5368 HeapRegion* cur;
5369 public:
5370 SortHeapRegionClosure(HeapRegion *_cur) : cur(_cur), young_regions(0),
5371 free_regions(0), unclean_regions(0),
5372 hum_regions(0),
5373 count(0), unaccounted(0),
5374 cur_alloc(0), total_free(0)
5375 {}
5376 bool doHeapRegion(HeapRegion *r) {
5377 count++;
5378 if (r->is_on_free_list()) free_regions++;
5379 else if (r->is_on_unclean_list()) unclean_regions++;
5380 else if (r->isHumongous()) hum_regions++;
5381 else if (r->is_young()) young_regions++;
5382 else if (r == cur) cur_alloc++;
5383 else unaccounted++;
5384 return false;
5385 }
5386 void print() {
5387 total_free = free_regions + unclean_regions;
5388 gclog_or_tty->print("%d regions\n", count);
5389 gclog_or_tty->print("%d free: free_list = %d unclean = %d\n",
5390 total_free, free_regions, unclean_regions);
5391 gclog_or_tty->print("%d humongous %d young\n",
5392 hum_regions, young_regions);
5393 gclog_or_tty->print("%d cur_alloc\n", cur_alloc);
5394 gclog_or_tty->print("UHOH unaccounted = %d\n", unaccounted);
5395 }
5396 };
5397
5398 void G1CollectedHeap::print_region_counts() {
5399 SortHeapRegionClosure sc(_cur_alloc_region);
5400 PrintHeapRegionClosure cl;
5401 heap_region_iterate(&cl);
5402 heap_region_iterate(&sc);
5403 sc.print();
5404 print_region_accounting_info();
5405 };
5406
5407 bool G1CollectedHeap::regions_accounted_for() {
5408 // TODO: regions accounting for young/survivor/tenured
5409 return true;
5410 }
5411
5412 bool G1CollectedHeap::print_region_accounting_info() {
5413 gclog_or_tty->print_cr("P regions: %d.", G1NumPopularRegions);
5414 gclog_or_tty->print_cr("Free regions: %d (count: %d count list %d) (clean: %d unclean: %d).",
5415 free_regions(),
5416 count_free_regions(), count_free_regions_list(),
5417 _free_region_list_size, _unclean_region_list.sz());
5418 gclog_or_tty->print_cr("cur_alloc: %d.",
5419 (_cur_alloc_region == NULL ? 0 : 1));
5420 gclog_or_tty->print_cr("H regions: %d.", _num_humongous_regions);
5421
5422 // TODO: check regions accounting for young/survivor/tenured
5423 return true;
5424 }
5425
5426 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
5427 HeapRegion* hr = heap_region_containing(p);
5428 if (hr == NULL) {
5429 return is_in_permanent(p);
5430 } else {
5431 return hr->is_in(p);
5432 }
5433 }
5434 #endif // PRODUCT
5435
5436 void G1CollectedHeap::g1_unimplemented() {
5437 // Unimplemented();
5438 }
5439
5440
5441 // Local Variables: ***
5442 // c-indentation-style: gnu ***
5443 // End: ***