1/*
2 * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "aot/aotLoader.hpp"
27#include "classfile/classLoaderDataGraph.hpp"
28#include "classfile/javaClasses.inline.hpp"
29#include "classfile/stringTable.hpp"
30#include "classfile/symbolTable.hpp"
31#include "classfile/systemDictionary.hpp"
32#include "code/codeCache.hpp"
33#include "gc/parallel/gcTaskManager.hpp"
34#include "gc/parallel/parallelArguments.hpp"
35#include "gc/parallel/parallelScavengeHeap.inline.hpp"
36#include "gc/parallel/parMarkBitMap.inline.hpp"
37#include "gc/parallel/pcTasks.hpp"
38#include "gc/parallel/psAdaptiveSizePolicy.hpp"
39#include "gc/parallel/psCompactionManager.inline.hpp"
40#include "gc/parallel/psOldGen.hpp"
41#include "gc/parallel/psParallelCompact.inline.hpp"
42#include "gc/parallel/psPromotionManager.inline.hpp"
43#include "gc/parallel/psScavenge.hpp"
44#include "gc/parallel/psYoungGen.hpp"
45#include "gc/shared/gcCause.hpp"
46#include "gc/shared/gcHeapSummary.hpp"
47#include "gc/shared/gcId.hpp"
48#include "gc/shared/gcLocker.hpp"
49#include "gc/shared/gcTimer.hpp"
50#include "gc/shared/gcTrace.hpp"
51#include "gc/shared/gcTraceTime.inline.hpp"
52#include "gc/shared/isGCActiveMark.hpp"
53#include "gc/shared/referencePolicy.hpp"
54#include "gc/shared/referenceProcessor.hpp"
55#include "gc/shared/referenceProcessorPhaseTimes.hpp"
56#include "gc/shared/spaceDecorator.hpp"
57#include "gc/shared/weakProcessor.hpp"
58#include "logging/log.hpp"
59#include "memory/iterator.inline.hpp"
60#include "memory/resourceArea.hpp"
61#include "memory/universe.hpp"
62#include "oops/access.inline.hpp"
63#include "oops/instanceClassLoaderKlass.inline.hpp"
64#include "oops/instanceKlass.inline.hpp"
65#include "oops/instanceMirrorKlass.inline.hpp"
66#include "oops/methodData.hpp"
67#include "oops/objArrayKlass.inline.hpp"
68#include "oops/oop.inline.hpp"
69#include "runtime/atomic.hpp"
70#include "runtime/handles.inline.hpp"
71#include "runtime/safepoint.hpp"
72#include "runtime/vmThread.hpp"
73#include "services/management.hpp"
74#include "services/memTracker.hpp"
75#include "services/memoryService.hpp"
76#include "utilities/align.hpp"
77#include "utilities/debug.hpp"
78#include "utilities/events.hpp"
79#include "utilities/formatBuffer.hpp"
80#include "utilities/macros.hpp"
81#include "utilities/stack.inline.hpp"
82#if INCLUDE_JVMCI
83#include "jvmci/jvmci.hpp"
84#endif
85
86#include <math.h>
87
88// All sizes are in HeapWords.
89const size_t ParallelCompactData::Log2RegionSize = 16; // 64K words
90const size_t ParallelCompactData::RegionSize = (size_t)1 << Log2RegionSize;
91const size_t ParallelCompactData::RegionSizeBytes =
92 RegionSize << LogHeapWordSize;
93const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
94const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
95const size_t ParallelCompactData::RegionAddrMask = ~RegionAddrOffsetMask;
96
97const size_t ParallelCompactData::Log2BlockSize = 7; // 128 words
98const size_t ParallelCompactData::BlockSize = (size_t)1 << Log2BlockSize;
99const size_t ParallelCompactData::BlockSizeBytes =
100 BlockSize << LogHeapWordSize;
101const size_t ParallelCompactData::BlockSizeOffsetMask = BlockSize - 1;
102const size_t ParallelCompactData::BlockAddrOffsetMask = BlockSizeBytes - 1;
103const size_t ParallelCompactData::BlockAddrMask = ~BlockAddrOffsetMask;
104
105const size_t ParallelCompactData::BlocksPerRegion = RegionSize / BlockSize;
106const size_t ParallelCompactData::Log2BlocksPerRegion =
107 Log2RegionSize - Log2BlockSize;
108
109const ParallelCompactData::RegionData::region_sz_t
110ParallelCompactData::RegionData::dc_shift = 27;
111
112const ParallelCompactData::RegionData::region_sz_t
113ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
114
115const ParallelCompactData::RegionData::region_sz_t
116ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
117
118const ParallelCompactData::RegionData::region_sz_t
119ParallelCompactData::RegionData::los_mask = ~dc_mask;
120
121const ParallelCompactData::RegionData::region_sz_t
122ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
123
124const ParallelCompactData::RegionData::region_sz_t
125ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
126
127SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
128
129SpanSubjectToDiscoveryClosure PSParallelCompact::_span_based_discoverer;
130ReferenceProcessor* PSParallelCompact::_ref_processor = NULL;
131
132double PSParallelCompact::_dwl_mean;
133double PSParallelCompact::_dwl_std_dev;
134double PSParallelCompact::_dwl_first_term;
135double PSParallelCompact::_dwl_adjustment;
136#ifdef ASSERT
137bool PSParallelCompact::_dwl_initialized = false;
138#endif // #ifdef ASSERT
139
140void SplitInfo::record(size_t src_region_idx, size_t partial_obj_size,
141 HeapWord* destination)
142{
143 assert(src_region_idx != 0, "invalid src_region_idx");
144 assert(partial_obj_size != 0, "invalid partial_obj_size argument");
145 assert(destination != NULL, "invalid destination argument");
146
147 _src_region_idx = src_region_idx;
148 _partial_obj_size = partial_obj_size;
149 _destination = destination;
150
151 // These fields may not be updated below, so make sure they're clear.
152 assert(_dest_region_addr == NULL, "should have been cleared");
153 assert(_first_src_addr == NULL, "should have been cleared");
154
155 // Determine the number of destination regions for the partial object.
156 HeapWord* const last_word = destination + partial_obj_size - 1;
157 const ParallelCompactData& sd = PSParallelCompact::summary_data();
158 HeapWord* const beg_region_addr = sd.region_align_down(destination);
159 HeapWord* const end_region_addr = sd.region_align_down(last_word);
160
161 if (beg_region_addr == end_region_addr) {
162 // One destination region.
163 _destination_count = 1;
164 if (end_region_addr == destination) {
165 // The destination falls on a region boundary, thus the first word of the
166 // partial object will be the first word copied to the destination region.
167 _dest_region_addr = end_region_addr;
168 _first_src_addr = sd.region_to_addr(src_region_idx);
169 }
170 } else {
171 // Two destination regions. When copied, the partial object will cross a
172 // destination region boundary, so a word somewhere within the partial
173 // object will be the first word copied to the second destination region.
174 _destination_count = 2;
175 _dest_region_addr = end_region_addr;
176 const size_t ofs = pointer_delta(end_region_addr, destination);
177 assert(ofs < _partial_obj_size, "sanity");
178 _first_src_addr = sd.region_to_addr(src_region_idx) + ofs;
179 }
180}
181
182void SplitInfo::clear()
183{
184 _src_region_idx = 0;
185 _partial_obj_size = 0;
186 _destination = NULL;
187 _destination_count = 0;
188 _dest_region_addr = NULL;
189 _first_src_addr = NULL;
190 assert(!is_valid(), "sanity");
191}
192
193#ifdef ASSERT
194void SplitInfo::verify_clear()
195{
196 assert(_src_region_idx == 0, "not clear");
197 assert(_partial_obj_size == 0, "not clear");
198 assert(_destination == NULL, "not clear");
199 assert(_destination_count == 0, "not clear");
200 assert(_dest_region_addr == NULL, "not clear");
201 assert(_first_src_addr == NULL, "not clear");
202}
203#endif // #ifdef ASSERT
204
205
206void PSParallelCompact::print_on_error(outputStream* st) {
207 _mark_bitmap.print_on_error(st);
208}
209
210#ifndef PRODUCT
211const char* PSParallelCompact::space_names[] = {
212 "old ", "eden", "from", "to "
213};
214
215void PSParallelCompact::print_region_ranges() {
216 if (!log_develop_is_enabled(Trace, gc, compaction)) {
217 return;
218 }
219 Log(gc, compaction) log;
220 ResourceMark rm;
221 LogStream ls(log.trace());
222 Universe::print_on(&ls);
223 log.trace("space bottom top end new_top");
224 log.trace("------ ---------- ---------- ---------- ----------");
225
226 for (unsigned int id = 0; id < last_space_id; ++id) {
227 const MutableSpace* space = _space_info[id].space();
228 log.trace("%u %s "
229 SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " "
230 SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ",
231 id, space_names[id],
232 summary_data().addr_to_region_idx(space->bottom()),
233 summary_data().addr_to_region_idx(space->top()),
234 summary_data().addr_to_region_idx(space->end()),
235 summary_data().addr_to_region_idx(_space_info[id].new_top()));
236 }
237}
238
239void
240print_generic_summary_region(size_t i, const ParallelCompactData::RegionData* c)
241{
242#define REGION_IDX_FORMAT SIZE_FORMAT_W(7)
243#define REGION_DATA_FORMAT SIZE_FORMAT_W(5)
244
245 ParallelCompactData& sd = PSParallelCompact::summary_data();
246 size_t dci = c->destination() ? sd.addr_to_region_idx(c->destination()) : 0;
247 log_develop_trace(gc, compaction)(
248 REGION_IDX_FORMAT " " PTR_FORMAT " "
249 REGION_IDX_FORMAT " " PTR_FORMAT " "
250 REGION_DATA_FORMAT " " REGION_DATA_FORMAT " "
251 REGION_DATA_FORMAT " " REGION_IDX_FORMAT " %d",
252 i, p2i(c->data_location()), dci, p2i(c->destination()),
253 c->partial_obj_size(), c->live_obj_size(),
254 c->data_size(), c->source_region(), c->destination_count());
255
256#undef REGION_IDX_FORMAT
257#undef REGION_DATA_FORMAT
258}
259
260void
261print_generic_summary_data(ParallelCompactData& summary_data,
262 HeapWord* const beg_addr,
263 HeapWord* const end_addr)
264{
265 size_t total_words = 0;
266 size_t i = summary_data.addr_to_region_idx(beg_addr);
267 const size_t last = summary_data.addr_to_region_idx(end_addr);
268 HeapWord* pdest = 0;
269
270 while (i < last) {
271 ParallelCompactData::RegionData* c = summary_data.region(i);
272 if (c->data_size() != 0 || c->destination() != pdest) {
273 print_generic_summary_region(i, c);
274 total_words += c->data_size();
275 pdest = c->destination();
276 }
277 ++i;
278 }
279
280 log_develop_trace(gc, compaction)("summary_data_bytes=" SIZE_FORMAT, total_words * HeapWordSize);
281}
282
283void
284PSParallelCompact::print_generic_summary_data(ParallelCompactData& summary_data,
285 HeapWord* const beg_addr,
286 HeapWord* const end_addr) {
287 ::print_generic_summary_data(summary_data,beg_addr, end_addr);
288}
289
290void
291print_generic_summary_data(ParallelCompactData& summary_data,
292 SpaceInfo* space_info)
293{
294 if (!log_develop_is_enabled(Trace, gc, compaction)) {
295 return;
296 }
297
298 for (unsigned int id = 0; id < PSParallelCompact::last_space_id; ++id) {
299 const MutableSpace* space = space_info[id].space();
300 print_generic_summary_data(summary_data, space->bottom(),
301 MAX2(space->top(), space_info[id].new_top()));
302 }
303}
304
305void
306print_initial_summary_data(ParallelCompactData& summary_data,
307 const MutableSpace* space) {
308 if (space->top() == space->bottom()) {
309 return;
310 }
311
312 const size_t region_size = ParallelCompactData::RegionSize;
313 typedef ParallelCompactData::RegionData RegionData;
314 HeapWord* const top_aligned_up = summary_data.region_align_up(space->top());
315 const size_t end_region = summary_data.addr_to_region_idx(top_aligned_up);
316 const RegionData* c = summary_data.region(end_region - 1);
317 HeapWord* end_addr = c->destination() + c->data_size();
318 const size_t live_in_space = pointer_delta(end_addr, space->bottom());
319
320 // Print (and count) the full regions at the beginning of the space.
321 size_t full_region_count = 0;
322 size_t i = summary_data.addr_to_region_idx(space->bottom());
323 while (i < end_region && summary_data.region(i)->data_size() == region_size) {
324 ParallelCompactData::RegionData* c = summary_data.region(i);
325 log_develop_trace(gc, compaction)(
326 SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
327 i, p2i(c->destination()),
328 c->partial_obj_size(), c->live_obj_size(),
329 c->data_size(), c->source_region(), c->destination_count());
330 ++full_region_count;
331 ++i;
332 }
333
334 size_t live_to_right = live_in_space - full_region_count * region_size;
335
336 double max_reclaimed_ratio = 0.0;
337 size_t max_reclaimed_ratio_region = 0;
338 size_t max_dead_to_right = 0;
339 size_t max_live_to_right = 0;
340
341 // Print the 'reclaimed ratio' for regions while there is something live in
342 // the region or to the right of it. The remaining regions are empty (and
343 // uninteresting), and computing the ratio will result in division by 0.
344 while (i < end_region && live_to_right > 0) {
345 c = summary_data.region(i);
346 HeapWord* const region_addr = summary_data.region_to_addr(i);
347 const size_t used_to_right = pointer_delta(space->top(), region_addr);
348 const size_t dead_to_right = used_to_right - live_to_right;
349 const double reclaimed_ratio = double(dead_to_right) / live_to_right;
350
351 if (reclaimed_ratio > max_reclaimed_ratio) {
352 max_reclaimed_ratio = reclaimed_ratio;
353 max_reclaimed_ratio_region = i;
354 max_dead_to_right = dead_to_right;
355 max_live_to_right = live_to_right;
356 }
357
358 ParallelCompactData::RegionData* c = summary_data.region(i);
359 log_develop_trace(gc, compaction)(
360 SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d"
361 "%12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10),
362 i, p2i(c->destination()),
363 c->partial_obj_size(), c->live_obj_size(),
364 c->data_size(), c->source_region(), c->destination_count(),
365 reclaimed_ratio, dead_to_right, live_to_right);
366
367
368 live_to_right -= c->data_size();
369 ++i;
370 }
371
372 // Any remaining regions are empty. Print one more if there is one.
373 if (i < end_region) {
374 ParallelCompactData::RegionData* c = summary_data.region(i);
375 log_develop_trace(gc, compaction)(
376 SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
377 i, p2i(c->destination()),
378 c->partial_obj_size(), c->live_obj_size(),
379 c->data_size(), c->source_region(), c->destination_count());
380 }
381
382 log_develop_trace(gc, compaction)("max: " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f",
383 max_reclaimed_ratio_region, max_dead_to_right, max_live_to_right, max_reclaimed_ratio);
384}
385
386void
387print_initial_summary_data(ParallelCompactData& summary_data,
388 SpaceInfo* space_info) {
389 if (!log_develop_is_enabled(Trace, gc, compaction)) {
390 return;
391 }
392
393 unsigned int id = PSParallelCompact::old_space_id;
394 const MutableSpace* space;
395 do {
396 space = space_info[id].space();
397 print_initial_summary_data(summary_data, space);
398 } while (++id < PSParallelCompact::eden_space_id);
399
400 do {
401 space = space_info[id].space();
402 print_generic_summary_data(summary_data, space->bottom(), space->top());
403 } while (++id < PSParallelCompact::last_space_id);
404}
405#endif // #ifndef PRODUCT
406
407#ifdef ASSERT
408size_t add_obj_count;
409size_t add_obj_size;
410size_t mark_bitmap_count;
411size_t mark_bitmap_size;
412#endif // #ifdef ASSERT
413
414ParallelCompactData::ParallelCompactData() :
415 _region_start(NULL),
416 DEBUG_ONLY(_region_end(NULL) COMMA)
417 _region_vspace(NULL),
418 _reserved_byte_size(0),
419 _region_data(NULL),
420 _region_count(0),
421 _block_vspace(NULL),
422 _block_data(NULL),
423 _block_count(0) {}
424
425bool ParallelCompactData::initialize(MemRegion covered_region)
426{
427 _region_start = covered_region.start();
428 const size_t region_size = covered_region.word_size();
429 DEBUG_ONLY(_region_end = _region_start + region_size;)
430
431 assert(region_align_down(_region_start) == _region_start,
432 "region start not aligned");
433 assert((region_size & RegionSizeOffsetMask) == 0,
434 "region size not a multiple of RegionSize");
435
436 bool result = initialize_region_data(region_size) && initialize_block_data();
437 return result;
438}
439
440PSVirtualSpace*
441ParallelCompactData::create_vspace(size_t count, size_t element_size)
442{
443 const size_t raw_bytes = count * element_size;
444 const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);
445 const size_t granularity = os::vm_allocation_granularity();
446 _reserved_byte_size = align_up(raw_bytes, MAX2(page_sz, granularity));
447
448 const size_t rs_align = page_sz == (size_t) os::vm_page_size() ? 0 :
449 MAX2(page_sz, granularity);
450 ReservedSpace rs(_reserved_byte_size, rs_align, rs_align > 0);
451 os::trace_page_sizes("Parallel Compact Data", raw_bytes, raw_bytes, page_sz, rs.base(),
452 rs.size());
453
454 MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);
455
456 PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
457 if (vspace != 0) {
458 if (vspace->expand_by(_reserved_byte_size)) {
459 return vspace;
460 }
461 delete vspace;
462 // Release memory reserved in the space.
463 rs.release();
464 }
465
466 return 0;
467}
468
469bool ParallelCompactData::initialize_region_data(size_t region_size)
470{
471 const size_t count = (region_size + RegionSizeOffsetMask) >> Log2RegionSize;
472 _region_vspace = create_vspace(count, sizeof(RegionData));
473 if (_region_vspace != 0) {
474 _region_data = (RegionData*)_region_vspace->reserved_low_addr();
475 _region_count = count;
476 return true;
477 }
478 return false;
479}
480
481bool ParallelCompactData::initialize_block_data()
482{
483 assert(_region_count != 0, "region data must be initialized first");
484 const size_t count = _region_count << Log2BlocksPerRegion;
485 _block_vspace = create_vspace(count, sizeof(BlockData));
486 if (_block_vspace != 0) {
487 _block_data = (BlockData*)_block_vspace->reserved_low_addr();
488 _block_count = count;
489 return true;
490 }
491 return false;
492}
493
494void ParallelCompactData::clear()
495{
496 memset(_region_data, 0, _region_vspace->committed_size());
497 memset(_block_data, 0, _block_vspace->committed_size());
498}
499
500void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
501 assert(beg_region <= _region_count, "beg_region out of range");
502 assert(end_region <= _region_count, "end_region out of range");
503 assert(RegionSize % BlockSize == 0, "RegionSize not a multiple of BlockSize");
504
505 const size_t region_cnt = end_region - beg_region;
506 memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));
507
508 const size_t beg_block = beg_region * BlocksPerRegion;
509 const size_t block_cnt = region_cnt * BlocksPerRegion;
510 memset(_block_data + beg_block, 0, block_cnt * sizeof(BlockData));
511}
512
513HeapWord* ParallelCompactData::partial_obj_end(size_t region_idx) const
514{
515 const RegionData* cur_cp = region(region_idx);
516 const RegionData* const end_cp = region(region_count() - 1);
517
518 HeapWord* result = region_to_addr(region_idx);
519 if (cur_cp < end_cp) {
520 do {
521 result += cur_cp->partial_obj_size();
522 } while (cur_cp->partial_obj_size() == RegionSize && ++cur_cp < end_cp);
523 }
524 return result;
525}
526
527void ParallelCompactData::add_obj(HeapWord* addr, size_t len)
528{
529 const size_t obj_ofs = pointer_delta(addr, _region_start);
530 const size_t beg_region = obj_ofs >> Log2RegionSize;
531 const size_t end_region = (obj_ofs + len - 1) >> Log2RegionSize;
532
533 DEBUG_ONLY(Atomic::inc(&add_obj_count);)
534 DEBUG_ONLY(Atomic::add(len, &add_obj_size);)
535
536 if (beg_region == end_region) {
537 // All in one region.
538 _region_data[beg_region].add_live_obj(len);
539 return;
540 }
541
542 // First region.
543 const size_t beg_ofs = region_offset(addr);
544 _region_data[beg_region].add_live_obj(RegionSize - beg_ofs);
545
546 Klass* klass = ((oop)addr)->klass();
547 // Middle regions--completely spanned by this object.
548 for (size_t region = beg_region + 1; region < end_region; ++region) {
549 _region_data[region].set_partial_obj_size(RegionSize);
550 _region_data[region].set_partial_obj_addr(addr);
551 }
552
553 // Last region.
554 const size_t end_ofs = region_offset(addr + len - 1);
555 _region_data[end_region].set_partial_obj_size(end_ofs + 1);
556 _region_data[end_region].set_partial_obj_addr(addr);
557}
558
559void
560ParallelCompactData::summarize_dense_prefix(HeapWord* beg, HeapWord* end)
561{
562 assert(region_offset(beg) == 0, "not RegionSize aligned");
563 assert(region_offset(end) == 0, "not RegionSize aligned");
564
565 size_t cur_region = addr_to_region_idx(beg);
566 const size_t end_region = addr_to_region_idx(end);
567 HeapWord* addr = beg;
568 while (cur_region < end_region) {
569 _region_data[cur_region].set_destination(addr);
570 _region_data[cur_region].set_destination_count(0);
571 _region_data[cur_region].set_source_region(cur_region);
572 _region_data[cur_region].set_data_location(addr);
573
574 // Update live_obj_size so the region appears completely full.
575 size_t live_size = RegionSize - _region_data[cur_region].partial_obj_size();
576 _region_data[cur_region].set_live_obj_size(live_size);
577
578 ++cur_region;
579 addr += RegionSize;
580 }
581}
582
583// Find the point at which a space can be split and, if necessary, record the
584// split point.
585//
586// If the current src region (which overflowed the destination space) doesn't
587// have a partial object, the split point is at the beginning of the current src
588// region (an "easy" split, no extra bookkeeping required).
589//
590// If the current src region has a partial object, the split point is in the
591// region where that partial object starts (call it the split_region). If
592// split_region has a partial object, then the split point is just after that
593// partial object (a "hard" split where we have to record the split data and
594// zero the partial_obj_size field). With a "hard" split, we know that the
595// partial_obj ends within split_region because the partial object that caused
596// the overflow starts in split_region. If split_region doesn't have a partial
597// obj, then the split is at the beginning of split_region (another "easy"
598// split).
599HeapWord*
600ParallelCompactData::summarize_split_space(size_t src_region,
601 SplitInfo& split_info,
602 HeapWord* destination,
603 HeapWord* target_end,
604 HeapWord** target_next)
605{
606 assert(destination <= target_end, "sanity");
607 assert(destination + _region_data[src_region].data_size() > target_end,
608 "region should not fit into target space");
609 assert(is_region_aligned(target_end), "sanity");
610
611 size_t split_region = src_region;
612 HeapWord* split_destination = destination;
613 size_t partial_obj_size = _region_data[src_region].partial_obj_size();
614
615 if (destination + partial_obj_size > target_end) {
616 // The split point is just after the partial object (if any) in the
617 // src_region that contains the start of the object that overflowed the
618 // destination space.
619 //
620 // Find the start of the "overflow" object and set split_region to the
621 // region containing it.
622 HeapWord* const overflow_obj = _region_data[src_region].partial_obj_addr();
623 split_region = addr_to_region_idx(overflow_obj);
624
625 // Clear the source_region field of all destination regions whose first word
626 // came from data after the split point (a non-null source_region field
627 // implies a region must be filled).
628 //
629 // An alternative to the simple loop below: clear during post_compact(),
630 // which uses memcpy instead of individual stores, and is easy to
631 // parallelize. (The downside is that it clears the entire RegionData
632 // object as opposed to just one field.)
633 //
634 // post_compact() would have to clear the summary data up to the highest
635 // address that was written during the summary phase, which would be
636 //
637 // max(top, max(new_top, clear_top))
638 //
639 // where clear_top is a new field in SpaceInfo. Would have to set clear_top
640 // to target_end.
641 const RegionData* const sr = region(split_region);
642 const size_t beg_idx =
643 addr_to_region_idx(region_align_up(sr->destination() +
644 sr->partial_obj_size()));
645 const size_t end_idx = addr_to_region_idx(target_end);
646
647 log_develop_trace(gc, compaction)("split: clearing source_region field in [" SIZE_FORMAT ", " SIZE_FORMAT ")", beg_idx, end_idx);
648 for (size_t idx = beg_idx; idx < end_idx; ++idx) {
649 _region_data[idx].set_source_region(0);
650 }
651
652 // Set split_destination and partial_obj_size to reflect the split region.
653 split_destination = sr->destination();
654 partial_obj_size = sr->partial_obj_size();
655 }
656
657 // The split is recorded only if a partial object extends onto the region.
658 if (partial_obj_size != 0) {
659 _region_data[split_region].set_partial_obj_size(0);
660 split_info.record(split_region, partial_obj_size, split_destination);
661 }
662
663 // Setup the continuation addresses.
664 *target_next = split_destination + partial_obj_size;
665 HeapWord* const source_next = region_to_addr(split_region) + partial_obj_size;
666
667 if (log_develop_is_enabled(Trace, gc, compaction)) {
668 const char * split_type = partial_obj_size == 0 ? "easy" : "hard";
669 log_develop_trace(gc, compaction)("%s split: src=" PTR_FORMAT " src_c=" SIZE_FORMAT " pos=" SIZE_FORMAT,
670 split_type, p2i(source_next), split_region, partial_obj_size);
671 log_develop_trace(gc, compaction)("%s split: dst=" PTR_FORMAT " dst_c=" SIZE_FORMAT " tn=" PTR_FORMAT,
672 split_type, p2i(split_destination),
673 addr_to_region_idx(split_destination),
674 p2i(*target_next));
675
676 if (partial_obj_size != 0) {
677 HeapWord* const po_beg = split_info.destination();
678 HeapWord* const po_end = po_beg + split_info.partial_obj_size();
679 log_develop_trace(gc, compaction)("%s split: po_beg=" PTR_FORMAT " " SIZE_FORMAT " po_end=" PTR_FORMAT " " SIZE_FORMAT,
680 split_type,
681 p2i(po_beg), addr_to_region_idx(po_beg),
682 p2i(po_end), addr_to_region_idx(po_end));
683 }
684 }
685
686 return source_next;
687}
688
689bool ParallelCompactData::summarize(SplitInfo& split_info,
690 HeapWord* source_beg, HeapWord* source_end,
691 HeapWord** source_next,
692 HeapWord* target_beg, HeapWord* target_end,
693 HeapWord** target_next)
694{
695 HeapWord* const source_next_val = source_next == NULL ? NULL : *source_next;
696 log_develop_trace(gc, compaction)(
697 "sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
698 "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
699 p2i(source_beg), p2i(source_end), p2i(source_next_val),
700 p2i(target_beg), p2i(target_end), p2i(*target_next));
701
702 size_t cur_region = addr_to_region_idx(source_beg);
703 const size_t end_region = addr_to_region_idx(region_align_up(source_end));
704
705 HeapWord *dest_addr = target_beg;
706 while (cur_region < end_region) {
707 // The destination must be set even if the region has no data.
708 _region_data[cur_region].set_destination(dest_addr);
709
710 size_t words = _region_data[cur_region].data_size();
711 if (words > 0) {
712 // If cur_region does not fit entirely into the target space, find a point
713 // at which the source space can be 'split' so that part is copied to the
714 // target space and the rest is copied elsewhere.
715 if (dest_addr + words > target_end) {
716 assert(source_next != NULL, "source_next is NULL when splitting");
717 *source_next = summarize_split_space(cur_region, split_info, dest_addr,
718 target_end, target_next);
719 return false;
720 }
721
722 // Compute the destination_count for cur_region, and if necessary, update
723 // source_region for a destination region. The source_region field is
724 // updated if cur_region is the first (left-most) region to be copied to a
725 // destination region.
726 //
727 // The destination_count calculation is a bit subtle. A region that has
728 // data that compacts into itself does not count itself as a destination.
729 // This maintains the invariant that a zero count means the region is
730 // available and can be claimed and then filled.
731 uint destination_count = 0;
732 if (split_info.is_split(cur_region)) {
733 // The current region has been split: the partial object will be copied
734 // to one destination space and the remaining data will be copied to
735 // another destination space. Adjust the initial destination_count and,
736 // if necessary, set the source_region field if the partial object will
737 // cross a destination region boundary.
738 destination_count = split_info.destination_count();
739 if (destination_count == 2) {
740 size_t dest_idx = addr_to_region_idx(split_info.dest_region_addr());
741 _region_data[dest_idx].set_source_region(cur_region);
742 }
743 }
744
745 HeapWord* const last_addr = dest_addr + words - 1;
746 const size_t dest_region_1 = addr_to_region_idx(dest_addr);
747 const size_t dest_region_2 = addr_to_region_idx(last_addr);
748
749 // Initially assume that the destination regions will be the same and
750 // adjust the value below if necessary. Under this assumption, if
751 // cur_region == dest_region_2, then cur_region will be compacted
752 // completely into itself.
753 destination_count += cur_region == dest_region_2 ? 0 : 1;
754 if (dest_region_1 != dest_region_2) {
755 // Destination regions differ; adjust destination_count.
756 destination_count += 1;
757 // Data from cur_region will be copied to the start of dest_region_2.
758 _region_data[dest_region_2].set_source_region(cur_region);
759 } else if (region_offset(dest_addr) == 0) {
760 // Data from cur_region will be copied to the start of the destination
761 // region.
762 _region_data[dest_region_1].set_source_region(cur_region);
763 }
764
765 _region_data[cur_region].set_destination_count(destination_count);
766 _region_data[cur_region].set_data_location(region_to_addr(cur_region));
767 dest_addr += words;
768 }
769
770 ++cur_region;
771 }
772
773 *target_next = dest_addr;
774 return true;
775}
776
777HeapWord* ParallelCompactData::calc_new_pointer(HeapWord* addr, ParCompactionManager* cm) {
778 assert(addr != NULL, "Should detect NULL oop earlier");
779 assert(ParallelScavengeHeap::heap()->is_in(addr), "not in heap");
780 assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "not marked");
781
782 // Region covering the object.
783 RegionData* const region_ptr = addr_to_region_ptr(addr);
784 HeapWord* result = region_ptr->destination();
785
786 // If the entire Region is live, the new location is region->destination + the
787 // offset of the object within in the Region.
788
789 // Run some performance tests to determine if this special case pays off. It
790 // is worth it for pointers into the dense prefix. If the optimization to
791 // avoid pointer updates in regions that only point to the dense prefix is
792 // ever implemented, this should be revisited.
793 if (region_ptr->data_size() == RegionSize) {
794 result += region_offset(addr);
795 return result;
796 }
797
798 // Otherwise, the new location is region->destination + block offset + the
799 // number of live words in the Block that are (a) to the left of addr and (b)
800 // due to objects that start in the Block.
801
802 // Fill in the block table if necessary. This is unsynchronized, so multiple
803 // threads may fill the block table for a region (harmless, since it is
804 // idempotent).
805 if (!region_ptr->blocks_filled()) {
806 PSParallelCompact::fill_blocks(addr_to_region_idx(addr));
807 region_ptr->set_blocks_filled();
808 }
809
810 HeapWord* const search_start = block_align_down(addr);
811 const size_t block_offset = addr_to_block_ptr(addr)->offset();
812
813 const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();
814 const size_t live = bitmap->live_words_in_range(cm, search_start, oop(addr));
815 result += block_offset + live;
816 DEBUG_ONLY(PSParallelCompact::check_new_location(addr, result));
817 return result;
818}
819
820#ifdef ASSERT
821void ParallelCompactData::verify_clear(const PSVirtualSpace* vspace)
822{
823 const size_t* const beg = (const size_t*)vspace->committed_low_addr();
824 const size_t* const end = (const size_t*)vspace->committed_high_addr();
825 for (const size_t* p = beg; p < end; ++p) {
826 assert(*p == 0, "not zero");
827 }
828}
829
830void ParallelCompactData::verify_clear()
831{
832 verify_clear(_region_vspace);
833 verify_clear(_block_vspace);
834}
835#endif // #ifdef ASSERT
836
837STWGCTimer PSParallelCompact::_gc_timer;
838ParallelOldTracer PSParallelCompact::_gc_tracer;
839elapsedTimer PSParallelCompact::_accumulated_time;
840unsigned int PSParallelCompact::_total_invocations = 0;
841unsigned int PSParallelCompact::_maximum_compaction_gc_num = 0;
842jlong PSParallelCompact::_time_of_last_gc = 0;
843CollectorCounters* PSParallelCompact::_counters = NULL;
844ParMarkBitMap PSParallelCompact::_mark_bitmap;
845ParallelCompactData PSParallelCompact::_summary_data;
846
847PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
848
849bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
850
851class PCReferenceProcessor: public ReferenceProcessor {
852public:
853 PCReferenceProcessor(
854 BoolObjectClosure* is_subject_to_discovery,
855 BoolObjectClosure* is_alive_non_header) :
856 ReferenceProcessor(is_subject_to_discovery,
857 ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing
858 ParallelGCThreads, // mt processing degree
859 true, // mt discovery
860 ParallelGCThreads, // mt discovery degree
861 true, // atomic_discovery
862 is_alive_non_header) {
863 }
864
865 template<typename T> bool discover(oop obj, ReferenceType type) {
866 T* referent_addr = (T*) java_lang_ref_Reference::referent_addr_raw(obj);
867 T heap_oop = RawAccess<>::oop_load(referent_addr);
868 oop referent = CompressedOops::decode_not_null(heap_oop);
869 return PSParallelCompact::mark_bitmap()->is_unmarked(referent)
870 && ReferenceProcessor::discover_reference(obj, type);
871 }
872 virtual bool discover_reference(oop obj, ReferenceType type) {
873 if (UseCompressedOops) {
874 return discover<narrowOop>(obj, type);
875 } else {
876 return discover<oop>(obj, type);
877 }
878 }
879};
880
881void PSParallelCompact::post_initialize() {
882 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
883 _span_based_discoverer.set_span(heap->reserved_region());
884 _ref_processor =
885 new PCReferenceProcessor(&_span_based_discoverer,
886 &_is_alive_closure); // non-header is alive closure
887
888 _counters = new CollectorCounters("Parallel full collection pauses", 1);
889
890 // Initialize static fields in ParCompactionManager.
891 ParCompactionManager::initialize(mark_bitmap());
892}
893
894bool PSParallelCompact::initialize() {
895 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
896 MemRegion mr = heap->reserved_region();
897
898 // Was the old gen get allocated successfully?
899 if (!heap->old_gen()->is_allocated()) {
900 return false;
901 }
902
903 initialize_space_info();
904 initialize_dead_wood_limiter();
905
906 if (!_mark_bitmap.initialize(mr)) {
907 vm_shutdown_during_initialization(
908 err_msg("Unable to allocate " SIZE_FORMAT "KB bitmaps for parallel "
909 "garbage collection for the requested " SIZE_FORMAT "KB heap.",
910 _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
911 return false;
912 }
913
914 if (!_summary_data.initialize(mr)) {
915 vm_shutdown_during_initialization(
916 err_msg("Unable to allocate " SIZE_FORMAT "KB card tables for parallel "
917 "garbage collection for the requested " SIZE_FORMAT "KB heap.",
918 _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
919 return false;
920 }
921
922 return true;
923}
924
925void PSParallelCompact::initialize_space_info()
926{
927 memset(&_space_info, 0, sizeof(_space_info));
928
929 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
930 PSYoungGen* young_gen = heap->young_gen();
931
932 _space_info[old_space_id].set_space(heap->old_gen()->object_space());
933 _space_info[eden_space_id].set_space(young_gen->eden_space());
934 _space_info[from_space_id].set_space(young_gen->from_space());
935 _space_info[to_space_id].set_space(young_gen->to_space());
936
937 _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
938}
939
940void PSParallelCompact::initialize_dead_wood_limiter()
941{
942 const size_t max = 100;
943 _dwl_mean = double(MIN2(ParallelOldDeadWoodLimiterMean, max)) / 100.0;
944 _dwl_std_dev = double(MIN2(ParallelOldDeadWoodLimiterStdDev, max)) / 100.0;
945 _dwl_first_term = 1.0 / (sqrt(2.0 * M_PI) * _dwl_std_dev);
946 DEBUG_ONLY(_dwl_initialized = true;)
947 _dwl_adjustment = normal_distribution(1.0);
948}
949
950void
951PSParallelCompact::clear_data_covering_space(SpaceId id)
952{
953 // At this point, top is the value before GC, new_top() is the value that will
954 // be set at the end of GC. The marking bitmap is cleared to top; nothing
955 // should be marked above top. The summary data is cleared to the larger of
956 // top & new_top.
957 MutableSpace* const space = _space_info[id].space();
958 HeapWord* const bot = space->bottom();
959 HeapWord* const top = space->top();
960 HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
961
962 const idx_t beg_bit = _mark_bitmap.addr_to_bit(bot);
963 const idx_t end_bit = BitMap::word_align_up(_mark_bitmap.addr_to_bit(top));
964 _mark_bitmap.clear_range(beg_bit, end_bit);
965
966 const size_t beg_region = _summary_data.addr_to_region_idx(bot);
967 const size_t end_region =
968 _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
969 _summary_data.clear_range(beg_region, end_region);
970
971 // Clear the data used to 'split' regions.
972 SplitInfo& split_info = _space_info[id].split_info();
973 if (split_info.is_valid()) {
974 split_info.clear();
975 }
976 DEBUG_ONLY(split_info.verify_clear();)
977}
978
979void PSParallelCompact::pre_compact()
980{
981 // Update the from & to space pointers in space_info, since they are swapped
982 // at each young gen gc. Do the update unconditionally (even though a
983 // promotion failure does not swap spaces) because an unknown number of young
984 // collections will have swapped the spaces an unknown number of times.
985 GCTraceTime(Debug, gc, phases) tm("Pre Compact", &_gc_timer);
986 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
987 _space_info[from_space_id].set_space(heap->young_gen()->from_space());
988 _space_info[to_space_id].set_space(heap->young_gen()->to_space());
989
990 DEBUG_ONLY(add_obj_count = add_obj_size = 0;)
991 DEBUG_ONLY(mark_bitmap_count = mark_bitmap_size = 0;)
992
993 // Increment the invocation count
994 heap->increment_total_collections(true);
995
996 // We need to track unique mark sweep invocations as well.
997 _total_invocations++;
998
999 heap->print_heap_before_gc();
1000 heap->trace_heap_before_gc(&_gc_tracer);
1001
1002 // Fill in TLABs
1003 heap->ensure_parsability(true); // retire TLABs
1004
1005 if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
1006 HandleMark hm; // Discard invalid handles created during verification
1007 Universe::verify("Before GC");
1008 }
1009
1010 // Verify object start arrays
1011 if (VerifyObjectStartArray &&
1012 VerifyBeforeGC) {
1013 heap->old_gen()->verify_object_start_array();
1014 }
1015
1016 DEBUG_ONLY(mark_bitmap()->verify_clear();)
1017 DEBUG_ONLY(summary_data().verify_clear();)
1018
1019 // Have worker threads release resources the next time they run a task.
1020 gc_task_manager()->release_all_resources();
1021
1022 ParCompactionManager::reset_all_bitmap_query_caches();
1023}
1024
1025void PSParallelCompact::post_compact()
1026{
1027 GCTraceTime(Info, gc, phases) tm("Post Compact", &_gc_timer);
1028
1029 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1030 // Clear the marking bitmap, summary data and split info.
1031 clear_data_covering_space(SpaceId(id));
1032 // Update top(). Must be done after clearing the bitmap and summary data.
1033 _space_info[id].publish_new_top();
1034 }
1035
1036 MutableSpace* const eden_space = _space_info[eden_space_id].space();
1037 MutableSpace* const from_space = _space_info[from_space_id].space();
1038 MutableSpace* const to_space = _space_info[to_space_id].space();
1039
1040 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1041 bool eden_empty = eden_space->is_empty();
1042 if (!eden_empty) {
1043 eden_empty = absorb_live_data_from_eden(heap->size_policy(),
1044 heap->young_gen(), heap->old_gen());
1045 }
1046
1047 // Update heap occupancy information which is used as input to the soft ref
1048 // clearing policy at the next gc.
1049 Universe::update_heap_info_at_gc();
1050
1051 bool young_gen_empty = eden_empty && from_space->is_empty() &&
1052 to_space->is_empty();
1053
1054 PSCardTable* ct = heap->card_table();
1055 MemRegion old_mr = heap->old_gen()->reserved();
1056 if (young_gen_empty) {
1057 ct->clear(MemRegion(old_mr.start(), old_mr.end()));
1058 } else {
1059 ct->invalidate(MemRegion(old_mr.start(), old_mr.end()));
1060 }
1061
1062 // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1063 ClassLoaderDataGraph::purge();
1064 MetaspaceUtils::verify_metrics();
1065
1066 heap->prune_scavengable_nmethods();
1067 JvmtiExport::gc_epilogue();
1068
1069#if COMPILER2_OR_JVMCI
1070 DerivedPointerTable::update_pointers();
1071#endif
1072
1073 if (ZapUnusedHeapArea) {
1074 heap->gen_mangle_unused_area();
1075 }
1076
1077 // Update time of last GC
1078 reset_millis_since_last_gc();
1079}
1080
1081HeapWord*
1082PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id,
1083 bool maximum_compaction)
1084{
1085 const size_t region_size = ParallelCompactData::RegionSize;
1086 const ParallelCompactData& sd = summary_data();
1087
1088 const MutableSpace* const space = _space_info[id].space();
1089 HeapWord* const top_aligned_up = sd.region_align_up(space->top());
1090 const RegionData* const beg_cp = sd.addr_to_region_ptr(space->bottom());
1091 const RegionData* const end_cp = sd.addr_to_region_ptr(top_aligned_up);
1092
1093 // Skip full regions at the beginning of the space--they are necessarily part
1094 // of the dense prefix.
1095 size_t full_count = 0;
1096 const RegionData* cp;
1097 for (cp = beg_cp; cp < end_cp && cp->data_size() == region_size; ++cp) {
1098 ++full_count;
1099 }
1100
1101 assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");
1102 const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;
1103 const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval;
1104 if (maximum_compaction || cp == end_cp || interval_ended) {
1105 _maximum_compaction_gc_num = total_invocations();
1106 return sd.region_to_addr(cp);
1107 }
1108
1109 HeapWord* const new_top = _space_info[id].new_top();
1110 const size_t space_live = pointer_delta(new_top, space->bottom());
1111 const size_t space_used = space->used_in_words();
1112 const size_t space_capacity = space->capacity_in_words();
1113
1114 const double cur_density = double(space_live) / space_capacity;
1115 const double deadwood_density =
1116 (1.0 - cur_density) * (1.0 - cur_density) * cur_density * cur_density;
1117 const size_t deadwood_goal = size_t(space_capacity * deadwood_density);
1118
1119 if (TraceParallelOldGCDensePrefix) {
1120 tty->print_cr("cur_dens=%5.3f dw_dens=%5.3f dw_goal=" SIZE_FORMAT,
1121 cur_density, deadwood_density, deadwood_goal);
1122 tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "
1123 "space_cap=" SIZE_FORMAT,
1124 space_live, space_used,
1125 space_capacity);
1126 }
1127
1128 // XXX - Use binary search?
1129 HeapWord* dense_prefix = sd.region_to_addr(cp);
1130 const RegionData* full_cp = cp;
1131 const RegionData* const top_cp = sd.addr_to_region_ptr(space->top() - 1);
1132 while (cp < end_cp) {
1133 HeapWord* region_destination = cp->destination();
1134 const size_t cur_deadwood = pointer_delta(dense_prefix, region_destination);
1135 if (TraceParallelOldGCDensePrefix && Verbose) {
1136 tty->print_cr("c#=" SIZE_FORMAT_W(4) " dst=" PTR_FORMAT " "
1137 "dp=" PTR_FORMAT " " "cdw=" SIZE_FORMAT_W(8),
1138 sd.region(cp), p2i(region_destination),
1139 p2i(dense_prefix), cur_deadwood);
1140 }
1141
1142 if (cur_deadwood >= deadwood_goal) {
1143 // Found the region that has the correct amount of deadwood to the left.
1144 // This typically occurs after crossing a fairly sparse set of regions, so
1145 // iterate backwards over those sparse regions, looking for the region
1146 // that has the lowest density of live objects 'to the right.'
1147 size_t space_to_left = sd.region(cp) * region_size;
1148 size_t live_to_left = space_to_left - cur_deadwood;
1149 size_t space_to_right = space_capacity - space_to_left;
1150 size_t live_to_right = space_live - live_to_left;
1151 double density_to_right = double(live_to_right) / space_to_right;
1152 while (cp > full_cp) {
1153 --cp;
1154 const size_t prev_region_live_to_right = live_to_right -
1155 cp->data_size();
1156 const size_t prev_region_space_to_right = space_to_right + region_size;
1157 double prev_region_density_to_right =
1158 double(prev_region_live_to_right) / prev_region_space_to_right;
1159 if (density_to_right <= prev_region_density_to_right) {
1160 return dense_prefix;
1161 }
1162 if (TraceParallelOldGCDensePrefix && Verbose) {
1163 tty->print_cr("backing up from c=" SIZE_FORMAT_W(4) " d2r=%10.8f "
1164 "pc_d2r=%10.8f", sd.region(cp), density_to_right,
1165 prev_region_density_to_right);
1166 }
1167 dense_prefix -= region_size;
1168 live_to_right = prev_region_live_to_right;
1169 space_to_right = prev_region_space_to_right;
1170 density_to_right = prev_region_density_to_right;
1171 }
1172 return dense_prefix;
1173 }
1174
1175 dense_prefix += region_size;
1176 ++cp;
1177 }
1178
1179 return dense_prefix;
1180}
1181
1182#ifndef PRODUCT
1183void PSParallelCompact::print_dense_prefix_stats(const char* const algorithm,
1184 const SpaceId id,
1185 const bool maximum_compaction,
1186 HeapWord* const addr)
1187{
1188 const size_t region_idx = summary_data().addr_to_region_idx(addr);
1189 RegionData* const cp = summary_data().region(region_idx);
1190 const MutableSpace* const space = _space_info[id].space();
1191 HeapWord* const new_top = _space_info[id].new_top();
1192
1193 const size_t space_live = pointer_delta(new_top, space->bottom());
1194 const size_t dead_to_left = pointer_delta(addr, cp->destination());
1195 const size_t space_cap = space->capacity_in_words();
1196 const double dead_to_left_pct = double(dead_to_left) / space_cap;
1197 const size_t live_to_right = new_top - cp->destination();
1198 const size_t dead_to_right = space->top() - addr - live_to_right;
1199
1200 tty->print_cr("%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W(5) " "
1201 "spl=" SIZE_FORMAT " "
1202 "d2l=" SIZE_FORMAT " d2l%%=%6.4f "
1203 "d2r=" SIZE_FORMAT " l2r=" SIZE_FORMAT
1204 " ratio=%10.8f",
1205 algorithm, p2i(addr), region_idx,
1206 space_live,
1207 dead_to_left, dead_to_left_pct,
1208 dead_to_right, live_to_right,
1209 double(dead_to_right) / live_to_right);
1210}
1211#endif // #ifndef PRODUCT
1212
1213// Return a fraction indicating how much of the generation can be treated as
1214// "dead wood" (i.e., not reclaimed). The function uses a normal distribution
1215// based on the density of live objects in the generation to determine a limit,
1216// which is then adjusted so the return value is min_percent when the density is
1217// 1.
1218//
1219// The following table shows some return values for a different values of the
1220// standard deviation (ParallelOldDeadWoodLimiterStdDev); the mean is 0.5 and
1221// min_percent is 1.
1222//
1223// fraction allowed as dead wood
1224// -----------------------------------------------------------------
1225// density std_dev=70 std_dev=75 std_dev=80 std_dev=85 std_dev=90 std_dev=95
1226// ------- ---------- ---------- ---------- ---------- ---------- ----------
1227// 0.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
1228// 0.05000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
1229// 0.10000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
1230// 0.15000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
1231// 0.20000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
1232// 0.25000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
1233// 0.30000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
1234// 0.35000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
1235// 0.40000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
1236// 0.45000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
1237// 0.50000 0.13832410 0.11599237 0.09847664 0.08456518 0.07338887 0.06431510
1238// 0.55000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
1239// 0.60000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
1240// 0.65000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
1241// 0.70000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
1242// 0.75000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
1243// 0.80000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
1244// 0.85000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
1245// 0.90000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
1246// 0.95000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
1247// 1.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
1248
1249double PSParallelCompact::dead_wood_limiter(double density, size_t min_percent)
1250{
1251 assert(_dwl_initialized, "uninitialized");
1252
1253 // The raw limit is the value of the normal distribution at x = density.
1254 const double raw_limit = normal_distribution(density);
1255
1256 // Adjust the raw limit so it becomes the minimum when the density is 1.
1257 //
1258 // First subtract the adjustment value (which is simply the precomputed value
1259 // normal_distribution(1.0)); this yields a value of 0 when the density is 1.
1260 // Then add the minimum value, so the minimum is returned when the density is
1261 // 1. Finally, prevent negative values, which occur when the mean is not 0.5.
1262 const double min = double(min_percent) / 100.0;
1263 const double limit = raw_limit - _dwl_adjustment + min;
1264 return MAX2(limit, 0.0);
1265}
1266
1267ParallelCompactData::RegionData*
1268PSParallelCompact::first_dead_space_region(const RegionData* beg,
1269 const RegionData* end)
1270{
1271 const size_t region_size = ParallelCompactData::RegionSize;
1272 ParallelCompactData& sd = summary_data();
1273 size_t left = sd.region(beg);
1274 size_t right = end > beg ? sd.region(end) - 1 : left;
1275
1276 // Binary search.
1277 while (left < right) {
1278 // Equivalent to (left + right) / 2, but does not overflow.
1279 const size_t middle = left + (right - left) / 2;
1280 RegionData* const middle_ptr = sd.region(middle);
1281 HeapWord* const dest = middle_ptr->destination();
1282 HeapWord* const addr = sd.region_to_addr(middle);
1283 assert(dest != NULL, "sanity");
1284 assert(dest <= addr, "must move left");
1285
1286 if (middle > left && dest < addr) {
1287 right = middle - 1;
1288 } else if (middle < right && middle_ptr->data_size() == region_size) {
1289 left = middle + 1;
1290 } else {
1291 return middle_ptr;
1292 }
1293 }
1294 return sd.region(left);
1295}
1296
1297ParallelCompactData::RegionData*
1298PSParallelCompact::dead_wood_limit_region(const RegionData* beg,
1299 const RegionData* end,
1300 size_t dead_words)
1301{
1302 ParallelCompactData& sd = summary_data();
1303 size_t left = sd.region(beg);
1304 size_t right = end > beg ? sd.region(end) - 1 : left;
1305
1306 // Binary search.
1307 while (left < right) {
1308 // Equivalent to (left + right) / 2, but does not overflow.
1309 const size_t middle = left + (right - left) / 2;
1310 RegionData* const middle_ptr = sd.region(middle);
1311 HeapWord* const dest = middle_ptr->destination();
1312 HeapWord* const addr = sd.region_to_addr(middle);
1313 assert(dest != NULL, "sanity");
1314 assert(dest <= addr, "must move left");
1315
1316 const size_t dead_to_left = pointer_delta(addr, dest);
1317 if (middle > left && dead_to_left > dead_words) {
1318 right = middle - 1;
1319 } else if (middle < right && dead_to_left < dead_words) {
1320 left = middle + 1;
1321 } else {
1322 return middle_ptr;
1323 }
1324 }
1325 return sd.region(left);
1326}
1327
1328// The result is valid during the summary phase, after the initial summarization
1329// of each space into itself, and before final summarization.
1330inline double
1331PSParallelCompact::reclaimed_ratio(const RegionData* const cp,
1332 HeapWord* const bottom,
1333 HeapWord* const top,
1334 HeapWord* const new_top)
1335{
1336 ParallelCompactData& sd = summary_data();
1337
1338 assert(cp != NULL, "sanity");
1339 assert(bottom != NULL, "sanity");
1340 assert(top != NULL, "sanity");
1341 assert(new_top != NULL, "sanity");
1342 assert(top >= new_top, "summary data problem?");
1343 assert(new_top > bottom, "space is empty; should not be here");
1344 assert(new_top >= cp->destination(), "sanity");
1345 assert(top >= sd.region_to_addr(cp), "sanity");
1346
1347 HeapWord* const destination = cp->destination();
1348 const size_t dense_prefix_live = pointer_delta(destination, bottom);
1349 const size_t compacted_region_live = pointer_delta(new_top, destination);
1350 const size_t compacted_region_used = pointer_delta(top,
1351 sd.region_to_addr(cp));
1352 const size_t reclaimable = compacted_region_used - compacted_region_live;
1353
1354 const double divisor = dense_prefix_live + 1.25 * compacted_region_live;
1355 return double(reclaimable) / divisor;
1356}
1357
1358// Return the address of the end of the dense prefix, a.k.a. the start of the
1359// compacted region. The address is always on a region boundary.
1360//
1361// Completely full regions at the left are skipped, since no compaction can
1362// occur in those regions. Then the maximum amount of dead wood to allow is
1363// computed, based on the density (amount live / capacity) of the generation;
1364// the region with approximately that amount of dead space to the left is
1365// identified as the limit region. Regions between the last completely full
1366// region and the limit region are scanned and the one that has the best
1367// (maximum) reclaimed_ratio() is selected.
1368HeapWord*
1369PSParallelCompact::compute_dense_prefix(const SpaceId id,
1370 bool maximum_compaction)
1371{
1372 const size_t region_size = ParallelCompactData::RegionSize;
1373 const ParallelCompactData& sd = summary_data();
1374
1375 const MutableSpace* const space = _space_info[id].space();
1376 HeapWord* const top = space->top();
1377 HeapWord* const top_aligned_up = sd.region_align_up(top);
1378 HeapWord* const new_top = _space_info[id].new_top();
1379 HeapWord* const new_top_aligned_up = sd.region_align_up(new_top);
1380 HeapWord* const bottom = space->bottom();
1381 const RegionData* const beg_cp = sd.addr_to_region_ptr(bottom);
1382 const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
1383 const RegionData* const new_top_cp =
1384 sd.addr_to_region_ptr(new_top_aligned_up);
1385
1386 // Skip full regions at the beginning of the space--they are necessarily part
1387 // of the dense prefix.
1388 const RegionData* const full_cp = first_dead_space_region(beg_cp, new_top_cp);
1389 assert(full_cp->destination() == sd.region_to_addr(full_cp) ||
1390 space->is_empty(), "no dead space allowed to the left");
1391 assert(full_cp->data_size() < region_size || full_cp == new_top_cp - 1,
1392 "region must have dead space");
1393
1394 // The gc number is saved whenever a maximum compaction is done, and used to
1395 // determine when the maximum compaction interval has expired. This avoids
1396 // successive max compactions for different reasons.
1397 assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");
1398 const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;
1399 const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval ||
1400 total_invocations() == HeapFirstMaximumCompactionCount;
1401 if (maximum_compaction || full_cp == top_cp || interval_ended) {
1402 _maximum_compaction_gc_num = total_invocations();
1403 return sd.region_to_addr(full_cp);
1404 }
1405
1406 const size_t space_live = pointer_delta(new_top, bottom);
1407 const size_t space_used = space->used_in_words();
1408 const size_t space_capacity = space->capacity_in_words();
1409
1410 const double density = double(space_live) / double(space_capacity);
1411 const size_t min_percent_free = MarkSweepDeadRatio;
1412 const double limiter = dead_wood_limiter(density, min_percent_free);
1413 const size_t dead_wood_max = space_used - space_live;
1414 const size_t dead_wood_limit = MIN2(size_t(space_capacity * limiter),
1415 dead_wood_max);
1416
1417 if (TraceParallelOldGCDensePrefix) {
1418 tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "
1419 "space_cap=" SIZE_FORMAT,
1420 space_live, space_used,
1421 space_capacity);
1422 tty->print_cr("dead_wood_limiter(%6.4f, " SIZE_FORMAT ")=%6.4f "
1423 "dead_wood_max=" SIZE_FORMAT " dead_wood_limit=" SIZE_FORMAT,
1424 density, min_percent_free, limiter,
1425 dead_wood_max, dead_wood_limit);
1426 }
1427
1428 // Locate the region with the desired amount of dead space to the left.
1429 const RegionData* const limit_cp =
1430 dead_wood_limit_region(full_cp, top_cp, dead_wood_limit);
1431
1432 // Scan from the first region with dead space to the limit region and find the
1433 // one with the best (largest) reclaimed ratio.
1434 double best_ratio = 0.0;
1435 const RegionData* best_cp = full_cp;
1436 for (const RegionData* cp = full_cp; cp < limit_cp; ++cp) {
1437 double tmp_ratio = reclaimed_ratio(cp, bottom, top, new_top);
1438 if (tmp_ratio > best_ratio) {
1439 best_cp = cp;
1440 best_ratio = tmp_ratio;
1441 }
1442 }
1443
1444 return sd.region_to_addr(best_cp);
1445}
1446
1447void PSParallelCompact::summarize_spaces_quick()
1448{
1449 for (unsigned int i = 0; i < last_space_id; ++i) {
1450 const MutableSpace* space = _space_info[i].space();
1451 HeapWord** nta = _space_info[i].new_top_addr();
1452 bool result = _summary_data.summarize(_space_info[i].split_info(),
1453 space->bottom(), space->top(), NULL,
1454 space->bottom(), space->end(), nta);
1455 assert(result, "space must fit into itself");
1456 _space_info[i].set_dense_prefix(space->bottom());
1457 }
1458}
1459
1460void PSParallelCompact::fill_dense_prefix_end(SpaceId id)
1461{
1462 HeapWord* const dense_prefix_end = dense_prefix(id);
1463 const RegionData* region = _summary_data.addr_to_region_ptr(dense_prefix_end);
1464 const idx_t dense_prefix_bit = _mark_bitmap.addr_to_bit(dense_prefix_end);
1465 if (dead_space_crosses_boundary(region, dense_prefix_bit)) {
1466 // Only enough dead space is filled so that any remaining dead space to the
1467 // left is larger than the minimum filler object. (The remainder is filled
1468 // during the copy/update phase.)
1469 //
1470 // The size of the dead space to the right of the boundary is not a
1471 // concern, since compaction will be able to use whatever space is
1472 // available.
1473 //
1474 // Here '||' is the boundary, 'x' represents a don't care bit and a box
1475 // surrounds the space to be filled with an object.
1476 //
1477 // In the 32-bit VM, each bit represents two 32-bit words:
1478 // +---+
1479 // a) beg_bits: ... x x x | 0 | || 0 x x ...
1480 // end_bits: ... x x x | 0 | || 0 x x ...
1481 // +---+
1482 //
1483 // In the 64-bit VM, each bit represents one 64-bit word:
1484 // +------------+
1485 // b) beg_bits: ... x x x | 0 || 0 | x x ...
1486 // end_bits: ... x x 1 | 0 || 0 | x x ...
1487 // +------------+
1488 // +-------+
1489 // c) beg_bits: ... x x | 0 0 | || 0 x x ...
1490 // end_bits: ... x 1 | 0 0 | || 0 x x ...
1491 // +-------+
1492 // +-----------+
1493 // d) beg_bits: ... x | 0 0 0 | || 0 x x ...
1494 // end_bits: ... 1 | 0 0 0 | || 0 x x ...
1495 // +-----------+
1496 // +-------+
1497 // e) beg_bits: ... 0 0 | 0 0 | || 0 x x ...
1498 // end_bits: ... 0 0 | 0 0 | || 0 x x ...
1499 // +-------+
1500
1501 // Initially assume case a, c or e will apply.
1502 size_t obj_len = CollectedHeap::min_fill_size();
1503 HeapWord* obj_beg = dense_prefix_end - obj_len;
1504
1505#ifdef _LP64
1506 if (MinObjAlignment > 1) { // object alignment > heap word size
1507 // Cases a, c or e.
1508 } else if (_mark_bitmap.is_obj_end(dense_prefix_bit - 2)) {
1509 // Case b above.
1510 obj_beg = dense_prefix_end - 1;
1511 } else if (!_mark_bitmap.is_obj_end(dense_prefix_bit - 3) &&
1512 _mark_bitmap.is_obj_end(dense_prefix_bit - 4)) {
1513 // Case d above.
1514 obj_beg = dense_prefix_end - 3;
1515 obj_len = 3;
1516 }
1517#endif // #ifdef _LP64
1518
1519 CollectedHeap::fill_with_object(obj_beg, obj_len);
1520 _mark_bitmap.mark_obj(obj_beg, obj_len);
1521 _summary_data.add_obj(obj_beg, obj_len);
1522 assert(start_array(id) != NULL, "sanity");
1523 start_array(id)->allocate_block(obj_beg);
1524 }
1525}
1526
1527void
1528PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction)
1529{
1530 assert(id < last_space_id, "id out of range");
1531 assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom(),
1532 "should have been reset in summarize_spaces_quick()");
1533
1534 const MutableSpace* space = _space_info[id].space();
1535 if (_space_info[id].new_top() != space->bottom()) {
1536 HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction);
1537 _space_info[id].set_dense_prefix(dense_prefix_end);
1538
1539#ifndef PRODUCT
1540 if (TraceParallelOldGCDensePrefix) {
1541 print_dense_prefix_stats("ratio", id, maximum_compaction,
1542 dense_prefix_end);
1543 HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction);
1544 print_dense_prefix_stats("density", id, maximum_compaction, addr);
1545 }
1546#endif // #ifndef PRODUCT
1547
1548 // Recompute the summary data, taking into account the dense prefix. If
1549 // every last byte will be reclaimed, then the existing summary data which
1550 // compacts everything can be left in place.
1551 if (!maximum_compaction && dense_prefix_end != space->bottom()) {
1552 // If dead space crosses the dense prefix boundary, it is (at least
1553 // partially) filled with a dummy object, marked live and added to the
1554 // summary data. This simplifies the copy/update phase and must be done
1555 // before the final locations of objects are determined, to prevent
1556 // leaving a fragment of dead space that is too small to fill.
1557 fill_dense_prefix_end(id);
1558
1559 // Compute the destination of each Region, and thus each object.
1560 _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end);
1561 _summary_data.summarize(_space_info[id].split_info(),
1562 dense_prefix_end, space->top(), NULL,
1563 dense_prefix_end, space->end(),
1564 _space_info[id].new_top_addr());
1565 }
1566 }
1567
1568 if (log_develop_is_enabled(Trace, gc, compaction)) {
1569 const size_t region_size = ParallelCompactData::RegionSize;
1570 HeapWord* const dense_prefix_end = _space_info[id].dense_prefix();
1571 const size_t dp_region = _summary_data.addr_to_region_idx(dense_prefix_end);
1572 const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom());
1573 HeapWord* const new_top = _space_info[id].new_top();
1574 const HeapWord* nt_aligned_up = _summary_data.region_align_up(new_top);
1575 const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end);
1576 log_develop_trace(gc, compaction)(
1577 "id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " "
1578 "dp_region=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " "
1579 "cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT,
1580 id, space->capacity_in_words(), p2i(dense_prefix_end),
1581 dp_region, dp_words / region_size,
1582 cr_words / region_size, p2i(new_top));
1583 }
1584}
1585
1586#ifndef PRODUCT
1587void PSParallelCompact::summary_phase_msg(SpaceId dst_space_id,
1588 HeapWord* dst_beg, HeapWord* dst_end,
1589 SpaceId src_space_id,
1590 HeapWord* src_beg, HeapWord* src_end)
1591{
1592 log_develop_trace(gc, compaction)(
1593 "Summarizing %d [%s] into %d [%s]: "
1594 "src=" PTR_FORMAT "-" PTR_FORMAT " "
1595 SIZE_FORMAT "-" SIZE_FORMAT " "
1596 "dst=" PTR_FORMAT "-" PTR_FORMAT " "
1597 SIZE_FORMAT "-" SIZE_FORMAT,
1598 src_space_id, space_names[src_space_id],
1599 dst_space_id, space_names[dst_space_id],
1600 p2i(src_beg), p2i(src_end),
1601 _summary_data.addr_to_region_idx(src_beg),
1602 _summary_data.addr_to_region_idx(src_end),
1603 p2i(dst_beg), p2i(dst_end),
1604 _summary_data.addr_to_region_idx(dst_beg),
1605 _summary_data.addr_to_region_idx(dst_end));
1606}
1607#endif // #ifndef PRODUCT
1608
1609void PSParallelCompact::summary_phase(ParCompactionManager* cm,
1610 bool maximum_compaction)
1611{
1612 GCTraceTime(Info, gc, phases) tm("Summary Phase", &_gc_timer);
1613
1614#ifdef ASSERT
1615 if (TraceParallelOldGCMarkingPhase) {
1616 tty->print_cr("add_obj_count=" SIZE_FORMAT " "
1617 "add_obj_bytes=" SIZE_FORMAT,
1618 add_obj_count, add_obj_size * HeapWordSize);
1619 tty->print_cr("mark_bitmap_count=" SIZE_FORMAT " "
1620 "mark_bitmap_bytes=" SIZE_FORMAT,
1621 mark_bitmap_count, mark_bitmap_size * HeapWordSize);
1622 }
1623#endif // #ifdef ASSERT
1624
1625 // Quick summarization of each space into itself, to see how much is live.
1626 summarize_spaces_quick();
1627
1628 log_develop_trace(gc, compaction)("summary phase: after summarizing each space to self");
1629 NOT_PRODUCT(print_region_ranges());
1630 NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1631
1632 // The amount of live data that will end up in old space (assuming it fits).
1633 size_t old_space_total_live = 0;
1634 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1635 old_space_total_live += pointer_delta(_space_info[id].new_top(),
1636 _space_info[id].space()->bottom());
1637 }
1638
1639 MutableSpace* const old_space = _space_info[old_space_id].space();
1640 const size_t old_capacity = old_space->capacity_in_words();
1641 if (old_space_total_live > old_capacity) {
1642 // XXX - should also try to expand
1643 maximum_compaction = true;
1644 }
1645
1646 // Old generations.
1647 summarize_space(old_space_id, maximum_compaction);
1648
1649 // Summarize the remaining spaces in the young gen. The initial target space
1650 // is the old gen. If a space does not fit entirely into the target, then the
1651 // remainder is compacted into the space itself and that space becomes the new
1652 // target.
1653 SpaceId dst_space_id = old_space_id;
1654 HeapWord* dst_space_end = old_space->end();
1655 HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
1656 for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
1657 const MutableSpace* space = _space_info[id].space();
1658 const size_t live = pointer_delta(_space_info[id].new_top(),
1659 space->bottom());
1660 const size_t available = pointer_delta(dst_space_end, *new_top_addr);
1661
1662 NOT_PRODUCT(summary_phase_msg(dst_space_id, *new_top_addr, dst_space_end,
1663 SpaceId(id), space->bottom(), space->top());)
1664 if (live > 0 && live <= available) {
1665 // All the live data will fit.
1666 bool done = _summary_data.summarize(_space_info[id].split_info(),
1667 space->bottom(), space->top(),
1668 NULL,
1669 *new_top_addr, dst_space_end,
1670 new_top_addr);
1671 assert(done, "space must fit into old gen");
1672
1673 // Reset the new_top value for the space.
1674 _space_info[id].set_new_top(space->bottom());
1675 } else if (live > 0) {
1676 // Attempt to fit part of the source space into the target space.
1677 HeapWord* next_src_addr = NULL;
1678 bool done = _summary_data.summarize(_space_info[id].split_info(),
1679 space->bottom(), space->top(),
1680 &next_src_addr,
1681 *new_top_addr, dst_space_end,
1682 new_top_addr);
1683 assert(!done, "space should not fit into old gen");
1684 assert(next_src_addr != NULL, "sanity");
1685
1686 // The source space becomes the new target, so the remainder is compacted
1687 // within the space itself.
1688 dst_space_id = SpaceId(id);
1689 dst_space_end = space->end();
1690 new_top_addr = _space_info[id].new_top_addr();
1691 NOT_PRODUCT(summary_phase_msg(dst_space_id,
1692 space->bottom(), dst_space_end,
1693 SpaceId(id), next_src_addr, space->top());)
1694 done = _summary_data.summarize(_space_info[id].split_info(),
1695 next_src_addr, space->top(),
1696 NULL,
1697 space->bottom(), dst_space_end,
1698 new_top_addr);
1699 assert(done, "space must fit when compacted into itself");
1700 assert(*new_top_addr <= space->top(), "usage should not grow");
1701 }
1702 }
1703
1704 log_develop_trace(gc, compaction)("Summary_phase: after final summarization");
1705 NOT_PRODUCT(print_region_ranges());
1706 NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1707}
1708
1709// This method should contain all heap-specific policy for invoking a full
1710// collection. invoke_no_policy() will only attempt to compact the heap; it
1711// will do nothing further. If we need to bail out for policy reasons, scavenge
1712// before full gc, or any other specialized behavior, it needs to be added here.
1713//
1714// Note that this method should only be called from the vm_thread while at a
1715// safepoint.
1716//
1717// Note that the all_soft_refs_clear flag in the soft ref policy
1718// may be true because this method can be called without intervening
1719// activity. For example when the heap space is tight and full measure
1720// are being taken to free space.
1721void PSParallelCompact::invoke(bool maximum_heap_compaction) {
1722 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
1723 assert(Thread::current() == (Thread*)VMThread::vm_thread(),
1724 "should be in vm thread");
1725
1726 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1727 GCCause::Cause gc_cause = heap->gc_cause();
1728 assert(!heap->is_gc_active(), "not reentrant");
1729
1730 PSAdaptiveSizePolicy* policy = heap->size_policy();
1731 IsGCActiveMark mark;
1732
1733 if (ScavengeBeforeFullGC) {
1734 PSScavenge::invoke_no_policy();
1735 }
1736
1737 const bool clear_all_soft_refs =
1738 heap->soft_ref_policy()->should_clear_all_soft_refs();
1739
1740 PSParallelCompact::invoke_no_policy(clear_all_soft_refs ||
1741 maximum_heap_compaction);
1742}
1743
1744// This method contains no policy. You should probably
1745// be calling invoke() instead.
1746bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
1747 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
1748 assert(ref_processor() != NULL, "Sanity");
1749
1750 if (GCLocker::check_active_before_gc()) {
1751 return false;
1752 }
1753
1754 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1755
1756 GCIdMark gc_id_mark;
1757 _gc_timer.register_gc_start();
1758 _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
1759
1760 TimeStamp marking_start;
1761 TimeStamp compaction_start;
1762 TimeStamp collection_exit;
1763
1764 GCCause::Cause gc_cause = heap->gc_cause();
1765 PSYoungGen* young_gen = heap->young_gen();
1766 PSOldGen* old_gen = heap->old_gen();
1767 PSAdaptiveSizePolicy* size_policy = heap->size_policy();
1768
1769 // The scope of casr should end after code that can change
1770 // SoftRefPolicy::_should_clear_all_soft_refs.
1771 ClearedAllSoftRefs casr(maximum_heap_compaction,
1772 heap->soft_ref_policy());
1773
1774 if (ZapUnusedHeapArea) {
1775 // Save information needed to minimize mangling
1776 heap->record_gen_tops_before_GC();
1777 }
1778
1779 // Make sure data structures are sane, make the heap parsable, and do other
1780 // miscellaneous bookkeeping.
1781 pre_compact();
1782
1783 PreGCValues pre_gc_values(heap);
1784
1785 // Get the compaction manager reserved for the VM thread.
1786 ParCompactionManager* const vmthread_cm =
1787 ParCompactionManager::manager_array(gc_task_manager()->workers());
1788
1789 {
1790 ResourceMark rm;
1791 HandleMark hm;
1792
1793 // Set the number of GC threads to be used in this collection
1794 gc_task_manager()->set_active_gang();
1795 gc_task_manager()->task_idle_workers();
1796
1797 GCTraceCPUTime tcpu;
1798 GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause, true);
1799
1800 heap->pre_full_gc_dump(&_gc_timer);
1801
1802 TraceCollectorStats tcs(counters());
1803 TraceMemoryManagerStats tms(heap->old_gc_manager(), gc_cause);
1804
1805 if (log_is_enabled(Debug, gc, heap, exit)) {
1806 accumulated_time()->start();
1807 }
1808
1809 // Let the size policy know we're starting
1810 size_policy->major_collection_begin();
1811
1812#if COMPILER2_OR_JVMCI
1813 DerivedPointerTable::clear();
1814#endif
1815
1816 ref_processor()->enable_discovery();
1817 ref_processor()->setup_policy(maximum_heap_compaction);
1818
1819 bool marked_for_unloading = false;
1820
1821 marking_start.update();
1822 marking_phase(vmthread_cm, maximum_heap_compaction, &_gc_tracer);
1823
1824 bool max_on_system_gc = UseMaximumCompactionOnSystemGC
1825 && GCCause::is_user_requested_gc(gc_cause);
1826 summary_phase(vmthread_cm, maximum_heap_compaction || max_on_system_gc);
1827
1828#if COMPILER2_OR_JVMCI
1829 assert(DerivedPointerTable::is_active(), "Sanity");
1830 DerivedPointerTable::set_active(false);
1831#endif
1832
1833 // adjust_roots() updates Universe::_intArrayKlassObj which is
1834 // needed by the compaction for filling holes in the dense prefix.
1835 adjust_roots(vmthread_cm);
1836
1837 compaction_start.update();
1838 compact();
1839
1840 // Reset the mark bitmap, summary data, and do other bookkeeping. Must be
1841 // done before resizing.
1842 post_compact();
1843
1844 // Let the size policy know we're done
1845 size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
1846
1847 if (UseAdaptiveSizePolicy) {
1848 log_debug(gc, ergo)("AdaptiveSizeStart: collection: %d ", heap->total_collections());
1849 log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT,
1850 old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
1851
1852 // Don't check if the size_policy is ready here. Let
1853 // the size_policy check that internally.
1854 if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
1855 AdaptiveSizePolicy::should_update_promo_stats(gc_cause)) {
1856 // Swap the survivor spaces if from_space is empty. The
1857 // resize_young_gen() called below is normally used after
1858 // a successful young GC and swapping of survivor spaces;
1859 // otherwise, it will fail to resize the young gen with
1860 // the current implementation.
1861 if (young_gen->from_space()->is_empty()) {
1862 young_gen->from_space()->clear(SpaceDecorator::Mangle);
1863 young_gen->swap_spaces();
1864 }
1865
1866 // Calculate optimal free space amounts
1867 assert(young_gen->max_size() >
1868 young_gen->from_space()->capacity_in_bytes() +
1869 young_gen->to_space()->capacity_in_bytes(),
1870 "Sizes of space in young gen are out-of-bounds");
1871
1872 size_t young_live = young_gen->used_in_bytes();
1873 size_t eden_live = young_gen->eden_space()->used_in_bytes();
1874 size_t old_live = old_gen->used_in_bytes();
1875 size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
1876 size_t max_old_gen_size = old_gen->max_gen_size();
1877 size_t max_eden_size = young_gen->max_size() -
1878 young_gen->from_space()->capacity_in_bytes() -
1879 young_gen->to_space()->capacity_in_bytes();
1880
1881 // Used for diagnostics
1882 size_policy->clear_generation_free_space_flags();
1883
1884 size_policy->compute_generations_free_space(young_live,
1885 eden_live,
1886 old_live,
1887 cur_eden,
1888 max_old_gen_size,
1889 max_eden_size,
1890 true /* full gc*/);
1891
1892 size_policy->check_gc_overhead_limit(eden_live,
1893 max_old_gen_size,
1894 max_eden_size,
1895 true /* full gc*/,
1896 gc_cause,
1897 heap->soft_ref_policy());
1898
1899 size_policy->decay_supplemental_growth(true /* full gc*/);
1900
1901 heap->resize_old_gen(
1902 size_policy->calculated_old_free_size_in_bytes());
1903
1904 heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
1905 size_policy->calculated_survivor_size_in_bytes());
1906 }
1907
1908 log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections());
1909 }
1910
1911 if (UsePerfData) {
1912 PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();
1913 counters->update_counters();
1914 counters->update_old_capacity(old_gen->capacity_in_bytes());
1915 counters->update_young_capacity(young_gen->capacity_in_bytes());
1916 }
1917
1918 heap->resize_all_tlabs();
1919
1920 // Resize the metaspace capacity after a collection
1921 MetaspaceGC::compute_new_size();
1922
1923 if (log_is_enabled(Debug, gc, heap, exit)) {
1924 accumulated_time()->stop();
1925 }
1926
1927 young_gen->print_used_change(pre_gc_values.young_gen_used());
1928 old_gen->print_used_change(pre_gc_values.old_gen_used());
1929 MetaspaceUtils::print_metaspace_change(pre_gc_values.metadata_used());
1930
1931 // Track memory usage and detect low memory
1932 MemoryService::track_memory_usage();
1933 heap->update_counters();
1934 gc_task_manager()->release_idle_workers();
1935
1936 heap->post_full_gc_dump(&_gc_timer);
1937 }
1938
1939#ifdef ASSERT
1940 for (size_t i = 0; i < ParallelGCThreads + 1; ++i) {
1941 ParCompactionManager* const cm =
1942 ParCompactionManager::manager_array(int(i));
1943 assert(cm->marking_stack()->is_empty(), "should be empty");
1944 assert(cm->region_stack()->is_empty(), "Region stack " SIZE_FORMAT " is not empty", i);
1945 }
1946#endif // ASSERT
1947
1948 if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
1949 HandleMark hm; // Discard invalid handles created during verification
1950 Universe::verify("After GC");
1951 }
1952
1953 // Re-verify object start arrays
1954 if (VerifyObjectStartArray &&
1955 VerifyAfterGC) {
1956 old_gen->verify_object_start_array();
1957 }
1958
1959 if (ZapUnusedHeapArea) {
1960 old_gen->object_space()->check_mangled_unused_area_complete();
1961 }
1962
1963 NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
1964
1965 collection_exit.update();
1966
1967 heap->print_heap_after_gc();
1968 heap->trace_heap_after_gc(&_gc_tracer);
1969
1970 log_debug(gc, task, time)("VM-Thread " JLONG_FORMAT " " JLONG_FORMAT " " JLONG_FORMAT,
1971 marking_start.ticks(), compaction_start.ticks(),
1972 collection_exit.ticks());
1973 gc_task_manager()->print_task_time_stamps();
1974
1975#ifdef TRACESPINNING
1976 ParallelTaskTerminator::print_termination_counts();
1977#endif
1978
1979 AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections());
1980
1981 _gc_timer.register_gc_end();
1982
1983 _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
1984 _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
1985
1986 return true;
1987}
1988
1989bool PSParallelCompact::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,
1990 PSYoungGen* young_gen,
1991 PSOldGen* old_gen) {
1992 MutableSpace* const eden_space = young_gen->eden_space();
1993 assert(!eden_space->is_empty(), "eden must be non-empty");
1994 assert(young_gen->virtual_space()->alignment() ==
1995 old_gen->virtual_space()->alignment(), "alignments do not match");
1996
1997 // We also return false when it's a heterogenous heap because old generation cannot absorb data from eden
1998 // when it is allocated on different memory (example, nv-dimm) than young.
1999 if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary) ||
2000 ParallelArguments::is_heterogeneous_heap()) {
2001 return false;
2002 }
2003
2004 // Both generations must be completely committed.
2005 if (young_gen->virtual_space()->uncommitted_size() != 0) {
2006 return false;
2007 }
2008 if (old_gen->virtual_space()->uncommitted_size() != 0) {
2009 return false;
2010 }
2011
2012 // Figure out how much to take from eden. Include the average amount promoted
2013 // in the total; otherwise the next young gen GC will simply bail out to a
2014 // full GC.
2015 const size_t alignment = old_gen->virtual_space()->alignment();
2016 const size_t eden_used = eden_space->used_in_bytes();
2017 const size_t promoted = (size_t)size_policy->avg_promoted()->padded_average();
2018 const size_t absorb_size = align_up(eden_used + promoted, alignment);
2019 const size_t eden_capacity = eden_space->capacity_in_bytes();
2020
2021 if (absorb_size >= eden_capacity) {
2022 return false; // Must leave some space in eden.
2023 }
2024
2025 const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;
2026 if (new_young_size < young_gen->min_gen_size()) {
2027 return false; // Respect young gen minimum size.
2028 }
2029
2030 log_trace(gc, ergo, heap)(" absorbing " SIZE_FORMAT "K: "
2031 "eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "
2032 "from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "
2033 "young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",
2034 absorb_size / K,
2035 eden_capacity / K, (eden_capacity - absorb_size) / K,
2036 young_gen->from_space()->used_in_bytes() / K,
2037 young_gen->to_space()->used_in_bytes() / K,
2038 young_gen->capacity_in_bytes() / K, new_young_size / K);
2039
2040 // Fill the unused part of the old gen.
2041 MutableSpace* const old_space = old_gen->object_space();
2042 HeapWord* const unused_start = old_space->top();
2043 size_t const unused_words = pointer_delta(old_space->end(), unused_start);
2044
2045 if (unused_words > 0) {
2046 if (unused_words < CollectedHeap::min_fill_size()) {
2047 return false; // If the old gen cannot be filled, must give up.
2048 }
2049 CollectedHeap::fill_with_objects(unused_start, unused_words);
2050 }
2051
2052 // Take the live data from eden and set both top and end in the old gen to
2053 // eden top. (Need to set end because reset_after_change() mangles the region
2054 // from end to virtual_space->high() in debug builds).
2055 HeapWord* const new_top = eden_space->top();
2056 old_gen->virtual_space()->expand_into(young_gen->virtual_space(),
2057 absorb_size);
2058 young_gen->reset_after_change();
2059 old_space->set_top(new_top);
2060 old_space->set_end(new_top);
2061 old_gen->reset_after_change();
2062
2063 // Update the object start array for the filler object and the data from eden.
2064 ObjectStartArray* const start_array = old_gen->start_array();
2065 for (HeapWord* p = unused_start; p < new_top; p += oop(p)->size()) {
2066 start_array->allocate_block(p);
2067 }
2068
2069 // Could update the promoted average here, but it is not typically updated at
2070 // full GCs and the value to use is unclear. Something like
2071 //
2072 // cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.
2073
2074 size_policy->set_bytes_absorbed_from_eden(absorb_size);
2075 return true;
2076}
2077
2078GCTaskManager* const PSParallelCompact::gc_task_manager() {
2079 assert(ParallelScavengeHeap::gc_task_manager() != NULL,
2080 "shouldn't return NULL");
2081 return ParallelScavengeHeap::gc_task_manager();
2082}
2083
2084class PCAddThreadRootsMarkingTaskClosure : public ThreadClosure {
2085private:
2086 GCTaskQueue* _q;
2087
2088public:
2089 PCAddThreadRootsMarkingTaskClosure(GCTaskQueue* q) : _q(q) { }
2090 void do_thread(Thread* t) {
2091 _q->enqueue(new ThreadRootsMarkingTask(t));
2092 }
2093};
2094
2095void PSParallelCompact::marking_phase(ParCompactionManager* cm,
2096 bool maximum_heap_compaction,
2097 ParallelOldTracer *gc_tracer) {
2098 // Recursively traverse all live objects and mark them
2099 GCTraceTime(Info, gc, phases) tm("Marking Phase", &_gc_timer);
2100
2101 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
2102 uint parallel_gc_threads = heap->gc_task_manager()->workers();
2103 uint active_gc_threads = heap->gc_task_manager()->active_workers();
2104 TaskQueueSetSuper* qset = ParCompactionManager::stack_array();
2105 TaskTerminator terminator(active_gc_threads, qset);
2106
2107 PCMarkAndPushClosure mark_and_push_closure(cm);
2108 ParCompactionManager::FollowStackClosure follow_stack_closure(cm);
2109
2110 // Need new claim bits before marking starts.
2111 ClassLoaderDataGraph::clear_claimed_marks();
2112
2113 {
2114 GCTraceTime(Debug, gc, phases) tm("Par Mark", &_gc_timer);
2115
2116 ParallelScavengeHeap::ParStrongRootsScope psrs;
2117
2118 GCTaskQueue* q = GCTaskQueue::create();
2119
2120 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::universe));
2121 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jni_handles));
2122 // We scan the thread roots in parallel
2123 PCAddThreadRootsMarkingTaskClosure cl(q);
2124 Threads::java_threads_and_vm_thread_do(&cl);
2125 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::object_synchronizer));
2126 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::management));
2127 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::system_dictionary));
2128 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::class_loader_data));
2129 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jvmti));
2130 q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::code_cache));
2131 JVMCI_ONLY(q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jvmci));)
2132
2133 if (active_gc_threads > 1) {
2134 for (uint j = 0; j < active_gc_threads; j++) {
2135 q->enqueue(new StealMarkingTask(terminator.terminator()));
2136 }
2137 }
2138
2139 gc_task_manager()->execute_and_wait(q);
2140 }
2141
2142 // Process reference objects found during marking
2143 {
2144 GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
2145
2146 ReferenceProcessorStats stats;
2147 ReferenceProcessorPhaseTimes pt(&_gc_timer, ref_processor()->max_num_queues());
2148
2149 if (ref_processor()->processing_is_mt()) {
2150 ref_processor()->set_active_mt_degree(active_gc_threads);
2151
2152 RefProcTaskExecutor task_executor;
2153 stats = ref_processor()->process_discovered_references(
2154 is_alive_closure(), &mark_and_push_closure, &follow_stack_closure,
2155 &task_executor, &pt);
2156 } else {
2157 stats = ref_processor()->process_discovered_references(
2158 is_alive_closure(), &mark_and_push_closure, &follow_stack_closure, NULL,
2159 &pt);
2160 }
2161
2162 gc_tracer->report_gc_reference_stats(stats);
2163 pt.print_all_references();
2164 }
2165
2166 // This is the point where the entire marking should have completed.
2167 assert(cm->marking_stacks_empty(), "Marking should have completed");
2168
2169 {
2170 GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
2171 WeakProcessor::weak_oops_do(is_alive_closure(), &do_nothing_cl);
2172 }
2173
2174 {
2175 GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
2176
2177 // Follow system dictionary roots and unload classes.
2178 bool purged_class = SystemDictionary::do_unloading(&_gc_timer);
2179
2180 // Unload nmethods.
2181 CodeCache::do_unloading(is_alive_closure(), purged_class);
2182
2183 // Prune dead klasses from subklass/sibling/implementor lists.
2184 Klass::clean_weak_klass_links(purged_class);
2185
2186 // Clean JVMCI metadata handles.
2187 JVMCI_ONLY(JVMCI::do_unloading(purged_class));
2188 }
2189
2190 _gc_tracer.report_object_count_after_gc(is_alive_closure());
2191}
2192
2193void PSParallelCompact::adjust_roots(ParCompactionManager* cm) {
2194 // Adjust the pointers to reflect the new locations
2195 GCTraceTime(Info, gc, phases) tm("Adjust Roots", &_gc_timer);
2196
2197 // Need new claim bits when tracing through and adjusting pointers.
2198 ClassLoaderDataGraph::clear_claimed_marks();
2199
2200 PCAdjustPointerClosure oop_closure(cm);
2201
2202 // General strong roots.
2203 Universe::oops_do(&oop_closure);
2204 JNIHandles::oops_do(&oop_closure); // Global (strong) JNI handles
2205 Threads::oops_do(&oop_closure, NULL);
2206 ObjectSynchronizer::oops_do(&oop_closure);
2207 Management::oops_do(&oop_closure);
2208 JvmtiExport::oops_do(&oop_closure);
2209 SystemDictionary::oops_do(&oop_closure);
2210 CLDToOopClosure cld_closure(&oop_closure, ClassLoaderData::_claim_strong);
2211 ClassLoaderDataGraph::cld_do(&cld_closure);
2212
2213 // Now adjust pointers in remaining weak roots. (All of which should
2214 // have been cleared if they pointed to non-surviving objects.)
2215 WeakProcessor::oops_do(&oop_closure);
2216
2217 CodeBlobToOopClosure adjust_from_blobs(&oop_closure, CodeBlobToOopClosure::FixRelocations);
2218 CodeCache::blobs_do(&adjust_from_blobs);
2219 AOT_ONLY(AOTLoader::oops_do(&oop_closure);)
2220
2221 JVMCI_ONLY(JVMCI::oops_do(&oop_closure);)
2222
2223 ref_processor()->weak_oops_do(&oop_closure);
2224 // Roots were visited so references into the young gen in roots
2225 // may have been scanned. Process them also.
2226 // Should the reference processor have a span that excludes
2227 // young gen objects?
2228 PSScavenge::reference_processor()->weak_oops_do(&oop_closure);
2229}
2230
2231// Helper class to print 8 region numbers per line and then print the total at the end.
2232class FillableRegionLogger : public StackObj {
2233private:
2234 Log(gc, compaction) log;
2235 static const int LineLength = 8;
2236 size_t _regions[LineLength];
2237 int _next_index;
2238 bool _enabled;
2239 size_t _total_regions;
2240public:
2241 FillableRegionLogger() : _next_index(0), _enabled(log_develop_is_enabled(Trace, gc, compaction)), _total_regions(0) { }
2242 ~FillableRegionLogger() {
2243 log.trace(SIZE_FORMAT " initially fillable regions", _total_regions);
2244 }
2245
2246 void print_line() {
2247 if (!_enabled || _next_index == 0) {
2248 return;
2249 }
2250 FormatBuffer<> line("Fillable: ");
2251 for (int i = 0; i < _next_index; i++) {
2252 line.append(" " SIZE_FORMAT_W(7), _regions[i]);
2253 }
2254 log.trace("%s", line.buffer());
2255 _next_index = 0;
2256 }
2257
2258 void handle(size_t region) {
2259 if (!_enabled) {
2260 return;
2261 }
2262 _regions[_next_index++] = region;
2263 if (_next_index == LineLength) {
2264 print_line();
2265 }
2266 _total_regions++;
2267 }
2268};
2269
2270void PSParallelCompact::prepare_region_draining_tasks(GCTaskQueue* q,
2271 uint parallel_gc_threads)
2272{
2273 GCTraceTime(Trace, gc, phases) tm("Drain Task Setup", &_gc_timer);
2274
2275 // Find the threads that are active
2276 unsigned int which = 0;
2277
2278 // Find all regions that are available (can be filled immediately) and
2279 // distribute them to the thread stacks. The iteration is done in reverse
2280 // order (high to low) so the regions will be removed in ascending order.
2281
2282 const ParallelCompactData& sd = PSParallelCompact::summary_data();
2283
2284 which = 0;
2285 // id + 1 is used to test termination so unsigned can
2286 // be used with an old_space_id == 0.
2287 FillableRegionLogger region_logger;
2288 for (unsigned int id = to_space_id; id + 1 > old_space_id; --id) {
2289 SpaceInfo* const space_info = _space_info + id;
2290 MutableSpace* const space = space_info->space();
2291 HeapWord* const new_top = space_info->new_top();
2292
2293 const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
2294 const size_t end_region =
2295 sd.addr_to_region_idx(sd.region_align_up(new_top));
2296
2297 for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
2298 if (sd.region(cur)->claim_unsafe()) {
2299 ParCompactionManager* cm = ParCompactionManager::manager_array(which);
2300 cm->region_stack()->push(cur);
2301 region_logger.handle(cur);
2302 // Assign regions to tasks in round-robin fashion.
2303 if (++which == parallel_gc_threads) {
2304 which = 0;
2305 }
2306 }
2307 }
2308 region_logger.print_line();
2309 }
2310}
2311
2312#define PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING 4
2313
2314void PSParallelCompact::enqueue_dense_prefix_tasks(GCTaskQueue* q,
2315 uint parallel_gc_threads) {
2316 GCTraceTime(Trace, gc, phases) tm("Dense Prefix Task Setup", &_gc_timer);
2317
2318 ParallelCompactData& sd = PSParallelCompact::summary_data();
2319
2320 // Iterate over all the spaces adding tasks for updating
2321 // regions in the dense prefix. Assume that 1 gc thread
2322 // will work on opening the gaps and the remaining gc threads
2323 // will work on the dense prefix.
2324 unsigned int space_id;
2325 for (space_id = old_space_id; space_id < last_space_id; ++ space_id) {
2326 HeapWord* const dense_prefix_end = _space_info[space_id].dense_prefix();
2327 const MutableSpace* const space = _space_info[space_id].space();
2328
2329 if (dense_prefix_end == space->bottom()) {
2330 // There is no dense prefix for this space.
2331 continue;
2332 }
2333
2334 // The dense prefix is before this region.
2335 size_t region_index_end_dense_prefix =
2336 sd.addr_to_region_idx(dense_prefix_end);
2337 RegionData* const dense_prefix_cp =
2338 sd.region(region_index_end_dense_prefix);
2339 assert(dense_prefix_end == space->end() ||
2340 dense_prefix_cp->available() ||
2341 dense_prefix_cp->claimed(),
2342 "The region after the dense prefix should always be ready to fill");
2343
2344 size_t region_index_start = sd.addr_to_region_idx(space->bottom());
2345
2346 // Is there dense prefix work?
2347 size_t total_dense_prefix_regions =
2348 region_index_end_dense_prefix - region_index_start;
2349 // How many regions of the dense prefix should be given to
2350 // each thread?
2351 if (total_dense_prefix_regions > 0) {
2352 uint tasks_for_dense_prefix = 1;
2353 if (total_dense_prefix_regions <=
2354 (parallel_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)) {
2355 // Don't over partition. This assumes that
2356 // PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING is a small integer value
2357 // so there are not many regions to process.
2358 tasks_for_dense_prefix = parallel_gc_threads;
2359 } else {
2360 // Over partition
2361 tasks_for_dense_prefix = parallel_gc_threads *
2362 PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING;
2363 }
2364 size_t regions_per_thread = total_dense_prefix_regions /
2365 tasks_for_dense_prefix;
2366 // Give each thread at least 1 region.
2367 if (regions_per_thread == 0) {
2368 regions_per_thread = 1;
2369 }
2370
2371 for (uint k = 0; k < tasks_for_dense_prefix; k++) {
2372 if (region_index_start >= region_index_end_dense_prefix) {
2373 break;
2374 }
2375 // region_index_end is not processed
2376 size_t region_index_end = MIN2(region_index_start + regions_per_thread,
2377 region_index_end_dense_prefix);
2378 q->enqueue(new UpdateDensePrefixTask(SpaceId(space_id),
2379 region_index_start,
2380 region_index_end));
2381 region_index_start = region_index_end;
2382 }
2383 }
2384 // This gets any part of the dense prefix that did not
2385 // fit evenly.
2386 if (region_index_start < region_index_end_dense_prefix) {
2387 q->enqueue(new UpdateDensePrefixTask(SpaceId(space_id),
2388 region_index_start,
2389 region_index_end_dense_prefix));
2390 }
2391 }
2392}
2393
2394void PSParallelCompact::enqueue_region_stealing_tasks(
2395 GCTaskQueue* q,
2396 ParallelTaskTerminator* terminator_ptr,
2397 uint parallel_gc_threads) {
2398 GCTraceTime(Trace, gc, phases) tm("Steal Task Setup", &_gc_timer);
2399
2400 // Once a thread has drained it's stack, it should try to steal regions from
2401 // other threads.
2402 for (uint j = 0; j < parallel_gc_threads; j++) {
2403 q->enqueue(new CompactionWithStealingTask(terminator_ptr));
2404 }
2405}
2406
2407#ifdef ASSERT
2408// Write a histogram of the number of times the block table was filled for a
2409// region.
2410void PSParallelCompact::write_block_fill_histogram()
2411{
2412 if (!log_develop_is_enabled(Trace, gc, compaction)) {
2413 return;
2414 }
2415
2416 Log(gc, compaction) log;
2417 ResourceMark rm;
2418 LogStream ls(log.trace());
2419 outputStream* out = &ls;
2420
2421 typedef ParallelCompactData::RegionData rd_t;
2422 ParallelCompactData& sd = summary_data();
2423
2424 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2425 MutableSpace* const spc = _space_info[id].space();
2426 if (spc->bottom() != spc->top()) {
2427 const rd_t* const beg = sd.addr_to_region_ptr(spc->bottom());
2428 HeapWord* const top_aligned_up = sd.region_align_up(spc->top());
2429 const rd_t* const end = sd.addr_to_region_ptr(top_aligned_up);
2430
2431 size_t histo[5] = { 0, 0, 0, 0, 0 };
2432 const size_t histo_len = sizeof(histo) / sizeof(size_t);
2433 const size_t region_cnt = pointer_delta(end, beg, sizeof(rd_t));
2434
2435 for (const rd_t* cur = beg; cur < end; ++cur) {
2436 ++histo[MIN2(cur->blocks_filled_count(), histo_len - 1)];
2437 }
2438 out->print("Block fill histogram: %u %-4s" SIZE_FORMAT_W(5), id, space_names[id], region_cnt);
2439 for (size_t i = 0; i < histo_len; ++i) {
2440 out->print(" " SIZE_FORMAT_W(5) " %5.1f%%",
2441 histo[i], 100.0 * histo[i] / region_cnt);
2442 }
2443 out->cr();
2444 }
2445 }
2446}
2447#endif // #ifdef ASSERT
2448
2449void PSParallelCompact::compact() {
2450 GCTraceTime(Info, gc, phases) tm("Compaction Phase", &_gc_timer);
2451
2452 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
2453 PSOldGen* old_gen = heap->old_gen();
2454 old_gen->start_array()->reset();
2455 uint parallel_gc_threads = heap->gc_task_manager()->workers();
2456 uint active_gc_threads = heap->gc_task_manager()->active_workers();
2457 TaskQueueSetSuper* qset = ParCompactionManager::region_array();
2458 TaskTerminator terminator(active_gc_threads, qset);
2459
2460 GCTaskQueue* q = GCTaskQueue::create();
2461 prepare_region_draining_tasks(q, active_gc_threads);
2462 enqueue_dense_prefix_tasks(q, active_gc_threads);
2463 enqueue_region_stealing_tasks(q, terminator.terminator(), active_gc_threads);
2464
2465 {
2466 GCTraceTime(Trace, gc, phases) tm("Par Compact", &_gc_timer);
2467
2468 gc_task_manager()->execute_and_wait(q);
2469
2470#ifdef ASSERT
2471 // Verify that all regions have been processed before the deferred updates.
2472 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2473 verify_complete(SpaceId(id));
2474 }
2475#endif
2476 }
2477
2478 {
2479 // Update the deferred objects, if any. Any compaction manager can be used.
2480 GCTraceTime(Trace, gc, phases) tm("Deferred Updates", &_gc_timer);
2481 ParCompactionManager* cm = ParCompactionManager::manager_array(0);
2482 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2483 update_deferred_objects(cm, SpaceId(id));
2484 }
2485 }
2486
2487 DEBUG_ONLY(write_block_fill_histogram());
2488}
2489
2490#ifdef ASSERT
2491void PSParallelCompact::verify_complete(SpaceId space_id) {
2492 // All Regions between space bottom() to new_top() should be marked as filled
2493 // and all Regions between new_top() and top() should be available (i.e.,
2494 // should have been emptied).
2495 ParallelCompactData& sd = summary_data();
2496 SpaceInfo si = _space_info[space_id];
2497 HeapWord* new_top_addr = sd.region_align_up(si.new_top());
2498 HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
2499 const size_t beg_region = sd.addr_to_region_idx(si.space()->bottom());
2500 const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
2501 const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
2502
2503 bool issued_a_warning = false;
2504
2505 size_t cur_region;
2506 for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
2507 const RegionData* const c = sd.region(cur_region);
2508 if (!c->completed()) {
2509 log_warning(gc)("region " SIZE_FORMAT " not filled: destination_count=%u",
2510 cur_region, c->destination_count());
2511 issued_a_warning = true;
2512 }
2513 }
2514
2515 for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
2516 const RegionData* const c = sd.region(cur_region);
2517 if (!c->available()) {
2518 log_warning(gc)("region " SIZE_FORMAT " not empty: destination_count=%u",
2519 cur_region, c->destination_count());
2520 issued_a_warning = true;
2521 }
2522 }
2523
2524 if (issued_a_warning) {
2525 print_region_ranges();
2526 }
2527}
2528#endif // #ifdef ASSERT
2529
2530inline void UpdateOnlyClosure::do_addr(HeapWord* addr) {
2531 _start_array->allocate_block(addr);
2532 compaction_manager()->update_contents(oop(addr));
2533}
2534
2535// Update interior oops in the ranges of regions [beg_region, end_region).
2536void
2537PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,
2538 SpaceId space_id,
2539 size_t beg_region,
2540 size_t end_region) {
2541 ParallelCompactData& sd = summary_data();
2542 ParMarkBitMap* const mbm = mark_bitmap();
2543
2544 HeapWord* beg_addr = sd.region_to_addr(beg_region);
2545 HeapWord* const end_addr = sd.region_to_addr(end_region);
2546 assert(beg_region <= end_region, "bad region range");
2547 assert(end_addr <= dense_prefix(space_id), "not in the dense prefix");
2548
2549#ifdef ASSERT
2550 // Claim the regions to avoid triggering an assert when they are marked as
2551 // filled.
2552 for (size_t claim_region = beg_region; claim_region < end_region; ++claim_region) {
2553 assert(sd.region(claim_region)->claim_unsafe(), "claim() failed");
2554 }
2555#endif // #ifdef ASSERT
2556
2557 if (beg_addr != space(space_id)->bottom()) {
2558 // Find the first live object or block of dead space that *starts* in this
2559 // range of regions. If a partial object crosses onto the region, skip it;
2560 // it will be marked for 'deferred update' when the object head is
2561 // processed. If dead space crosses onto the region, it is also skipped; it
2562 // will be filled when the prior region is processed. If neither of those
2563 // apply, the first word in the region is the start of a live object or dead
2564 // space.
2565 assert(beg_addr > space(space_id)->bottom(), "sanity");
2566 const RegionData* const cp = sd.region(beg_region);
2567 if (cp->partial_obj_size() != 0) {
2568 beg_addr = sd.partial_obj_end(beg_region);
2569 } else if (dead_space_crosses_boundary(cp, mbm->addr_to_bit(beg_addr))) {
2570 beg_addr = mbm->find_obj_beg(beg_addr, end_addr);
2571 }
2572 }
2573
2574 if (beg_addr < end_addr) {
2575 // A live object or block of dead space starts in this range of Regions.
2576 HeapWord* const dense_prefix_end = dense_prefix(space_id);
2577
2578 // Create closures and iterate.
2579 UpdateOnlyClosure update_closure(mbm, cm, space_id);
2580 FillClosure fill_closure(cm, space_id);
2581 ParMarkBitMap::IterationStatus status;
2582 status = mbm->iterate(&update_closure, &fill_closure, beg_addr, end_addr,
2583 dense_prefix_end);
2584 if (status == ParMarkBitMap::incomplete) {
2585 update_closure.do_addr(update_closure.source());
2586 }
2587 }
2588
2589 // Mark the regions as filled.
2590 RegionData* const beg_cp = sd.region(beg_region);
2591 RegionData* const end_cp = sd.region(end_region);
2592 for (RegionData* cp = beg_cp; cp < end_cp; ++cp) {
2593 cp->set_completed();
2594 }
2595}
2596
2597// Return the SpaceId for the space containing addr. If addr is not in the
2598// heap, last_space_id is returned. In debug mode it expects the address to be
2599// in the heap and asserts such.
2600PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
2601 assert(ParallelScavengeHeap::heap()->is_in_reserved(addr), "addr not in the heap");
2602
2603 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2604 if (_space_info[id].space()->contains(addr)) {
2605 return SpaceId(id);
2606 }
2607 }
2608
2609 assert(false, "no space contains the addr");
2610 return last_space_id;
2611}
2612
2613void PSParallelCompact::update_deferred_objects(ParCompactionManager* cm,
2614 SpaceId id) {
2615 assert(id < last_space_id, "bad space id");
2616
2617 ParallelCompactData& sd = summary_data();
2618 const SpaceInfo* const space_info = _space_info + id;
2619 ObjectStartArray* const start_array = space_info->start_array();
2620
2621 const MutableSpace* const space = space_info->space();
2622 assert(space_info->dense_prefix() >= space->bottom(), "dense_prefix not set");
2623 HeapWord* const beg_addr = space_info->dense_prefix();
2624 HeapWord* const end_addr = sd.region_align_up(space_info->new_top());
2625
2626 const RegionData* const beg_region = sd.addr_to_region_ptr(beg_addr);
2627 const RegionData* const end_region = sd.addr_to_region_ptr(end_addr);
2628 const RegionData* cur_region;
2629 for (cur_region = beg_region; cur_region < end_region; ++cur_region) {
2630 HeapWord* const addr = cur_region->deferred_obj_addr();
2631 if (addr != NULL) {
2632 if (start_array != NULL) {
2633 start_array->allocate_block(addr);
2634 }
2635 cm->update_contents(oop(addr));
2636 assert(oopDesc::is_oop_or_null(oop(addr)), "Expected an oop or NULL at " PTR_FORMAT, p2i(oop(addr)));
2637 }
2638 }
2639}
2640
2641// Skip over count live words starting from beg, and return the address of the
2642// next live word. Unless marked, the word corresponding to beg is assumed to
2643// be dead. Callers must either ensure beg does not correspond to the middle of
2644// an object, or account for those live words in some other way. Callers must
2645// also ensure that there are enough live words in the range [beg, end) to skip.
2646HeapWord*
2647PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
2648{
2649 assert(count > 0, "sanity");
2650
2651 ParMarkBitMap* m = mark_bitmap();
2652 idx_t bits_to_skip = m->words_to_bits(count);
2653 idx_t cur_beg = m->addr_to_bit(beg);
2654 const idx_t search_end = BitMap::word_align_up(m->addr_to_bit(end));
2655
2656 do {
2657 cur_beg = m->find_obj_beg(cur_beg, search_end);
2658 idx_t cur_end = m->find_obj_end(cur_beg, search_end);
2659 const size_t obj_bits = cur_end - cur_beg + 1;
2660 if (obj_bits > bits_to_skip) {
2661 return m->bit_to_addr(cur_beg + bits_to_skip);
2662 }
2663 bits_to_skip -= obj_bits;
2664 cur_beg = cur_end + 1;
2665 } while (bits_to_skip > 0);
2666
2667 // Skipping the desired number of words landed just past the end of an object.
2668 // Find the start of the next object.
2669 cur_beg = m->find_obj_beg(cur_beg, search_end);
2670 assert(cur_beg < m->addr_to_bit(end), "not enough live words to skip");
2671 return m->bit_to_addr(cur_beg);
2672}
2673
2674HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
2675 SpaceId src_space_id,
2676 size_t src_region_idx)
2677{
2678 assert(summary_data().is_region_aligned(dest_addr), "not aligned");
2679
2680 const SplitInfo& split_info = _space_info[src_space_id].split_info();
2681 if (split_info.dest_region_addr() == dest_addr) {
2682 // The partial object ending at the split point contains the first word to
2683 // be copied to dest_addr.
2684 return split_info.first_src_addr();
2685 }
2686
2687 const ParallelCompactData& sd = summary_data();
2688 ParMarkBitMap* const bitmap = mark_bitmap();
2689 const size_t RegionSize = ParallelCompactData::RegionSize;
2690
2691 assert(sd.is_region_aligned(dest_addr), "not aligned");
2692 const RegionData* const src_region_ptr = sd.region(src_region_idx);
2693 const size_t partial_obj_size = src_region_ptr->partial_obj_size();
2694 HeapWord* const src_region_destination = src_region_ptr->destination();
2695
2696 assert(dest_addr >= src_region_destination, "wrong src region");
2697 assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
2698
2699 HeapWord* const src_region_beg = sd.region_to_addr(src_region_idx);
2700 HeapWord* const src_region_end = src_region_beg + RegionSize;
2701
2702 HeapWord* addr = src_region_beg;
2703 if (dest_addr == src_region_destination) {
2704 // Return the first live word in the source region.
2705 if (partial_obj_size == 0) {
2706 addr = bitmap->find_obj_beg(addr, src_region_end);
2707 assert(addr < src_region_end, "no objects start in src region");
2708 }
2709 return addr;
2710 }
2711
2712 // Must skip some live data.
2713 size_t words_to_skip = dest_addr - src_region_destination;
2714 assert(src_region_ptr->data_size() > words_to_skip, "wrong src region");
2715
2716 if (partial_obj_size >= words_to_skip) {
2717 // All the live words to skip are part of the partial object.
2718 addr += words_to_skip;
2719 if (partial_obj_size == words_to_skip) {
2720 // Find the first live word past the partial object.
2721 addr = bitmap->find_obj_beg(addr, src_region_end);
2722 assert(addr < src_region_end, "wrong src region");
2723 }
2724 return addr;
2725 }
2726
2727 // Skip over the partial object (if any).
2728 if (partial_obj_size != 0) {
2729 words_to_skip -= partial_obj_size;
2730 addr += partial_obj_size;
2731 }
2732
2733 // Skip over live words due to objects that start in the region.
2734 addr = skip_live_words(addr, src_region_end, words_to_skip);
2735 assert(addr < src_region_end, "wrong src region");
2736 return addr;
2737}
2738
2739void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
2740 SpaceId src_space_id,
2741 size_t beg_region,
2742 HeapWord* end_addr)
2743{
2744 ParallelCompactData& sd = summary_data();
2745
2746#ifdef ASSERT
2747 MutableSpace* const src_space = _space_info[src_space_id].space();
2748 HeapWord* const beg_addr = sd.region_to_addr(beg_region);
2749 assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
2750 "src_space_id does not match beg_addr");
2751 assert(src_space->contains(end_addr) || end_addr == src_space->end(),
2752 "src_space_id does not match end_addr");
2753#endif // #ifdef ASSERT
2754
2755 RegionData* const beg = sd.region(beg_region);
2756 RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));
2757
2758 // Regions up to new_top() are enqueued if they become available.
2759 HeapWord* const new_top = _space_info[src_space_id].new_top();
2760 RegionData* const enqueue_end =
2761 sd.addr_to_region_ptr(sd.region_align_up(new_top));
2762
2763 for (RegionData* cur = beg; cur < end; ++cur) {
2764 assert(cur->data_size() > 0, "region must have live data");
2765 cur->decrement_destination_count();
2766 if (cur < enqueue_end && cur->available() && cur->claim()) {
2767 cm->push_region(sd.region(cur));
2768 }
2769 }
2770}
2771
2772size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
2773 SpaceId& src_space_id,
2774 HeapWord*& src_space_top,
2775 HeapWord* end_addr)
2776{
2777 typedef ParallelCompactData::RegionData RegionData;
2778
2779 ParallelCompactData& sd = PSParallelCompact::summary_data();
2780 const size_t region_size = ParallelCompactData::RegionSize;
2781
2782 size_t src_region_idx = 0;
2783
2784 // Skip empty regions (if any) up to the top of the space.
2785 HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
2786 RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
2787 HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
2788 const RegionData* const top_region_ptr =
2789 sd.addr_to_region_ptr(top_aligned_up);
2790 while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
2791 ++src_region_ptr;
2792 }
2793
2794 if (src_region_ptr < top_region_ptr) {
2795 // The next source region is in the current space. Update src_region_idx
2796 // and the source address to match src_region_ptr.
2797 src_region_idx = sd.region(src_region_ptr);
2798 HeapWord* const src_region_addr = sd.region_to_addr(src_region_idx);
2799 if (src_region_addr > closure.source()) {
2800 closure.set_source(src_region_addr);
2801 }
2802 return src_region_idx;
2803 }
2804
2805 // Switch to a new source space and find the first non-empty region.
2806 unsigned int space_id = src_space_id + 1;
2807 assert(space_id < last_space_id, "not enough spaces");
2808
2809 HeapWord* const destination = closure.destination();
2810
2811 do {
2812 MutableSpace* space = _space_info[space_id].space();
2813 HeapWord* const bottom = space->bottom();
2814 const RegionData* const bottom_cp = sd.addr_to_region_ptr(bottom);
2815
2816 // Iterate over the spaces that do not compact into themselves.
2817 if (bottom_cp->destination() != bottom) {
2818 HeapWord* const top_aligned_up = sd.region_align_up(space->top());
2819 const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
2820
2821 for (const RegionData* src_cp = bottom_cp; src_cp < top_cp; ++src_cp) {
2822 if (src_cp->live_obj_size() > 0) {
2823 // Found it.
2824 assert(src_cp->destination() == destination,
2825 "first live obj in the space must match the destination");
2826 assert(src_cp->partial_obj_size() == 0,
2827 "a space cannot begin with a partial obj");
2828
2829 src_space_id = SpaceId(space_id);
2830 src_space_top = space->top();
2831 const size_t src_region_idx = sd.region(src_cp);
2832 closure.set_source(sd.region_to_addr(src_region_idx));
2833 return src_region_idx;
2834 } else {
2835 assert(src_cp->data_size() == 0, "sanity");
2836 }
2837 }
2838 }
2839 } while (++space_id < last_space_id);
2840
2841 assert(false, "no source region was found");
2842 return 0;
2843}
2844
2845void PSParallelCompact::fill_region(ParCompactionManager* cm, size_t region_idx)
2846{
2847 typedef ParMarkBitMap::IterationStatus IterationStatus;
2848 const size_t RegionSize = ParallelCompactData::RegionSize;
2849 ParMarkBitMap* const bitmap = mark_bitmap();
2850 ParallelCompactData& sd = summary_data();
2851 RegionData* const region_ptr = sd.region(region_idx);
2852
2853 // Get the items needed to construct the closure.
2854 HeapWord* dest_addr = sd.region_to_addr(region_idx);
2855 SpaceId dest_space_id = space_id(dest_addr);
2856 ObjectStartArray* start_array = _space_info[dest_space_id].start_array();
2857 HeapWord* new_top = _space_info[dest_space_id].new_top();
2858 assert(dest_addr < new_top, "sanity");
2859 const size_t words = MIN2(pointer_delta(new_top, dest_addr), RegionSize);
2860
2861 // Get the source region and related info.
2862 size_t src_region_idx = region_ptr->source_region();
2863 SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
2864 HeapWord* src_space_top = _space_info[src_space_id].space()->top();
2865
2866 MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);
2867 closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
2868
2869 // Adjust src_region_idx to prepare for decrementing destination counts (the
2870 // destination count is not decremented when a region is copied to itself).
2871 if (src_region_idx == region_idx) {
2872 src_region_idx += 1;
2873 }
2874
2875 if (bitmap->is_unmarked(closure.source())) {
2876 // The first source word is in the middle of an object; copy the remainder
2877 // of the object or as much as will fit. The fact that pointer updates were
2878 // deferred will be noted when the object header is processed.
2879 HeapWord* const old_src_addr = closure.source();
2880 closure.copy_partial_obj();
2881 if (closure.is_full()) {
2882 decrement_destination_counts(cm, src_space_id, src_region_idx,
2883 closure.source());
2884 region_ptr->set_deferred_obj_addr(NULL);
2885 region_ptr->set_completed();
2886 return;
2887 }
2888
2889 HeapWord* const end_addr = sd.region_align_down(closure.source());
2890 if (sd.region_align_down(old_src_addr) != end_addr) {
2891 // The partial object was copied from more than one source region.
2892 decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2893
2894 // Move to the next source region, possibly switching spaces as well. All
2895 // args except end_addr may be modified.
2896 src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2897 end_addr);
2898 }
2899 }
2900
2901 do {
2902 HeapWord* const cur_addr = closure.source();
2903 HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
2904 src_space_top);
2905 IterationStatus status = bitmap->iterate(&closure, cur_addr, end_addr);
2906
2907 if (status == ParMarkBitMap::incomplete) {
2908 // The last obj that starts in the source region does not end in the
2909 // region.
2910 assert(closure.source() < end_addr, "sanity");
2911 HeapWord* const obj_beg = closure.source();
2912 HeapWord* const range_end = MIN2(obj_beg + closure.words_remaining(),
2913 src_space_top);
2914 HeapWord* const obj_end = bitmap->find_obj_end(obj_beg, range_end);
2915 if (obj_end < range_end) {
2916 // The end was found; the entire object will fit.
2917 status = closure.do_addr(obj_beg, bitmap->obj_size(obj_beg, obj_end));
2918 assert(status != ParMarkBitMap::would_overflow, "sanity");
2919 } else {
2920 // The end was not found; the object will not fit.
2921 assert(range_end < src_space_top, "obj cannot cross space boundary");
2922 status = ParMarkBitMap::would_overflow;
2923 }
2924 }
2925
2926 if (status == ParMarkBitMap::would_overflow) {
2927 // The last object did not fit. Note that interior oop updates were
2928 // deferred, then copy enough of the object to fill the region.
2929 region_ptr->set_deferred_obj_addr(closure.destination());
2930 status = closure.copy_until_full(); // copies from closure.source()
2931
2932 decrement_destination_counts(cm, src_space_id, src_region_idx,
2933 closure.source());
2934 region_ptr->set_completed();
2935 return;
2936 }
2937
2938 if (status == ParMarkBitMap::full) {
2939 decrement_destination_counts(cm, src_space_id, src_region_idx,
2940 closure.source());
2941 region_ptr->set_deferred_obj_addr(NULL);
2942 region_ptr->set_completed();
2943 return;
2944 }
2945
2946 decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2947
2948 // Move to the next source region, possibly switching spaces as well. All
2949 // args except end_addr may be modified.
2950 src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2951 end_addr);
2952 } while (true);
2953}
2954
2955void PSParallelCompact::fill_blocks(size_t region_idx)
2956{
2957 // Fill in the block table elements for the specified region. Each block
2958 // table element holds the number of live words in the region that are to the
2959 // left of the first object that starts in the block. Thus only blocks in
2960 // which an object starts need to be filled.
2961 //
2962 // The algorithm scans the section of the bitmap that corresponds to the
2963 // region, keeping a running total of the live words. When an object start is
2964 // found, if it's the first to start in the block that contains it, the
2965 // current total is written to the block table element.
2966 const size_t Log2BlockSize = ParallelCompactData::Log2BlockSize;
2967 const size_t Log2RegionSize = ParallelCompactData::Log2RegionSize;
2968 const size_t RegionSize = ParallelCompactData::RegionSize;
2969
2970 ParallelCompactData& sd = summary_data();
2971 const size_t partial_obj_size = sd.region(region_idx)->partial_obj_size();
2972 if (partial_obj_size >= RegionSize) {
2973 return; // No objects start in this region.
2974 }
2975
2976 // Ensure the first loop iteration decides that the block has changed.
2977 size_t cur_block = sd.block_count();
2978
2979 const ParMarkBitMap* const bitmap = mark_bitmap();
2980
2981 const size_t Log2BitsPerBlock = Log2BlockSize - LogMinObjAlignment;
2982 assert((size_t)1 << Log2BitsPerBlock ==
2983 bitmap->words_to_bits(ParallelCompactData::BlockSize), "sanity");
2984
2985 size_t beg_bit = bitmap->words_to_bits(region_idx << Log2RegionSize);
2986 const size_t range_end = beg_bit + bitmap->words_to_bits(RegionSize);
2987 size_t live_bits = bitmap->words_to_bits(partial_obj_size);
2988 beg_bit = bitmap->find_obj_beg(beg_bit + live_bits, range_end);
2989 while (beg_bit < range_end) {
2990 const size_t new_block = beg_bit >> Log2BitsPerBlock;
2991 if (new_block != cur_block) {
2992 cur_block = new_block;
2993 sd.block(cur_block)->set_offset(bitmap->bits_to_words(live_bits));
2994 }
2995
2996 const size_t end_bit = bitmap->find_obj_end(beg_bit, range_end);
2997 if (end_bit < range_end - 1) {
2998 live_bits += end_bit - beg_bit + 1;
2999 beg_bit = bitmap->find_obj_beg(end_bit + 1, range_end);
3000 } else {
3001 return;
3002 }
3003 }
3004}
3005
3006void
3007PSParallelCompact::move_and_update(ParCompactionManager* cm, SpaceId space_id) {
3008 const MutableSpace* sp = space(space_id);
3009 if (sp->is_empty()) {
3010 return;
3011 }
3012
3013 ParallelCompactData& sd = PSParallelCompact::summary_data();
3014 ParMarkBitMap* const bitmap = mark_bitmap();
3015 HeapWord* const dp_addr = dense_prefix(space_id);
3016 HeapWord* beg_addr = sp->bottom();
3017 HeapWord* end_addr = sp->top();
3018
3019 assert(beg_addr <= dp_addr && dp_addr <= end_addr, "bad dense prefix");
3020
3021 const size_t beg_region = sd.addr_to_region_idx(beg_addr);
3022 const size_t dp_region = sd.addr_to_region_idx(dp_addr);
3023 if (beg_region < dp_region) {
3024 update_and_deadwood_in_dense_prefix(cm, space_id, beg_region, dp_region);
3025 }
3026
3027 // The destination of the first live object that starts in the region is one
3028 // past the end of the partial object entering the region (if any).
3029 HeapWord* const dest_addr = sd.partial_obj_end(dp_region);
3030 HeapWord* const new_top = _space_info[space_id].new_top();
3031 assert(new_top >= dest_addr, "bad new_top value");
3032 const size_t words = pointer_delta(new_top, dest_addr);
3033
3034 if (words > 0) {
3035 ObjectStartArray* start_array = _space_info[space_id].start_array();
3036 MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);
3037
3038 ParMarkBitMap::IterationStatus status;
3039 status = bitmap->iterate(&closure, dest_addr, end_addr);
3040 assert(status == ParMarkBitMap::full, "iteration not complete");
3041 assert(bitmap->find_obj_beg(closure.source(), end_addr) == end_addr,
3042 "live objects skipped because closure is full");
3043 }
3044}
3045
3046jlong PSParallelCompact::millis_since_last_gc() {
3047 // We need a monotonically non-decreasing time in ms but
3048 // os::javaTimeMillis() does not guarantee monotonicity.
3049 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
3050 jlong ret_val = now - _time_of_last_gc;
3051 // XXX See note in genCollectedHeap::millis_since_last_gc().
3052 if (ret_val < 0) {
3053 NOT_PRODUCT(log_warning(gc)("time warp: " JLONG_FORMAT, ret_val);)
3054 return 0;
3055 }
3056 return ret_val;
3057}
3058
3059void PSParallelCompact::reset_millis_since_last_gc() {
3060 // We need a monotonically non-decreasing time in ms but
3061 // os::javaTimeMillis() does not guarantee monotonicity.
3062 _time_of_last_gc = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
3063}
3064
3065ParMarkBitMap::IterationStatus MoveAndUpdateClosure::copy_until_full()
3066{
3067 if (source() != destination()) {
3068 DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3069 Copy::aligned_conjoint_words(source(), destination(), words_remaining());
3070 }
3071 update_state(words_remaining());
3072 assert(is_full(), "sanity");
3073 return ParMarkBitMap::full;
3074}
3075
3076void MoveAndUpdateClosure::copy_partial_obj()
3077{
3078 size_t words = words_remaining();
3079
3080 HeapWord* const range_end = MIN2(source() + words, bitmap()->region_end());
3081 HeapWord* const end_addr = bitmap()->find_obj_end(source(), range_end);
3082 if (end_addr < range_end) {
3083 words = bitmap()->obj_size(source(), end_addr);
3084 }
3085
3086 // This test is necessary; if omitted, the pointer updates to a partial object
3087 // that crosses the dense prefix boundary could be overwritten.
3088 if (source() != destination()) {
3089 DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3090 Copy::aligned_conjoint_words(source(), destination(), words);
3091 }
3092 update_state(words);
3093}
3094
3095ParMarkBitMapClosure::IterationStatus
3096MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
3097 assert(destination() != NULL, "sanity");
3098 assert(bitmap()->obj_size(addr) == words, "bad size");
3099
3100 _source = addr;
3101 assert(PSParallelCompact::summary_data().calc_new_pointer(source(), compaction_manager()) ==
3102 destination(), "wrong destination");
3103
3104 if (words > words_remaining()) {
3105 return ParMarkBitMap::would_overflow;
3106 }
3107
3108 // The start_array must be updated even if the object is not moving.
3109 if (_start_array != NULL) {
3110 _start_array->allocate_block(destination());
3111 }
3112
3113 if (destination() != source()) {
3114 DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3115 Copy::aligned_conjoint_words(source(), destination(), words);
3116 }
3117
3118 oop moved_oop = (oop) destination();
3119 compaction_manager()->update_contents(moved_oop);
3120 assert(oopDesc::is_oop_or_null(moved_oop), "Expected an oop or NULL at " PTR_FORMAT, p2i(moved_oop));
3121
3122 update_state(words);
3123 assert(destination() == (HeapWord*)moved_oop + moved_oop->size(), "sanity");
3124 return is_full() ? ParMarkBitMap::full : ParMarkBitMap::incomplete;
3125}
3126
3127UpdateOnlyClosure::UpdateOnlyClosure(ParMarkBitMap* mbm,
3128 ParCompactionManager* cm,
3129 PSParallelCompact::SpaceId space_id) :
3130 ParMarkBitMapClosure(mbm, cm),
3131 _space_id(space_id),
3132 _start_array(PSParallelCompact::start_array(space_id))
3133{
3134}
3135
3136// Updates the references in the object to their new values.
3137ParMarkBitMapClosure::IterationStatus
3138UpdateOnlyClosure::do_addr(HeapWord* addr, size_t words) {
3139 do_addr(addr);
3140 return ParMarkBitMap::incomplete;
3141}
3142
3143FillClosure::FillClosure(ParCompactionManager* cm, PSParallelCompact::SpaceId space_id) :
3144 ParMarkBitMapClosure(PSParallelCompact::mark_bitmap(), cm),
3145 _start_array(PSParallelCompact::start_array(space_id))
3146{
3147 assert(space_id == PSParallelCompact::old_space_id,
3148 "cannot use FillClosure in the young gen");
3149}
3150
3151ParMarkBitMapClosure::IterationStatus
3152FillClosure::do_addr(HeapWord* addr, size_t size) {
3153 CollectedHeap::fill_with_objects(addr, size);
3154 HeapWord* const end = addr + size;
3155 do {
3156 _start_array->allocate_block(addr);
3157 addr += oop(addr)->size();
3158 } while (addr < end);
3159 return ParMarkBitMap::incomplete;
3160}
3161