1 /*
2 * Copyright (c) 2005, 2026, 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 "classfile/classLoaderDataGraph.hpp"
26 #include "classfile/javaClasses.inline.hpp"
27 #include "classfile/stringTable.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "classfile/systemDictionary.hpp"
30 #include "code/codeCache.hpp"
31 #include "code/nmethod.hpp"
32 #include "compiler/oopMap.hpp"
33 #include "cppstdlib/new.hpp"
34 #include "gc/parallel/objectStartArray.inline.hpp"
35 #include "gc/parallel/parallelArguments.hpp"
36 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
37 #include "gc/parallel/parMarkBitMap.inline.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/psRootType.hpp"
44 #include "gc/parallel/psScavenge.hpp"
45 #include "gc/parallel/psStringDedup.hpp"
46 #include "gc/parallel/psYoungGen.hpp"
47 #include "gc/shared/classUnloadingContext.hpp"
48 #include "gc/shared/collectedHeap.inline.hpp"
49 #include "gc/shared/fullGCForwarding.inline.hpp"
50 #include "gc/shared/gcCause.hpp"
51 #include "gc/shared/gcHeapSummary.hpp"
52 #include "gc/shared/gcId.hpp"
53 #include "gc/shared/gcLocker.hpp"
54 #include "gc/shared/gcTimer.hpp"
55 #include "gc/shared/gcTrace.hpp"
56 #include "gc/shared/gcTraceTime.inline.hpp"
57 #include "gc/shared/gcVMOperations.hpp"
58 #include "gc/shared/isGCActiveMark.hpp"
59 #include "gc/shared/oopStorage.inline.hpp"
60 #include "gc/shared/oopStorageSet.inline.hpp"
61 #include "gc/shared/oopStorageSetParState.inline.hpp"
62 #include "gc/shared/parallelCleaning.hpp"
63 #include "gc/shared/preservedMarks.inline.hpp"
64 #include "gc/shared/referencePolicy.hpp"
65 #include "gc/shared/referenceProcessor.hpp"
66 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
67 #include "gc/shared/spaceDecorator.hpp"
68 #include "gc/shared/taskTerminator.hpp"
69 #include "gc/shared/weakProcessor.inline.hpp"
70 #include "gc/shared/workerPolicy.hpp"
71 #include "gc/shared/workerThread.hpp"
72 #include "gc/shared/workerUtils.hpp"
73 #include "logging/log.hpp"
74 #include "memory/iterator.inline.hpp"
75 #include "memory/memoryReserver.hpp"
76 #include "memory/metaspaceUtils.hpp"
77 #include "memory/resourceArea.hpp"
78 #include "memory/universe.hpp"
79 #include "nmt/memTracker.hpp"
80 #include "oops/access.inline.hpp"
81 #include "oops/instanceClassLoaderKlass.inline.hpp"
82 #include "oops/instanceKlass.inline.hpp"
83 #include "oops/instanceMirrorKlass.inline.hpp"
84 #include "oops/methodData.hpp"
85 #include "oops/objArrayKlass.inline.hpp"
86 #include "oops/oop.inline.hpp"
87 #include "runtime/handles.inline.hpp"
88 #include "runtime/java.hpp"
89 #include "runtime/safepoint.hpp"
90 #include "runtime/threads.hpp"
91 #include "runtime/vmThread.hpp"
92 #include "services/memoryService.hpp"
93 #include "utilities/align.hpp"
94 #include "utilities/debug.hpp"
95 #include "utilities/events.hpp"
96 #include "utilities/formatBuffer.hpp"
97 #include "utilities/macros.hpp"
98 #include "utilities/stack.inline.hpp"
99 #if INCLUDE_JVMCI
100 #include "jvmci/jvmci.hpp"
101 #endif
102
103 #include <math.h>
104
105 // All sizes are in HeapWords.
106 const size_t ParallelCompactData::Log2RegionSize = 16; // 64K words
107 const size_t ParallelCompactData::RegionSize = (size_t)1 << Log2RegionSize;
108 static_assert(ParallelCompactData::RegionSize >= BitsPerWord, "region-start bit word-aligned");
109 const size_t ParallelCompactData::RegionSizeBytes =
110 RegionSize << LogHeapWordSize;
111 const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
112 const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
113 const size_t ParallelCompactData::RegionAddrMask = ~RegionAddrOffsetMask;
114
115 const ParallelCompactData::RegionData::region_sz_t
116 ParallelCompactData::RegionData::dc_shift = 27;
117
118 const ParallelCompactData::RegionData::region_sz_t
119 ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
120
121 const ParallelCompactData::RegionData::region_sz_t
122 ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
123
124 const ParallelCompactData::RegionData::region_sz_t
125 ParallelCompactData::RegionData::los_mask = ~dc_mask;
126
127 const ParallelCompactData::RegionData::region_sz_t
128 ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
129
130 const ParallelCompactData::RegionData::region_sz_t
131 ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
132
133 bool ParallelCompactData::RegionData::is_clear() {
134 return (_destination == nullptr) &&
135 (_source_region == 0) &&
136 (_partial_obj_addr == nullptr) &&
137 (_partial_obj_size == 0) &&
138 (dc_and_los() == 0) &&
139 (shadow_state() == 0);
140 }
141
142 #ifdef ASSERT
143 void ParallelCompactData::RegionData::verify_clear() {
144 assert(_destination == nullptr, "inv");
145 assert(_source_region == 0, "inv");
146 assert(_partial_obj_addr == nullptr, "inv");
147 assert(_partial_obj_size == 0, "inv");
148 assert(dc_and_los() == 0, "inv");
149 assert(shadow_state() == 0, "inv");
150 }
151 #endif
152
153 SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
154
155 SpanSubjectToDiscoveryClosure PSParallelCompact::_span_based_discoverer;
156 ReferenceProcessor* PSParallelCompact::_ref_processor = nullptr;
157
158 void SplitInfo::record(size_t split_region_idx, HeapWord* split_point, size_t preceding_live_words) {
159 assert(split_region_idx != 0, "precondition");
160
161 // Obj denoted by split_point will be deferred to the next space.
162 assert(split_point != nullptr, "precondition");
163
164 const ParallelCompactData& sd = PSParallelCompact::summary_data();
165
166 PSParallelCompact::RegionData* split_region_ptr = sd.region(split_region_idx);
167 assert(preceding_live_words < split_region_ptr->data_size(), "inv");
168
169 HeapWord* preceding_destination = split_region_ptr->destination();
170 assert(preceding_destination != nullptr, "inv");
171
172 // How many regions does the preceding part occupy
173 uint preceding_destination_count;
174 if (preceding_live_words == 0) {
175 preceding_destination_count = 0;
176 } else {
177 // -1 so that the ending address doesn't fall on the region-boundary
178 if (sd.region_align_down(preceding_destination) ==
179 sd.region_align_down(preceding_destination + preceding_live_words - 1)) {
180 preceding_destination_count = 1;
181 } else {
182 preceding_destination_count = 2;
183 }
184 }
185
186 _split_region_idx = split_region_idx;
187 _split_point = split_point;
188 _preceding_live_words = preceding_live_words;
189 _preceding_destination = preceding_destination;
190 _preceding_destination_count = preceding_destination_count;
191 }
192
193 void SplitInfo::clear()
194 {
195 _split_region_idx = 0;
196 _split_point = nullptr;
197 _preceding_live_words = 0;
198 _preceding_destination = nullptr;
199 _preceding_destination_count = 0;
200 assert(!is_valid(), "sanity");
201 }
202
203 #ifdef ASSERT
204 void SplitInfo::verify_clear()
205 {
206 assert(_split_region_idx == 0, "not clear");
207 assert(_split_point == nullptr, "not clear");
208 assert(_preceding_live_words == 0, "not clear");
209 assert(_preceding_destination == nullptr, "not clear");
210 assert(_preceding_destination_count == 0, "not clear");
211 }
212 #endif // #ifdef ASSERT
213
214
215 void PSParallelCompact::print_on(outputStream* st) {
216 _mark_bitmap.print_on(st);
217 }
218
219 ParallelCompactData::ParallelCompactData() :
220 _heap_start(nullptr),
221 DEBUG_ONLY(_heap_end(nullptr) COMMA)
222 _region_vspace(nullptr),
223 _reserved_byte_size(0),
224 _region_data(nullptr),
225 _region_count(0) {}
226
227 bool ParallelCompactData::initialize(MemRegion reserved_heap)
228 {
229 _heap_start = reserved_heap.start();
230 const size_t heap_size = reserved_heap.word_size();
231 DEBUG_ONLY(_heap_end = _heap_start + heap_size;)
232
233 assert(region_align_down(_heap_start) == _heap_start,
234 "region start not aligned");
235 assert(is_aligned(heap_size, RegionSize), "precondition");
236
237 const size_t count = heap_size >> Log2RegionSize;
238 const size_t raw_bytes = count * sizeof(RegionData);
239 const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);
240 const size_t granularity = os::vm_allocation_granularity();
241 const size_t rs_align = MAX2(page_sz, granularity);
242
243 _reserved_byte_size = align_up(raw_bytes, rs_align);
244
245 ReservedSpace rs = MemoryReserver::reserve(_reserved_byte_size,
246 rs_align,
247 page_sz,
248 mtGC);
249
250 if (!rs.is_reserved()) {
251 // Failed to reserve memory.
252 return false;
253 }
254
255 os::trace_page_sizes("Parallel Compact Data", raw_bytes, raw_bytes, rs.base(),
256 rs.size(), page_sz);
257
258 MemTracker::record_virtual_memory_tag(rs, mtGC);
259
260 PSVirtualSpace* region_vspace = new PSVirtualSpace(rs, page_sz);
261
262 if (!region_vspace->expand_by(_reserved_byte_size)) {
263 // Failed to commit memory.
264
265 delete region_vspace;
266
267 // Release memory reserved in the space.
268 MemoryReserver::release(rs);
269
270 return false;
271 }
272
273 _region_vspace = region_vspace;
274 _region_data = (RegionData*)_region_vspace->reserved_low_addr();
275 _region_count = count;
276 return true;
277 }
278
279 void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
280 assert(beg_region <= _region_count, "beg_region out of range");
281 assert(end_region <= _region_count, "end_region out of range");
282
283 const size_t region_cnt = end_region - beg_region;
284 for (size_t i = beg_region; i < end_region; i++) {
285 ::new (&_region_data[i]) RegionData{};
286 }
287 }
288
289 // The total live words on src_region would overflow the target space, so find
290 // the overflowing object and record the split point. The invariant is that an
291 // obj should not cross space boundary.
292 HeapWord* ParallelCompactData::summarize_split_space(size_t src_region,
293 SplitInfo& split_info,
294 HeapWord* const destination,
295 HeapWord* const target_end,
296 HeapWord** target_next) {
297 assert(destination <= target_end, "sanity");
298 assert(destination + _region_data[src_region].data_size() > target_end,
299 "region should not fit into target space");
300 assert(is_region_aligned(target_end), "sanity");
301
302 size_t partial_obj_size = _region_data[src_region].partial_obj_size();
303
304 if (destination + partial_obj_size > target_end) {
305 assert(partial_obj_size > 0, "inv");
306 // The overflowing obj is from a previous region.
307 //
308 // source-regions:
309 //
310 // ***************
311 // | A|AA |
312 // ***************
313 // ^
314 // | split-point
315 //
316 // dest-region:
317 //
318 // ********
319 // |~~~~A |
320 // ********
321 // ^^
322 // || target-space-end
323 // |
324 // | destination
325 //
326 // AAA would overflow target-space.
327 //
328 HeapWord* overflowing_obj = _region_data[src_region].partial_obj_addr();
329 size_t split_region = addr_to_region_idx(overflowing_obj);
330
331 // The number of live words before the overflowing object on this split region
332 size_t preceding_live_words;
333 if (is_region_aligned(overflowing_obj)) {
334 preceding_live_words = 0;
335 } else {
336 // Words accounted by the overflowing object on the split region
337 size_t overflowing_size = pointer_delta(region_align_up(overflowing_obj), overflowing_obj);
338 preceding_live_words = region(split_region)->data_size() - overflowing_size;
339 }
340
341 split_info.record(split_region, overflowing_obj, preceding_live_words);
342
343 // The [overflowing_obj, src_region_start) part has been accounted for, so
344 // must move back the new_top, now that this overflowing obj is deferred.
345 HeapWord* new_top = destination - pointer_delta(region_to_addr(src_region), overflowing_obj);
346
347 // If the overflowing obj was relocated to its original destination,
348 // those destination regions would have their source_region set. Now that
349 // this overflowing obj is relocated somewhere else, reset the
350 // source_region.
351 {
352 size_t range_start = addr_to_region_idx(region_align_up(new_top));
353 size_t range_end = addr_to_region_idx(region_align_up(destination));
354 for (size_t i = range_start; i < range_end; ++i) {
355 region(i)->set_source_region(0);
356 }
357 }
358
359 // Update new top of target space
360 *target_next = new_top;
361
362 return overflowing_obj;
363 }
364
365 // Obj-iteration to locate the overflowing obj
366 HeapWord* region_start = region_to_addr(src_region);
367 HeapWord* region_end = region_start + RegionSize;
368 HeapWord* cur_addr = region_start + partial_obj_size;
369 size_t live_words = partial_obj_size;
370
371 while (true) {
372 assert(cur_addr < region_end, "inv");
373 cur_addr = PSParallelCompact::mark_bitmap()->find_obj_beg(cur_addr, region_end);
374 // There must be an overflowing obj in this region
375 assert(cur_addr < region_end, "inv");
376
377 oop obj = cast_to_oop(cur_addr);
378 size_t obj_size = obj->size();
379 if (destination + live_words + obj_size > target_end) {
380 // Found the overflowing obj
381 split_info.record(src_region, cur_addr, live_words);
382 *target_next = destination + live_words;
383 return cur_addr;
384 }
385
386 live_words += obj_size;
387 cur_addr += obj_size;
388 }
389 }
390
391 size_t ParallelCompactData::live_words_in_space(const MutableSpace* space,
392 HeapWord** full_region_prefix_end) {
393 size_t cur_region = addr_to_region_idx(space->bottom());
394 const size_t end_region = addr_to_region_idx(region_align_up(space->top()));
395 size_t live_words = 0;
396 if (full_region_prefix_end == nullptr) {
397 for (/* empty */; cur_region < end_region; ++cur_region) {
398 live_words += _region_data[cur_region].data_size();
399 }
400 } else {
401 bool first_set = false;
402 for (/* empty */; cur_region < end_region; ++cur_region) {
403 size_t live_words_in_region = _region_data[cur_region].data_size();
404 if (!first_set && live_words_in_region < RegionSize) {
405 *full_region_prefix_end = region_to_addr(cur_region);
406 first_set = true;
407 }
408 live_words += live_words_in_region;
409 }
410 if (!first_set) {
411 // All regions are full of live objs.
412 assert(is_region_aligned(space->top()), "inv");
413 *full_region_prefix_end = space->top();
414 }
415 assert(*full_region_prefix_end != nullptr, "postcondition");
416 assert(is_region_aligned(*full_region_prefix_end), "inv");
417 assert(*full_region_prefix_end >= space->bottom(), "in-range");
418 assert(*full_region_prefix_end <= space->top(), "in-range");
419 }
420 return live_words;
421 }
422
423 bool ParallelCompactData::summarize(SplitInfo& split_info,
424 HeapWord* source_beg, HeapWord* source_end,
425 HeapWord** source_next,
426 HeapWord* target_beg, HeapWord* target_end,
427 HeapWord** target_next)
428 {
429 HeapWord* const source_next_val = source_next == nullptr ? nullptr : *source_next;
430 log_develop_trace(gc, compaction)(
431 "sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
432 "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
433 p2i(source_beg), p2i(source_end), p2i(source_next_val),
434 p2i(target_beg), p2i(target_end), p2i(*target_next));
435
436 size_t cur_region = addr_to_region_idx(source_beg);
437 const size_t end_region = addr_to_region_idx(region_align_up(source_end));
438
439 HeapWord *dest_addr = target_beg;
440 for (/* empty */; cur_region < end_region; cur_region++) {
441 size_t words = _region_data[cur_region].data_size();
442
443 // Skip empty ones
444 if (words == 0) {
445 continue;
446 }
447
448 if (split_info.is_split(cur_region)) {
449 assert(words > split_info.preceding_live_words(), "inv");
450 words -= split_info.preceding_live_words();
451 }
452
453 _region_data[cur_region].set_destination(dest_addr);
454
455 // If cur_region does not fit entirely into the target space, find a point
456 // at which the source space can be 'split' so that part is copied to the
457 // target space and the rest is copied elsewhere.
458 if (dest_addr + words > target_end) {
459 assert(source_next != nullptr, "source_next is null when splitting");
460 *source_next = summarize_split_space(cur_region, split_info, dest_addr,
461 target_end, target_next);
462 return false;
463 }
464
465 uint destination_count = split_info.is_split(cur_region)
466 ? split_info.preceding_destination_count()
467 : 0;
468
469 HeapWord* const last_addr = dest_addr + words - 1;
470 const size_t dest_region_1 = addr_to_region_idx(dest_addr);
471 const size_t dest_region_2 = addr_to_region_idx(last_addr);
472
473 // Initially assume that the destination regions will be the same and
474 // adjust the value below if necessary. Under this assumption, if
475 // cur_region == dest_region_2, then cur_region will be compacted
476 // completely into itself.
477 destination_count += cur_region == dest_region_2 ? 0 : 1;
478 if (dest_region_1 != dest_region_2) {
479 // Destination regions differ; adjust destination_count.
480 destination_count += 1;
481 // Data from cur_region will be copied to the start of dest_region_2.
482 _region_data[dest_region_2].set_source_region(cur_region);
483 } else if (is_region_aligned(dest_addr)) {
484 // Data from cur_region will be copied to the start of the destination
485 // region.
486 _region_data[dest_region_1].set_source_region(cur_region);
487 }
488
489 _region_data[cur_region].set_destination_count(destination_count);
490 dest_addr += words;
491 }
492
493 *target_next = dest_addr;
494 return true;
495 }
496
497 #ifdef ASSERT
498 void ParallelCompactData::verify_clear() {
499 for (uint cur_idx = 0; cur_idx < region_count(); ++cur_idx) {
500 if (!region(cur_idx)->is_clear()) {
501 log_warning(gc)("Uncleared Region: %u", cur_idx);
502 region(cur_idx)->verify_clear();
503 }
504 }
505 }
506 #endif // #ifdef ASSERT
507
508 STWGCTimer PSParallelCompact::_gc_timer;
509 ParallelOldTracer PSParallelCompact::_gc_tracer;
510 elapsedTimer PSParallelCompact::_accumulated_time;
511 unsigned int PSParallelCompact::_maximum_compaction_gc_num = 0;
512 CollectorCounters* PSParallelCompact::_counters = nullptr;
513 ParMarkBitMap PSParallelCompact::_mark_bitmap;
514 ParallelCompactData PSParallelCompact::_summary_data;
515
516 PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
517
518 class PCAdjustPointerClosure: public BasicOopIterateClosure {
519 template <typename T>
520 void do_oop_work(T* p) { PSParallelCompact::adjust_pointer(p); }
521
522 public:
523 virtual void do_oop(oop* p) { do_oop_work(p); }
524 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
525
526 virtual ReferenceIterationMode reference_iteration_mode() { return DO_FIELDS; }
527 };
528
529 static PCAdjustPointerClosure pc_adjust_pointer_closure;
530
531 bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
532
533 void PSParallelCompact::post_initialize() {
534 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
535 _span_based_discoverer.set_span(heap->reserved_region());
536 _ref_processor =
537 new ReferenceProcessor(&_span_based_discoverer,
538 ParallelGCThreads, // mt processing degree
539 ParallelGCThreads, // mt discovery degree
540 false, // concurrent_discovery
541 &_is_alive_closure); // non-header is alive closure
542
543 _counters = new CollectorCounters("Parallel full collection pauses", 1);
544
545 // Initialize static fields in ParCompactionManager.
546 ParCompactionManager::initialize(mark_bitmap());
547 }
548
549 bool PSParallelCompact::initialize_aux_data() {
550 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
551 MemRegion mr = heap->reserved_region();
552 assert(mr.byte_size() != 0, "heap should be reserved");
553
554 initialize_space_info();
555
556 if (!_mark_bitmap.initialize(mr)) {
557 vm_shutdown_during_initialization(
558 err_msg("Unable to allocate %zuKB bitmaps for parallel "
559 "garbage collection for the requested %zuKB heap.",
560 _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
561 return false;
562 }
563
564 if (!_summary_data.initialize(mr)) {
565 vm_shutdown_during_initialization(
566 err_msg("Unable to allocate %zuKB card tables for parallel "
567 "garbage collection for the requested %zuKB heap.",
568 _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
569 return false;
570 }
571
572 return true;
573 }
574
575 void PSParallelCompact::initialize_space_info()
576 {
577 memset(&_space_info, 0, sizeof(_space_info));
578
579 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
580 PSYoungGen* young_gen = heap->young_gen();
581
582 _space_info[old_space_id].set_space(heap->old_gen()->object_space());
583 _space_info[eden_space_id].set_space(young_gen->eden_space());
584 _space_info[from_space_id].set_space(young_gen->from_space());
585 _space_info[to_space_id].set_space(young_gen->to_space());
586
587 _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
588 }
589
590 void
591 PSParallelCompact::clear_data_covering_space(SpaceId id)
592 {
593 // At this point, top is the value before GC, new_top() is the value that will
594 // be set at the end of GC. The marking bitmap is cleared to top; nothing
595 // should be marked above top. The summary data is cleared to the larger of
596 // top & new_top.
597 MutableSpace* const space = _space_info[id].space();
598 HeapWord* const bot = space->bottom();
599 HeapWord* const top = space->top();
600 HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
601
602 _mark_bitmap.clear_range(bot, top);
603
604 const size_t beg_region = _summary_data.addr_to_region_idx(bot);
605 const size_t end_region =
606 _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
607 _summary_data.clear_range(beg_region, end_region);
608
609 // Clear the data used to 'split' regions.
610 SplitInfo& split_info = _space_info[id].split_info();
611 if (split_info.is_valid()) {
612 split_info.clear();
613 }
614 DEBUG_ONLY(split_info.verify_clear();)
615 }
616
617 void PSParallelCompact::pre_compact()
618 {
619 // Update the from & to space pointers in space_info, since they are swapped
620 // at each young gen gc. Do the update unconditionally (even though a
621 // promotion failure does not swap spaces) because an unknown number of young
622 // collections will have swapped the spaces an unknown number of times.
623 GCTraceTime(Debug, gc, phases) tm("Pre Compact", &_gc_timer);
624 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
625 _space_info[from_space_id].set_space(heap->young_gen()->from_space());
626 _space_info[to_space_id].set_space(heap->young_gen()->to_space());
627
628 heap->increment_total_collections(true);
629
630 CodeCache::on_gc_marking_cycle_start();
631
632 heap->print_before_gc();
633 heap->trace_heap_before_gc(&_gc_tracer);
634
635 // Fill in TLABs
636 heap->ensure_parsability(true); // retire TLABs
637
638 if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
639 Universe::verify("Before GC");
640 }
641
642 DEBUG_ONLY(mark_bitmap()->verify_clear();)
643 DEBUG_ONLY(summary_data().verify_clear();)
644 }
645
646 void PSParallelCompact::post_compact()
647 {
648 GCTraceTime(Info, gc, phases) tm("Post Compact", &_gc_timer);
649 ParCompactionManager::remove_all_shadow_regions();
650
651 CodeCache::on_gc_marking_cycle_finish();
652 CodeCache::arm_all_nmethods();
653
654 // Need to clear claim bits for the next full-gc (marking and adjust-pointers).
655 ClassLoaderDataGraph::clear_claimed_marks();
656
657 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
658 // Clear the marking bitmap, summary data and split info.
659 clear_data_covering_space(SpaceId(id));
660 {
661 MutableSpace* space = _space_info[id].space();
662 HeapWord* top = space->top();
663 HeapWord* new_top = _space_info[id].new_top();
664 if (ZapUnusedHeapArea && new_top < top) {
665 space->mangle_region(MemRegion(new_top, top));
666 }
667 // Update top(). Must be done after clearing the bitmap and summary data.
668 space->set_top(new_top);
669 }
670 }
671
672 #ifdef ASSERT
673 {
674 mark_bitmap()->verify_clear();
675 summary_data().verify_clear();
676 }
677 #endif
678
679 ParCompactionManager::flush_all_string_dedup_requests();
680
681 MutableSpace* const eden_space = _space_info[eden_space_id].space();
682 MutableSpace* const from_space = _space_info[from_space_id].space();
683 MutableSpace* const to_space = _space_info[to_space_id].space();
684
685 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
686 bool eden_empty = eden_space->is_empty();
687
688 // Update heap occupancy information which is used as input to the soft ref
689 // clearing policy at the next gc.
690 Universe::heap()->update_capacity_and_used_at_gc();
691
692 bool young_gen_empty = eden_empty && from_space->is_empty() &&
693 to_space->is_empty();
694
695 PSCardTable* ct = heap->card_table();
696 MemRegion old_mr = heap->old_gen()->committed();
697 if (young_gen_empty) {
698 ct->clear_MemRegion(old_mr);
699 } else {
700 ct->dirty_MemRegion(old_mr);
701 }
702
703 heap->prune_scavengable_nmethods();
704
705 #if COMPILER2_OR_JVMCI
706 DerivedPointerTable::update_pointers();
707 #endif
708
709 // Signal that we have completed a visit to all live objects.
710 Universe::heap()->record_whole_heap_examined_timestamp();
711 }
712
713 HeapWord* PSParallelCompact::compute_dense_prefix_for_old_space(MutableSpace* old_space,
714 HeapWord* full_region_prefix_end) {
715 const size_t region_size = ParallelCompactData::RegionSize;
716 const ParallelCompactData& sd = summary_data();
717
718 // Iteration starts with the region *after* the full-region-prefix-end.
719 const RegionData* const start_region = sd.addr_to_region_ptr(full_region_prefix_end);
720 // If final region is not full, iteration stops before that region,
721 // because fill_dense_prefix_end assumes that prefix_end <= top.
722 const RegionData* const end_region = sd.addr_to_region_ptr(old_space->top());
723 assert(start_region <= end_region, "inv");
724
725 size_t max_waste = old_space->capacity_in_words() * (MarkSweepDeadRatio / 100.0);
726 const RegionData* cur_region = start_region;
727 for (/* empty */; cur_region < end_region; ++cur_region) {
728 assert(region_size >= cur_region->data_size(), "inv");
729 size_t dead_size = region_size - cur_region->data_size();
730 if (max_waste < dead_size) {
731 break;
732 }
733 max_waste -= dead_size;
734 }
735
736 HeapWord* const prefix_end = sd.region_to_addr(cur_region);
737 assert(sd.is_region_aligned(prefix_end), "postcondition");
738 assert(prefix_end >= full_region_prefix_end, "in-range");
739 assert(prefix_end <= old_space->top(), "in-range");
740 return prefix_end;
741 }
742
743 void PSParallelCompact::fill_dense_prefix_end(SpaceId id) {
744 // Comparing two sizes to decide if filling is required:
745 //
746 // The size of the filler (min-obj-size) is 2 heap words with the default
747 // MinObjAlignment, since both markword and klass take 1 heap word.
748 // With +UseCompactObjectHeaders, the minimum filler size is only one word,
749 // because the Klass* gets encoded in the mark-word.
750 //
751 // The size of the gap (if any) right before dense-prefix-end is
752 // MinObjAlignment.
753 //
754 // Need to fill in the gap only if it's smaller than min-obj-size, and the
755 // filler obj will extend to next region.
756
757 if (MinObjAlignment >= checked_cast<int>(CollectedHeap::min_fill_size())) {
758 return;
759 }
760
761 assert(!UseCompactObjectHeaders, "Compact headers can allocate small objects");
762 assert(CollectedHeap::min_fill_size() == 2, "inv");
763 HeapWord* const dense_prefix_end = dense_prefix(id);
764 assert(_summary_data.is_region_aligned(dense_prefix_end), "precondition");
765 assert(dense_prefix_end <= space(id)->top(), "precondition");
766 if (dense_prefix_end == space(id)->top()) {
767 // Must not have single-word gap right before prefix-end/top.
768 return;
769 }
770 RegionData* const region_after_dense_prefix = _summary_data.addr_to_region_ptr(dense_prefix_end);
771
772 if (region_after_dense_prefix->partial_obj_size() != 0 ||
773 _mark_bitmap.is_marked(dense_prefix_end)) {
774 // The region after the dense prefix starts with live bytes.
775 return;
776 }
777
778 HeapWord* block_start = start_array(id)->block_start_reaching_into_card(dense_prefix_end);
779 if (block_start == dense_prefix_end - 1) {
780 assert(!_mark_bitmap.is_marked(block_start), "inv");
781 // There is exactly one heap word gap right before the dense prefix end, so we need a filler object.
782 // The filler object will extend into region_after_dense_prefix.
783 const size_t obj_len = 2; // min-fill-size
784 HeapWord* const obj_beg = dense_prefix_end - 1;
785 CollectedHeap::fill_with_object(obj_beg, obj_len);
786 _mark_bitmap.mark_obj(obj_beg);
787 _summary_data.addr_to_region_ptr(obj_beg)->add_live_obj(1);
788 region_after_dense_prefix->set_partial_obj_size(1);
789 region_after_dense_prefix->set_partial_obj_addr(obj_beg);
790 assert(start_array(id) != nullptr, "sanity");
791 start_array(id)->update_for_block(obj_beg, obj_beg + obj_len);
792 }
793 }
794
795 bool PSParallelCompact::check_maximum_compaction(bool should_do_max_compaction,
796 size_t total_live_words,
797 MutableSpace* const old_space,
798 HeapWord* full_region_prefix_end) {
799
800 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
801
802 // Check System.GC
803 bool is_max_on_system_gc = UseMaximumCompactionOnSystemGC
804 && GCCause::is_user_requested_gc(heap->gc_cause());
805
806 // Check if all live objs are too much for old-gen.
807 const bool is_old_gen_too_full = (total_live_words >= old_space->capacity_in_words());
808
809 // If all regions in old-gen are full
810 const bool is_region_full =
811 full_region_prefix_end >= _summary_data.region_align_down(old_space->top());
812
813 return should_do_max_compaction
814 || is_max_on_system_gc
815 || is_old_gen_too_full
816 || is_region_full;
817 }
818
819 void PSParallelCompact::summary_phase(bool should_do_max_compaction)
820 {
821 GCTraceTime(Info, gc, phases) tm("Summary Phase", &_gc_timer);
822
823 MutableSpace* const old_space = _space_info[old_space_id].space();
824 {
825 size_t total_live_words = 0;
826 HeapWord* full_region_prefix_end = nullptr;
827 {
828 // old-gen
829 size_t live_words = _summary_data.live_words_in_space(old_space,
830 &full_region_prefix_end);
831 total_live_words += live_words;
832 }
833 // young-gen
834 for (uint i = eden_space_id; i < last_space_id; ++i) {
835 const MutableSpace* space = _space_info[i].space();
836 size_t live_words = _summary_data.live_words_in_space(space);
837 total_live_words += live_words;
838 _space_info[i].set_new_top(space->bottom() + live_words);
839 _space_info[i].set_dense_prefix(space->bottom());
840 }
841
842 should_do_max_compaction = check_maximum_compaction(should_do_max_compaction,
843 total_live_words,
844 old_space,
845 full_region_prefix_end);
846 {
847 GCTraceTime(Info, gc, phases) tm("Summary Phase: expand", &_gc_timer);
848 // Try to expand old-gen in order to fit all live objs and waste.
849 size_t target_capacity_bytes = total_live_words * HeapWordSize
850 + old_space->capacity_in_bytes() * (MarkSweepDeadRatio / 100);
851 ParallelScavengeHeap::heap()->old_gen()->try_expand_till_size(target_capacity_bytes);
852 }
853
854 HeapWord* dense_prefix_end = should_do_max_compaction
855 ? full_region_prefix_end
856 : compute_dense_prefix_for_old_space(old_space,
857 full_region_prefix_end);
858 SpaceId id = old_space_id;
859 _space_info[id].set_dense_prefix(dense_prefix_end);
860
861 if (dense_prefix_end != old_space->bottom()) {
862 fill_dense_prefix_end(id);
863 }
864
865 // Compacting objs in [dense_prefix_end, old_space->top())
866 _summary_data.summarize(_space_info[id].split_info(),
867 dense_prefix_end, old_space->top(), nullptr,
868 dense_prefix_end, old_space->end(),
869 _space_info[id].new_top_addr());
870 }
871
872 // Summarize the remaining spaces in the young gen. The initial target space
873 // is the old gen. If a space does not fit entirely into the target, then the
874 // remainder is compacted into the space itself and that space becomes the new
875 // target.
876 SpaceId dst_space_id = old_space_id;
877 HeapWord* dst_space_end = old_space->end();
878 HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
879 for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
880 const MutableSpace* space = _space_info[id].space();
881 const size_t live = pointer_delta(_space_info[id].new_top(),
882 space->bottom());
883 const size_t available = pointer_delta(dst_space_end, *new_top_addr);
884
885 if (live > 0 && live <= available) {
886 // All the live data will fit.
887 bool done = _summary_data.summarize(_space_info[id].split_info(),
888 space->bottom(), space->top(),
889 nullptr,
890 *new_top_addr, dst_space_end,
891 new_top_addr);
892 assert(done, "space must fit into old gen");
893
894 // Reset the new_top value for the space.
895 _space_info[id].set_new_top(space->bottom());
896 } else if (live > 0) {
897 // Attempt to fit part of the source space into the target space.
898 HeapWord* next_src_addr = nullptr;
899 bool done = _summary_data.summarize(_space_info[id].split_info(),
900 space->bottom(), space->top(),
901 &next_src_addr,
902 *new_top_addr, dst_space_end,
903 new_top_addr);
904 assert(!done, "space should not fit into old gen");
905 assert(next_src_addr != nullptr, "sanity");
906
907 // The source space becomes the new target, so the remainder is compacted
908 // within the space itself.
909 dst_space_id = SpaceId(id);
910 dst_space_end = space->end();
911 new_top_addr = _space_info[id].new_top_addr();
912 done = _summary_data.summarize(_space_info[id].split_info(),
913 next_src_addr, space->top(),
914 nullptr,
915 space->bottom(), dst_space_end,
916 new_top_addr);
917 assert(done, "space must fit when compacted into itself");
918 assert(*new_top_addr <= space->top(), "usage should not grow");
919 }
920 }
921 }
922
923 void PSParallelCompact::report_object_count_after_gc() {
924 GCTraceTime(Debug, gc, phases) tm("Report Object Count", &_gc_timer);
925 // The heap is compacted, all objects are iterable. However there may be
926 // filler objects in the heap which we should ignore.
927 class SkipFillerObjectClosure : public BoolObjectClosure {
928 public:
929 bool do_object_b(oop obj) override { return !CollectedHeap::is_filler_object(obj); }
930 } cl;
931 _gc_tracer.report_object_count_after_gc(&cl, &ParallelScavengeHeap::heap()->workers());
932 }
933
934 bool PSParallelCompact::invoke(bool clear_all_soft_refs, bool should_do_max_compaction) {
935 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
936 assert(Thread::current() == (Thread*)VMThread::vm_thread(),
937 "should be in vm thread");
938 assert(ref_processor() != nullptr, "Sanity");
939
940 SvcGCMarker sgcm(SvcGCMarker::FULL);
941 IsSTWGCActiveMark mark;
942
943 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
944
945 GCIdMark gc_id_mark;
946 _gc_timer.register_gc_start();
947 _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
948
949 GCCause::Cause gc_cause = heap->gc_cause();
950 PSOldGen* old_gen = heap->old_gen();
951 PSAdaptiveSizePolicy* size_policy = heap->size_policy();
952
953 // Make sure data structures are sane, make the heap parsable, and do other
954 // miscellaneous bookkeeping.
955 pre_compact();
956
957 const PreGenGCValues pre_gc_values = heap->get_pre_gc_values();
958
959 {
960 const uint active_workers =
961 WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().max_workers(),
962 ParallelScavengeHeap::heap()->workers().active_workers(),
963 Threads::number_of_non_daemon_threads());
964 ParallelScavengeHeap::heap()->workers().set_active_workers(active_workers);
965
966 GCTraceCPUTime tcpu(&_gc_tracer);
967 GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause, true);
968
969 heap->pre_full_gc_dump(&_gc_timer);
970
971 TraceCollectorStats tcs(counters());
972 TraceMemoryManagerStats tms(heap->old_gc_manager(), gc_cause, "end of major GC");
973
974 if (log_is_enabled(Debug, gc, heap, exit)) {
975 accumulated_time()->start();
976 }
977
978 // Let the size policy know we're starting
979 size_policy->major_collection_begin();
980
981 #if COMPILER2_OR_JVMCI
982 DerivedPointerTable::clear();
983 #endif
984
985 ref_processor()->start_discovery(clear_all_soft_refs);
986
987 marking_phase(&_gc_tracer);
988
989 summary_phase(should_do_max_compaction);
990
991 #if COMPILER2_OR_JVMCI
992 assert(DerivedPointerTable::is_active(), "Sanity");
993 DerivedPointerTable::set_active(false);
994 #endif
995
996 forward_to_new_addr();
997
998 adjust_pointers();
999
1000 compact();
1001
1002 ParCompactionManager::_preserved_marks_set->restore(&ParallelScavengeHeap::heap()->workers());
1003
1004 ParCompactionManager::verify_all_region_stack_empty();
1005
1006 // Reset the mark bitmap, summary data, and do other bookkeeping. Must be
1007 // done before resizing.
1008 post_compact();
1009
1010 size_policy->major_collection_end();
1011
1012 size_policy->sample_old_gen_used_bytes(MAX2(pre_gc_values.old_gen_used(), old_gen->used_in_bytes()));
1013
1014 if (UseAdaptiveSizePolicy) {
1015 heap->resize_after_full_gc();
1016 }
1017
1018 heap->resize_all_tlabs();
1019
1020 // Resize the metaspace capacity after a collection
1021 MetaspaceGC::compute_new_size();
1022
1023 if (log_is_enabled(Debug, gc, heap, exit)) {
1024 accumulated_time()->stop();
1025 }
1026
1027 heap->print_heap_change(pre_gc_values);
1028
1029 report_object_count_after_gc();
1030
1031 // Track memory usage and detect low memory
1032 MemoryService::track_memory_usage();
1033 heap->update_counters();
1034
1035 heap->post_full_gc_dump(&_gc_timer);
1036
1037 size_policy->record_gc_pause_end_instant();
1038 }
1039
1040 heap->gc_epilogue(true);
1041
1042 if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
1043 Universe::verify("After GC");
1044 }
1045
1046 heap->print_after_gc();
1047 heap->trace_heap_after_gc(&_gc_tracer);
1048
1049 _gc_timer.register_gc_end();
1050
1051 _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
1052 _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
1053
1054 return true;
1055 }
1056
1057 class PCAddThreadRootsMarkingTaskClosure : public ThreadClosure {
1058 ParCompactionManager* _cm;
1059
1060 public:
1061 PCAddThreadRootsMarkingTaskClosure(ParCompactionManager* cm) : _cm(cm) { }
1062 void do_thread(Thread* thread) {
1063 ResourceMark rm;
1064
1065 MarkingNMethodClosure mark_and_push_in_blobs(&_cm->_mark_and_push_closure);
1066
1067 thread->oops_do(&_cm->_mark_and_push_closure, &mark_and_push_in_blobs);
1068
1069 // Do the real work
1070 _cm->follow_marking_stacks();
1071 }
1072 };
1073
1074 void steal_marking_work(TaskTerminator& terminator, uint worker_id) {
1075 assert(ParallelScavengeHeap::heap()->is_stw_gc_active(), "called outside gc");
1076
1077 ParCompactionManager* cm =
1078 ParCompactionManager::gc_thread_compaction_manager(worker_id);
1079
1080 do {
1081 ScannerTask task;
1082 if (ParCompactionManager::steal(worker_id, task)) {
1083 cm->follow_contents(task, true);
1084 }
1085 cm->follow_marking_stacks();
1086 } while (!terminator.offer_termination());
1087 }
1088
1089 class MarkFromRootsTask : public WorkerTask {
1090 NMethodMarkingScope _nmethod_marking_scope;
1091 ThreadsClaimTokenScope _threads_claim_token_scope;
1092 OopStorageSetStrongParState<false /* concurrent */, false /* is_const */> _oop_storage_set_par_state;
1093 TaskTerminator _terminator;
1094 uint _active_workers;
1095
1096 public:
1097 MarkFromRootsTask(uint active_workers) :
1098 WorkerTask("MarkFromRootsTask"),
1099 _nmethod_marking_scope(),
1100 _threads_claim_token_scope(),
1101 _terminator(active_workers, ParCompactionManager::marking_stacks()),
1102 _active_workers(active_workers) {}
1103
1104 virtual void work(uint worker_id) {
1105 ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1106 cm->create_marking_stats_cache();
1107 {
1108 CLDToOopClosure cld_closure(&cm->_mark_and_push_closure, ClassLoaderData::_claim_stw_fullgc_mark);
1109 ClassLoaderDataGraph::always_strong_cld_do(&cld_closure);
1110
1111 // Do the real work
1112 cm->follow_marking_stacks();
1113 }
1114
1115 {
1116 PCAddThreadRootsMarkingTaskClosure closure(cm);
1117 Threads::possibly_parallel_threads_do(_active_workers > 1 /* is_par */, &closure);
1118 }
1119
1120 // Mark from OopStorages
1121 {
1122 _oop_storage_set_par_state.oops_do(&cm->_mark_and_push_closure);
1123 // Do the real work
1124 cm->follow_marking_stacks();
1125 }
1126
1127 if (_active_workers > 1) {
1128 steal_marking_work(_terminator, worker_id);
1129 }
1130 }
1131 };
1132
1133 class ParallelCompactRefProcProxyTask : public RefProcProxyTask {
1134 TaskTerminator _terminator;
1135
1136 public:
1137 ParallelCompactRefProcProxyTask(uint max_workers)
1138 : RefProcProxyTask("ParallelCompactRefProcProxyTask", max_workers),
1139 _terminator(_max_workers, ParCompactionManager::marking_stacks()) {}
1140
1141 void work(uint worker_id) override {
1142 assert(worker_id < _max_workers, "sanity");
1143 ParCompactionManager* cm = (_tm == RefProcThreadModel::Single) ? ParCompactionManager::get_vmthread_cm() : ParCompactionManager::gc_thread_compaction_manager(worker_id);
1144 BarrierEnqueueDiscoveredFieldClosure enqueue;
1145 ParCompactionManager::FollowStackClosure complete_gc(cm, (_tm == RefProcThreadModel::Single) ? nullptr : &_terminator, worker_id);
1146 _rp_task->rp_work(worker_id, PSParallelCompact::is_alive_closure(), &cm->_mark_and_push_closure, &enqueue, &complete_gc);
1147 }
1148
1149 void prepare_run_task_hook() override {
1150 _terminator.reset_for_reuse(_queue_count);
1151 }
1152 };
1153
1154 static void flush_marking_stats_cache(const uint num_workers) {
1155 for (uint i = 0; i < num_workers; ++i) {
1156 ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(i);
1157 cm->flush_and_destroy_marking_stats_cache();
1158 }
1159 }
1160
1161 class PSParallelCleaningTask : public WorkerTask {
1162 bool _unloading_occurred;
1163 CodeCacheUnloadingTask _code_cache_task;
1164 // Prune dead klasses from subklass/sibling/implementor lists.
1165 KlassCleaningTask _klass_cleaning_task;
1166
1167 public:
1168 PSParallelCleaningTask(bool unloading_occurred) :
1169 WorkerTask("PS Parallel Cleaning"),
1170 _unloading_occurred(unloading_occurred),
1171 _code_cache_task(unloading_occurred),
1172 _klass_cleaning_task() {}
1173
1174 void work(uint worker_id) {
1175 #if INCLUDE_JVMCI
1176 if (EnableJVMCI && worker_id == 0) {
1177 // Serial work; only first worker.
1178 // Clean JVMCI metadata handles.
1179 JVMCI::do_unloading(_unloading_occurred);
1180 }
1181 #endif
1182
1183 // Do first pass of code cache cleaning.
1184 _code_cache_task.work(worker_id);
1185
1186 // Clean all klasses that were not unloaded.
1187 // The weak metadata in klass doesn't need to be
1188 // processed if there was no unloading.
1189 if (_unloading_occurred) {
1190 _klass_cleaning_task.work();
1191 }
1192 }
1193 };
1194
1195 void PSParallelCompact::marking_phase(ParallelOldTracer *gc_tracer) {
1196 // Recursively traverse all live objects and mark them
1197 GCTraceTime(Info, gc, phases) tm("Marking Phase", &_gc_timer);
1198
1199 uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
1200
1201 ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_mark);
1202 {
1203 GCTraceTime(Debug, gc, phases) tm("Par Mark", &_gc_timer);
1204
1205 MarkFromRootsTask task(active_gc_threads);
1206 ParallelScavengeHeap::heap()->workers().run_task(&task);
1207 }
1208
1209 // Process reference objects found during marking
1210 {
1211 GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
1212
1213 ReferenceProcessorStats stats;
1214 ReferenceProcessorPhaseTimes pt(&_gc_timer, ref_processor()->max_num_queues());
1215
1216 ParallelCompactRefProcProxyTask task(ref_processor()->max_num_queues());
1217 stats = ref_processor()->process_discovered_references(task, &ParallelScavengeHeap::heap()->workers(), pt);
1218
1219 gc_tracer->report_gc_reference_stats(stats);
1220 pt.print_all_references();
1221 }
1222
1223 {
1224 GCTraceTime(Debug, gc, phases) tm("Flush Marking Stats", &_gc_timer);
1225
1226 flush_marking_stats_cache(active_gc_threads);
1227 }
1228
1229 // This is the point where the entire marking should have completed.
1230 ParCompactionManager::verify_all_marking_stack_empty();
1231
1232 {
1233 GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
1234 WeakProcessor::weak_oops_do(&ParallelScavengeHeap::heap()->workers(),
1235 is_alive_closure(),
1236 &do_nothing_cl,
1237 1);
1238 }
1239
1240 {
1241 GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
1242
1243 ClassUnloadingContext ctx(active_gc_threads /* num_nmethod_unlink_workers */,
1244 false /* unregister_nmethods_during_purge */,
1245 false /* lock_nmethod_free_separately */);
1246
1247 {
1248 CodeCache::UnlinkingScope scope(is_alive_closure());
1249
1250 // Follow system dictionary roots and unload classes.
1251 bool unloading_occurred = SystemDictionary::do_unloading(&_gc_timer);
1252
1253 PSParallelCleaningTask task{unloading_occurred};
1254 ParallelScavengeHeap::heap()->workers().run_task(&task);
1255 }
1256
1257 {
1258 GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", gc_timer());
1259 // Release unloaded nmethod's memory.
1260 ctx.purge_nmethods();
1261 }
1262 {
1263 GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", &_gc_timer);
1264 ParallelScavengeHeap::heap()->prune_unlinked_nmethods();
1265 }
1266 {
1267 GCTraceTime(Debug, gc, phases) t("Free Code Blobs", gc_timer());
1268 ctx.free_nmethods();
1269 }
1270 {
1271 // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1272 GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", gc_timer());
1273 ClassLoaderDataGraph::purge(true /* at_safepoint */);
1274 DEBUG_ONLY(MetaspaceUtils::verify();)
1275 }
1276 }
1277
1278 #if TASKQUEUE_STATS
1279 ParCompactionManager::print_and_reset_taskqueue_stats();
1280 #endif
1281 }
1282
1283 template<typename Func>
1284 void PSParallelCompact::adjust_in_space_helper(SpaceId id, Atomic<uint>* claim_counter, Func&& on_stripe) {
1285 MutableSpace* sp = PSParallelCompact::space(id);
1286 HeapWord* const bottom = sp->bottom();
1287 HeapWord* const top = sp->top();
1288 if (bottom == top) {
1289 return;
1290 }
1291
1292 const uint num_regions_per_stripe = 2;
1293 const size_t region_size = ParallelCompactData::RegionSize;
1294 const size_t stripe_size = num_regions_per_stripe * region_size;
1295
1296 while (true) {
1297 uint counter = claim_counter->fetch_then_add(num_regions_per_stripe);
1298 HeapWord* cur_stripe = bottom + counter * region_size;
1299 if (cur_stripe >= top) {
1300 break;
1301 }
1302 HeapWord* stripe_end = MIN2(cur_stripe + stripe_size, top);
1303 on_stripe(cur_stripe, stripe_end);
1304 }
1305 }
1306
1307 void PSParallelCompact::adjust_in_old_space(Atomic<uint>* claim_counter) {
1308 // Regions in old-space shouldn't be split.
1309 assert(!_space_info[old_space_id].split_info().is_valid(), "inv");
1310
1311 auto scan_obj_with_limit = [&] (HeapWord* obj_start, HeapWord* left, HeapWord* right) {
1312 assert(mark_bitmap()->is_marked(obj_start), "inv");
1313 oop obj = cast_to_oop(obj_start);
1314 return obj->oop_iterate_size(&pc_adjust_pointer_closure, MemRegion(left, right));
1315 };
1316
1317 adjust_in_space_helper(old_space_id, claim_counter, [&] (HeapWord* stripe_start, HeapWord* stripe_end) {
1318 assert(_summary_data.is_region_aligned(stripe_start), "inv");
1319 RegionData* cur_region = _summary_data.addr_to_region_ptr(stripe_start);
1320 HeapWord* obj_start;
1321 if (cur_region->partial_obj_size() != 0) {
1322 obj_start = cur_region->partial_obj_addr();
1323 obj_start += scan_obj_with_limit(obj_start, stripe_start, stripe_end);
1324 } else {
1325 obj_start = stripe_start;
1326 }
1327
1328 while (obj_start < stripe_end) {
1329 obj_start = mark_bitmap()->find_obj_beg(obj_start, stripe_end);
1330 if (obj_start >= stripe_end) {
1331 break;
1332 }
1333 obj_start += scan_obj_with_limit(obj_start, stripe_start, stripe_end);
1334 }
1335 });
1336 }
1337
1338 void PSParallelCompact::adjust_in_young_space(SpaceId id, Atomic<uint>* claim_counter) {
1339 adjust_in_space_helper(id, claim_counter, [](HeapWord* stripe_start, HeapWord* stripe_end) {
1340 HeapWord* obj_start = stripe_start;
1341 while (obj_start < stripe_end) {
1342 obj_start = mark_bitmap()->find_obj_beg(obj_start, stripe_end);
1343 if (obj_start >= stripe_end) {
1344 break;
1345 }
1346 oop obj = cast_to_oop(obj_start);
1347 obj_start += obj->oop_iterate_size(&pc_adjust_pointer_closure);
1348 }
1349 });
1350 }
1351
1352 void PSParallelCompact::adjust_pointers_in_spaces(uint worker_id, Atomic<uint>* claim_counters) {
1353 auto start_time = Ticks::now();
1354 adjust_in_old_space(&claim_counters[0]);
1355 for (uint id = eden_space_id; id < last_space_id; ++id) {
1356 adjust_in_young_space(SpaceId(id), &claim_counters[id]);
1357 }
1358 log_trace(gc, phases)("adjust_pointers_in_spaces worker %u: %.3f ms", worker_id, (Ticks::now() - start_time).seconds() * 1000);
1359 }
1360
1361 class PSAdjustTask final : public WorkerTask {
1362 ThreadsClaimTokenScope _threads_claim_token_scope;
1363 WeakProcessor::Task _weak_proc_task;
1364 OopStorageSetStrongParState<false, false> _oop_storage_iter;
1365 uint _nworkers;
1366 Atomic<bool> _code_cache_claimed;
1367 Atomic<uint> _claim_counters[PSParallelCompact::last_space_id];
1368
1369 bool try_claim_code_cache_task() {
1370 return _code_cache_claimed.load_relaxed() == false
1371 && _code_cache_claimed.compare_set(false, true);
1372 }
1373
1374 public:
1375 PSAdjustTask(uint nworkers) :
1376 WorkerTask("PSAdjust task"),
1377 _threads_claim_token_scope(),
1378 _weak_proc_task(nworkers),
1379 _oop_storage_iter(),
1380 _nworkers(nworkers),
1381 _code_cache_claimed(false) {
1382
1383 for (unsigned int i = PSParallelCompact::old_space_id; i < PSParallelCompact::last_space_id; ++i) {
1384 ::new (&_claim_counters[i]) Atomic<uint>{};
1385 }
1386 ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_adjust);
1387 }
1388
1389 void work(uint worker_id) {
1390 {
1391 // Pointers in heap.
1392 ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1393 cm->preserved_marks()->adjust_during_full_gc();
1394
1395 PSParallelCompact::adjust_pointers_in_spaces(worker_id, _claim_counters);
1396 }
1397
1398 {
1399 // All (strong and weak) CLDs.
1400 CLDToOopClosure cld_closure(&pc_adjust_pointer_closure, ClassLoaderData::_claim_stw_fullgc_adjust);
1401 ClassLoaderDataGraph::cld_do(&cld_closure);
1402 }
1403
1404 {
1405 // Threads stack frames. No need to visit on-stack nmethods, because all
1406 // nmethods are visited in one go via CodeCache::nmethods_do.
1407 ResourceMark rm;
1408 Threads::possibly_parallel_oops_do(_nworkers > 1, &pc_adjust_pointer_closure, nullptr);
1409 if (try_claim_code_cache_task()) {
1410 NMethodToOopClosure adjust_code(&pc_adjust_pointer_closure, NMethodToOopClosure::FixRelocations);
1411 CodeCache::nmethods_do(&adjust_code);
1412 }
1413 }
1414
1415 {
1416 // VM internal strong and weak roots.
1417 _oop_storage_iter.oops_do(&pc_adjust_pointer_closure);
1418 AlwaysTrueClosure always_alive;
1419 _weak_proc_task.work(worker_id, &always_alive, &pc_adjust_pointer_closure);
1420 }
1421 }
1422 };
1423
1424 void PSParallelCompact::adjust_pointers() {
1425 // Adjust the pointers to reflect the new locations
1426 GCTraceTime(Info, gc, phases) tm("Adjust Pointers", &_gc_timer);
1427 uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
1428 PSAdjustTask task(nworkers);
1429 ParallelScavengeHeap::heap()->workers().run_task(&task);
1430 }
1431
1432 // Split [start, end) evenly for a number of workers and return the
1433 // range for worker_id.
1434 static void split_regions_for_worker(size_t start, size_t end,
1435 uint worker_id, uint num_workers,
1436 size_t* worker_start, size_t* worker_end) {
1437 assert(start < end, "precondition");
1438 assert(num_workers > 0, "precondition");
1439 assert(worker_id < num_workers, "precondition");
1440
1441 size_t num_regions = end - start;
1442 size_t num_regions_per_worker = num_regions / num_workers;
1443 size_t remainder = num_regions % num_workers;
1444 // The first few workers will get one extra.
1445 *worker_start = start + worker_id * num_regions_per_worker
1446 + MIN2(checked_cast<size_t>(worker_id), remainder);
1447 *worker_end = *worker_start + num_regions_per_worker
1448 + (worker_id < remainder ? 1 : 0);
1449 }
1450
1451 void PSParallelCompact::forward_to_new_addr() {
1452 GCTraceTime(Info, gc, phases) tm("Forward", &_gc_timer);
1453 uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
1454
1455 struct ForwardTask final : public WorkerTask {
1456 uint _num_workers;
1457
1458 explicit ForwardTask(uint num_workers) :
1459 WorkerTask("PSForward task"),
1460 _num_workers(num_workers) {}
1461
1462 static void forward_objs_in_range(ParCompactionManager* cm,
1463 HeapWord* start,
1464 HeapWord* end,
1465 HeapWord* destination) {
1466 HeapWord* cur_addr = start;
1467 HeapWord* new_addr = destination;
1468
1469 while (cur_addr < end) {
1470 cur_addr = mark_bitmap()->find_obj_beg(cur_addr, end);
1471 if (cur_addr >= end) {
1472 return;
1473 }
1474 assert(mark_bitmap()->is_marked(cur_addr), "inv");
1475 oop obj = cast_to_oop(cur_addr);
1476 if (new_addr != cur_addr) {
1477 cm->preserved_marks()->push_if_necessary(obj, obj->mark());
1478 FullGCForwarding::forward_to(obj, cast_to_oop(new_addr));
1479 }
1480 size_t obj_size = obj->size();
1481 new_addr += obj_size;
1482 cur_addr += obj_size;
1483 }
1484 }
1485
1486 void work(uint worker_id) override {
1487 ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1488 for (uint id = old_space_id; id < last_space_id; ++id) {
1489 MutableSpace* sp = PSParallelCompact::space(SpaceId(id));
1490 HeapWord* dense_prefix_addr = dense_prefix(SpaceId(id));
1491 HeapWord* top = sp->top();
1492
1493 if (dense_prefix_addr == top) {
1494 // Empty space
1495 continue;
1496 }
1497
1498 const SplitInfo& split_info = _space_info[SpaceId(id)].split_info();
1499 size_t dense_prefix_region = _summary_data.addr_to_region_idx(dense_prefix_addr);
1500 size_t top_region = _summary_data.addr_to_region_idx(_summary_data.region_align_up(top));
1501 size_t start_region;
1502 size_t end_region;
1503 split_regions_for_worker(dense_prefix_region, top_region,
1504 worker_id, _num_workers,
1505 &start_region, &end_region);
1506 for (size_t cur_region = start_region; cur_region < end_region; ++cur_region) {
1507 RegionData* region_ptr = _summary_data.region(cur_region);
1508 size_t partial_obj_size = region_ptr->partial_obj_size();
1509
1510 if (partial_obj_size == ParallelCompactData::RegionSize) {
1511 // No obj-start
1512 continue;
1513 }
1514
1515 HeapWord* region_start = _summary_data.region_to_addr(cur_region);
1516 HeapWord* region_end = region_start + ParallelCompactData::RegionSize;
1517
1518 if (split_info.is_split(cur_region)) {
1519 // Part 1: will be relocated to space-1
1520 HeapWord* preceding_destination = split_info.preceding_destination();
1521 HeapWord* split_point = split_info.split_point();
1522 forward_objs_in_range(cm, region_start + partial_obj_size, split_point, preceding_destination + partial_obj_size);
1523
1524 // Part 2: will be relocated to space-2
1525 HeapWord* destination = region_ptr->destination();
1526 forward_objs_in_range(cm, split_point, region_end, destination);
1527 } else {
1528 HeapWord* destination = region_ptr->destination();
1529 forward_objs_in_range(cm, region_start + partial_obj_size, region_end, destination + partial_obj_size);
1530 }
1531 }
1532 }
1533 }
1534 } task(nworkers);
1535
1536 ParallelScavengeHeap::heap()->workers().run_task(&task);
1537 DEBUG_ONLY(verify_forward();)
1538 }
1539
1540 #ifdef ASSERT
1541 void PSParallelCompact::verify_forward() {
1542 HeapWord* const old_dense_prefix_addr = dense_prefix(SpaceId(old_space_id));
1543 // The destination addr for the first live obj after dense-prefix.
1544 HeapWord* bump_ptr = old_dense_prefix_addr
1545 + _summary_data.addr_to_region_ptr(old_dense_prefix_addr)->partial_obj_size();
1546 SpaceId bump_ptr_space = old_space_id;
1547
1548 for (uint id = old_space_id; id < last_space_id; ++id) {
1549 MutableSpace* sp = PSParallelCompact::space(SpaceId(id));
1550 // Only verify objs after dense-prefix, because those before dense-prefix are not moved (forwarded).
1551 HeapWord* cur_addr = dense_prefix(SpaceId(id));
1552 HeapWord* top = sp->top();
1553
1554 while (cur_addr < top) {
1555 cur_addr = mark_bitmap()->find_obj_beg(cur_addr, top);
1556 if (cur_addr >= top) {
1557 break;
1558 }
1559 assert(mark_bitmap()->is_marked(cur_addr), "inv");
1560 assert(bump_ptr <= _space_info[bump_ptr_space].new_top(), "inv");
1561 // Move to the space containing cur_addr
1562 if (bump_ptr == _space_info[bump_ptr_space].new_top()) {
1563 bump_ptr = space(space_id(cur_addr))->bottom();
1564 bump_ptr_space = space_id(bump_ptr);
1565 }
1566 oop obj = cast_to_oop(cur_addr);
1567 if (cur_addr == bump_ptr) {
1568 assert(!FullGCForwarding::is_forwarded(obj), "inv");
1569 } else {
1570 assert(FullGCForwarding::forwardee(obj) == cast_to_oop(bump_ptr), "inv");
1571 }
1572 bump_ptr += obj->size();
1573 cur_addr += obj->size();
1574 }
1575 }
1576 }
1577 #endif
1578
1579 // Helper class to print 8 region numbers per line and then print the total at the end.
1580 class FillableRegionLogger : public StackObj {
1581 private:
1582 Log(gc, compaction) log;
1583 static const int LineLength = 8;
1584 size_t _regions[LineLength];
1585 int _next_index;
1586 bool _enabled;
1587 size_t _total_regions;
1588 public:
1589 FillableRegionLogger() : _next_index(0), _enabled(log_develop_is_enabled(Trace, gc, compaction)), _total_regions(0) { }
1590 ~FillableRegionLogger() {
1591 log.trace("%zu initially fillable regions", _total_regions);
1592 }
1593
1594 void print_line() {
1595 if (!_enabled || _next_index == 0) {
1596 return;
1597 }
1598 FormatBuffer<> line("Fillable: ");
1599 for (int i = 0; i < _next_index; i++) {
1600 line.append(" %7zu", _regions[i]);
1601 }
1602 log.trace("%s", line.buffer());
1603 _next_index = 0;
1604 }
1605
1606 void handle(size_t region) {
1607 if (!_enabled) {
1608 return;
1609 }
1610 _regions[_next_index++] = region;
1611 if (_next_index == LineLength) {
1612 print_line();
1613 }
1614 _total_regions++;
1615 }
1616 };
1617
1618 void PSParallelCompact::prepare_region_draining_tasks(uint parallel_gc_threads)
1619 {
1620 GCTraceTime(Trace, gc, phases) tm("Drain Task Setup", &_gc_timer);
1621
1622 // Find the threads that are active
1623 uint worker_id = 0;
1624
1625 // Find all regions that are available (can be filled immediately) and
1626 // distribute them to the thread stacks. The iteration is done in reverse
1627 // order (high to low) so the regions will be removed in ascending order.
1628
1629 const ParallelCompactData& sd = PSParallelCompact::summary_data();
1630
1631 // id + 1 is used to test termination so unsigned can
1632 // be used with an old_space_id == 0.
1633 FillableRegionLogger region_logger;
1634 for (unsigned int id = last_space_id - 1; id + 1 > old_space_id; --id) {
1635 SpaceInfo* const space_info = _space_info + id;
1636 HeapWord* const new_top = space_info->new_top();
1637
1638 const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
1639 const size_t end_region =
1640 sd.addr_to_region_idx(sd.region_align_up(new_top));
1641
1642 for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
1643 if (sd.region(cur)->claim_unsafe()) {
1644 ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1645 bool result = sd.region(cur)->mark_normal();
1646 assert(result, "Must succeed at this point.");
1647 cm->region_stack()->push(cur);
1648 region_logger.handle(cur);
1649 // Assign regions to tasks in round-robin fashion.
1650 if (++worker_id == parallel_gc_threads) {
1651 worker_id = 0;
1652 }
1653 }
1654 }
1655 region_logger.print_line();
1656 }
1657 }
1658
1659 static void compaction_with_stealing_work(TaskTerminator* terminator, uint worker_id) {
1660 assert(ParallelScavengeHeap::heap()->is_stw_gc_active(), "called outside gc");
1661
1662 ParCompactionManager* cm =
1663 ParCompactionManager::gc_thread_compaction_manager(worker_id);
1664
1665 // Drain the stacks that have been preloaded with regions
1666 // that are ready to fill.
1667
1668 cm->drain_region_stacks();
1669
1670 guarantee(cm->region_stack()->is_empty(), "Not empty");
1671
1672 size_t region_index = 0;
1673
1674 while (true) {
1675 if (ParCompactionManager::steal(worker_id, region_index)) {
1676 PSParallelCompact::fill_and_update_region(cm, region_index);
1677 cm->drain_region_stacks();
1678 } else if (PSParallelCompact::steal_unavailable_region(cm, region_index)) {
1679 // Fill and update an unavailable region with the help of a shadow region
1680 PSParallelCompact::fill_and_update_shadow_region(cm, region_index);
1681 cm->drain_region_stacks();
1682 } else {
1683 if (terminator->offer_termination()) {
1684 break;
1685 }
1686 // Go around again.
1687 }
1688 }
1689 }
1690
1691 class FillDensePrefixAndCompactionTask: public WorkerTask {
1692 TaskTerminator _terminator;
1693
1694 public:
1695 FillDensePrefixAndCompactionTask(uint active_workers) :
1696 WorkerTask("FillDensePrefixAndCompactionTask"),
1697 _terminator(active_workers, ParCompactionManager::region_task_queues()) {
1698 }
1699
1700 virtual void work(uint worker_id) {
1701 if (worker_id == 0) {
1702 auto start = Ticks::now();
1703 PSParallelCompact::fill_dead_objs_in_dense_prefix();
1704 log_trace(gc, phases)("Fill dense prefix by worker 0: %.3f ms", (Ticks::now() - start).seconds() * 1000);
1705 }
1706 compaction_with_stealing_work(&_terminator, worker_id);
1707 }
1708 };
1709
1710 void PSParallelCompact::fill_range_in_dense_prefix(HeapWord* start, HeapWord* end) {
1711 #ifdef ASSERT
1712 {
1713 assert(start < end, "precondition");
1714 assert(mark_bitmap()->find_obj_beg(start, end) == end, "precondition");
1715 HeapWord* bottom = _space_info[old_space_id].space()->bottom();
1716 if (start != bottom) {
1717 // The preceding live obj.
1718 HeapWord* obj_start = mark_bitmap()->find_obj_beg_reverse(bottom, start);
1719 HeapWord* obj_end = obj_start + cast_to_oop(obj_start)->size();
1720 assert(obj_end == start, "precondition");
1721 }
1722 }
1723 #endif
1724
1725 CollectedHeap::fill_with_objects(start, pointer_delta(end, start));
1726 HeapWord* addr = start;
1727 do {
1728 size_t size = cast_to_oop(addr)->size();
1729 start_array(old_space_id)->update_for_block(addr, addr + size);
1730 addr += size;
1731 } while (addr < end);
1732 }
1733
1734 void PSParallelCompact::fill_dead_objs_in_dense_prefix() {
1735 ParMarkBitMap* bitmap = mark_bitmap();
1736
1737 HeapWord* const bottom = _space_info[old_space_id].space()->bottom();
1738 HeapWord* const prefix_end = dense_prefix(old_space_id);
1739
1740 const size_t region_size = ParallelCompactData::RegionSize;
1741
1742 // Fill dead space in [start_addr, end_addr)
1743 HeapWord* const start_addr = bottom;
1744 HeapWord* const end_addr = prefix_end;
1745
1746 for (HeapWord* cur_addr = start_addr; cur_addr < end_addr; /* empty */) {
1747 RegionData* cur_region_ptr = _summary_data.addr_to_region_ptr(cur_addr);
1748 if (cur_region_ptr->data_size() == region_size) {
1749 // Full; no dead space. Next region.
1750 if (_summary_data.is_region_aligned(cur_addr)) {
1751 cur_addr += region_size;
1752 } else {
1753 cur_addr = _summary_data.region_align_up(cur_addr);
1754 }
1755 continue;
1756 }
1757
1758 // Fill dead space inside cur_region.
1759 if (_summary_data.is_region_aligned(cur_addr)) {
1760 cur_addr += cur_region_ptr->partial_obj_size();
1761 }
1762
1763 HeapWord* region_end_addr = _summary_data.region_align_up(cur_addr + 1);
1764 assert(region_end_addr <= end_addr, "inv");
1765 while (cur_addr < region_end_addr) {
1766 // Use end_addr to allow filler-obj to cross region boundary.
1767 HeapWord* live_start = bitmap->find_obj_beg(cur_addr, end_addr);
1768 if (cur_addr != live_start) {
1769 // Found dead space [cur_addr, live_start).
1770 fill_range_in_dense_prefix(cur_addr, live_start);
1771 }
1772 if (live_start >= region_end_addr) {
1773 cur_addr = live_start;
1774 break;
1775 }
1776 assert(bitmap->is_marked(live_start), "inv");
1777 cur_addr = live_start + cast_to_oop(live_start)->size();
1778 }
1779 }
1780 }
1781
1782 void PSParallelCompact::compact() {
1783 GCTraceTime(Info, gc, phases) tm("Compaction Phase", &_gc_timer);
1784
1785 uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
1786
1787 initialize_shadow_regions(active_gc_threads);
1788 prepare_region_draining_tasks(active_gc_threads);
1789
1790 {
1791 GCTraceTime(Trace, gc, phases) tm("Par Compact", &_gc_timer);
1792
1793 FillDensePrefixAndCompactionTask task(active_gc_threads);
1794 ParallelScavengeHeap::heap()->workers().run_task(&task);
1795
1796 #ifdef ASSERT
1797 verify_filler_in_dense_prefix();
1798
1799 // Verify that all regions have been processed.
1800 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1801 verify_complete(SpaceId(id));
1802 }
1803 #endif
1804 }
1805 }
1806
1807 #ifdef ASSERT
1808 void PSParallelCompact::verify_filler_in_dense_prefix() {
1809 HeapWord* bottom = _space_info[old_space_id].space()->bottom();
1810 HeapWord* dense_prefix_end = dense_prefix(old_space_id);
1811
1812 const size_t region_size = ParallelCompactData::RegionSize;
1813
1814 for (HeapWord* cur_addr = bottom; cur_addr < dense_prefix_end; /* empty */) {
1815 RegionData* cur_region_ptr = _summary_data.addr_to_region_ptr(cur_addr);
1816 if (cur_region_ptr->data_size() == region_size) {
1817 // Full; no dead space. Next region.
1818 if (_summary_data.is_region_aligned(cur_addr)) {
1819 cur_addr += region_size;
1820 } else {
1821 cur_addr = _summary_data.region_align_up(cur_addr);
1822 }
1823 continue;
1824 }
1825
1826 // This region contains filler objs.
1827 if (_summary_data.is_region_aligned(cur_addr)) {
1828 cur_addr += cur_region_ptr->partial_obj_size();
1829 }
1830
1831 HeapWord* region_end_addr = _summary_data.region_align_up(cur_addr + 1);
1832 assert(region_end_addr <= dense_prefix_end, "inv");
1833
1834 while (cur_addr < region_end_addr) {
1835 oop obj = cast_to_oop(cur_addr);
1836 oopDesc::verify(obj);
1837 if (!mark_bitmap()->is_marked(cur_addr)) {
1838 assert(CollectedHeap::is_filler_object(cast_to_oop(cur_addr)), "inv");
1839 }
1840 cur_addr += obj->size();
1841 }
1842 }
1843 }
1844
1845 void PSParallelCompact::verify_complete(SpaceId space_id) {
1846 // All Regions served as compaction targets, from dense_prefix() to
1847 // new_top(), should be marked as filled and all Regions between new_top()
1848 // and top() should be available (i.e., should have been emptied).
1849 ParallelCompactData& sd = summary_data();
1850 SpaceInfo si = _space_info[space_id];
1851 HeapWord* new_top_addr = sd.region_align_up(si.new_top());
1852 HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
1853 const size_t beg_region = sd.addr_to_region_idx(si.dense_prefix());
1854 const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
1855 const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
1856
1857 size_t cur_region;
1858 for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
1859 const RegionData* const c = sd.region(cur_region);
1860 assert(c->completed(), "region %zu not filled: destination_count=%u",
1861 cur_region, c->destination_count());
1862 }
1863
1864 for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
1865 const RegionData* const c = sd.region(cur_region);
1866 assert(c->available(), "region %zu not empty: destination_count=%u",
1867 cur_region, c->destination_count());
1868 }
1869 }
1870 #endif // #ifdef ASSERT
1871
1872 // Return the SpaceId for the space containing addr. If addr is not in the
1873 // heap, last_space_id is returned. In debug mode it expects the address to be
1874 // in the heap and asserts such.
1875 PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
1876 assert(ParallelScavengeHeap::heap()->is_in_reserved(addr), "addr not in the heap");
1877
1878 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1879 if (_space_info[id].space()->contains(addr)) {
1880 return SpaceId(id);
1881 }
1882 }
1883
1884 assert(false, "no space contains the addr");
1885 return last_space_id;
1886 }
1887
1888 // Skip over count live words starting from beg, and return the address of the
1889 // next live word. Callers must also ensure that there are enough live words in
1890 // the range [beg, end) to skip.
1891 HeapWord* PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
1892 {
1893 ParMarkBitMap* m = mark_bitmap();
1894 HeapWord* cur_addr = beg;
1895 while (true) {
1896 cur_addr = m->find_obj_beg(cur_addr, end);
1897 assert(cur_addr < end, "inv");
1898 size_t obj_size = cast_to_oop(cur_addr)->size();
1899 // Strictly greater-than
1900 if (obj_size > count) {
1901 return cur_addr + count;
1902 }
1903 count -= obj_size;
1904 cur_addr += obj_size;
1905 }
1906 }
1907
1908 // On starting to fill a destination region (dest-region), we need to know the
1909 // location of the word that will be at the start of the dest-region after
1910 // compaction. A dest-region can have one or more source regions, but only the
1911 // first source-region contains this location. This location is retrieved by
1912 // calling `first_src_addr` on a dest-region.
1913 // Conversely, a source-region has a dest-region which holds the destination of
1914 // the first live word on this source-region, based on which the destination
1915 // for the rest of live words can be derived.
1916 //
1917 // Note:
1918 // There is some complication due to space-boundary-fragmentation (an obj can't
1919 // cross space-boundary) -- a source-region may be split and behave like two
1920 // distinct regions with their own dest-region, as depicted below.
1921 //
1922 // source-region: region-n
1923 //
1924 // **********************
1925 // | A|A~~~~B|B |
1926 // **********************
1927 // n-1 n n+1
1928 //
1929 // AA, BB denote two live objs. ~~~~ denotes unknown number of live objs.
1930 //
1931 // Assuming the dest-region for region-n is the final region before
1932 // old-space-end and its first-live-word is the middle of AA, the heap content
1933 // will look like the following after compaction:
1934 //
1935 // ************** *************
1936 // A|A~~~~ | |BB |
1937 // ************** *************
1938 // ^ ^
1939 // | old-space-end | eden-space-start
1940 //
1941 // Therefore, in this example, region-n will have two dest-regions:
1942 // 1. the final region in old-space
1943 // 2. the first region in eden-space.
1944 // To handle this special case, we introduce the concept of split-region, whose
1945 // contents are relocated to two spaces. `SplitInfo` captures all necessary
1946 // info about the split, the first part, spliting-point, and the second part.
1947 HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
1948 SpaceId src_space_id,
1949 size_t src_region_idx)
1950 {
1951 const size_t RegionSize = ParallelCompactData::RegionSize;
1952 const ParallelCompactData& sd = summary_data();
1953 assert(sd.is_region_aligned(dest_addr), "precondition");
1954
1955 const RegionData* const src_region_ptr = sd.region(src_region_idx);
1956 assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
1957
1958 const size_t partial_obj_size = src_region_ptr->partial_obj_size();
1959 HeapWord* const src_region_destination = src_region_ptr->destination();
1960
1961 HeapWord* const region_start = sd.region_to_addr(src_region_idx);
1962 HeapWord* const region_end = sd.region_to_addr(src_region_idx) + RegionSize;
1963
1964 // Identify the actual destination for the first live words on this region,
1965 // taking split-region into account.
1966 HeapWord* region_start_destination;
1967 const SplitInfo& split_info = _space_info[src_space_id].split_info();
1968 if (split_info.is_split(src_region_idx)) {
1969 // The second part of this split region; use the recorded split point.
1970 if (dest_addr == src_region_destination) {
1971 return split_info.split_point();
1972 }
1973 region_start_destination = split_info.preceding_destination();
1974 } else {
1975 region_start_destination = src_region_destination;
1976 }
1977
1978 // Calculate the offset to be skipped
1979 size_t words_to_skip = pointer_delta(dest_addr, region_start_destination);
1980
1981 HeapWord* result;
1982 if (partial_obj_size > words_to_skip) {
1983 result = region_start + words_to_skip;
1984 } else {
1985 words_to_skip -= partial_obj_size;
1986 result = skip_live_words(region_start + partial_obj_size, region_end, words_to_skip);
1987 }
1988
1989 if (split_info.is_split(src_region_idx)) {
1990 assert(result < split_info.split_point(), "postcondition");
1991 } else {
1992 assert(result < region_end, "postcondition");
1993 }
1994
1995 return result;
1996 }
1997
1998 void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
1999 SpaceId src_space_id,
2000 size_t beg_region,
2001 HeapWord* end_addr)
2002 {
2003 ParallelCompactData& sd = summary_data();
2004
2005 #ifdef ASSERT
2006 MutableSpace* const src_space = _space_info[src_space_id].space();
2007 HeapWord* const beg_addr = sd.region_to_addr(beg_region);
2008 assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
2009 "src_space_id does not match beg_addr");
2010 assert(src_space->contains(end_addr) || end_addr == src_space->end(),
2011 "src_space_id does not match end_addr");
2012 #endif // #ifdef ASSERT
2013
2014 RegionData* const beg = sd.region(beg_region);
2015 RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));
2016
2017 // Regions up to new_top() are enqueued if they become available.
2018 HeapWord* const new_top = _space_info[src_space_id].new_top();
2019 RegionData* const enqueue_end =
2020 sd.addr_to_region_ptr(sd.region_align_up(new_top));
2021
2022 for (RegionData* cur = beg; cur < end; ++cur) {
2023 assert(cur->data_size() > 0, "region must have live data");
2024 cur->decrement_destination_count();
2025 if (cur < enqueue_end && cur->available() && cur->claim()) {
2026 if (cur->mark_normal()) {
2027 cm->push_region(sd.region(cur));
2028 } else if (cur->mark_copied()) {
2029 // Try to copy the content of the shadow region back to its corresponding
2030 // heap region if the shadow region is filled. Otherwise, the GC thread
2031 // fills the shadow region will copy the data back (see
2032 // MoveAndUpdateShadowClosure::complete_region).
2033 copy_back(sd.region_to_addr(cur->shadow_region()), sd.region_to_addr(cur));
2034 ParCompactionManager::push_shadow_region_mt_safe(cur->shadow_region());
2035 cur->set_completed();
2036 }
2037 }
2038 }
2039 }
2040
2041 size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
2042 SpaceId& src_space_id,
2043 HeapWord*& src_space_top,
2044 HeapWord* end_addr)
2045 {
2046 ParallelCompactData& sd = PSParallelCompact::summary_data();
2047
2048 size_t src_region_idx = 0;
2049
2050 // Skip empty regions (if any) up to the top of the space.
2051 HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
2052 RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
2053 HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
2054 const RegionData* const top_region_ptr = sd.addr_to_region_ptr(top_aligned_up);
2055
2056 while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
2057 ++src_region_ptr;
2058 }
2059
2060 if (src_region_ptr < top_region_ptr) {
2061 // Found the first non-empty region in the same space.
2062 src_region_idx = sd.region(src_region_ptr);
2063 closure.set_source(sd.region_to_addr(src_region_idx));
2064 return src_region_idx;
2065 }
2066
2067 // Switch to a new source space and find the first non-empty region.
2068 uint space_id = src_space_id + 1;
2069 assert(space_id < last_space_id, "not enough spaces");
2070
2071 for (/* empty */; space_id < last_space_id; ++space_id) {
2072 HeapWord* bottom = _space_info[space_id].space()->bottom();
2073 HeapWord* top = _space_info[space_id].space()->top();
2074 // Skip empty space
2075 if (bottom == top) {
2076 continue;
2077 }
2078
2079 // Identify the first region that contains live words in this space
2080 size_t cur_region = sd.addr_to_region_idx(bottom);
2081 size_t end_region = sd.addr_to_region_idx(sd.region_align_up(top));
2082
2083 for (/* empty */ ; cur_region < end_region; ++cur_region) {
2084 RegionData* cur = sd.region(cur_region);
2085 if (cur->live_obj_size() > 0) {
2086 HeapWord* region_start_addr = sd.region_to_addr(cur_region);
2087
2088 src_space_id = SpaceId(space_id);
2089 src_space_top = top;
2090 closure.set_source(region_start_addr);
2091 return cur_region;
2092 }
2093 }
2094 }
2095
2096 ShouldNotReachHere();
2097 }
2098
2099 HeapWord* PSParallelCompact::partial_obj_end(HeapWord* region_start_addr) {
2100 ParallelCompactData& sd = summary_data();
2101 assert(sd.is_region_aligned(region_start_addr), "precondition");
2102
2103 // Use per-region partial_obj_size to locate the end of the obj, that extends
2104 // to region_start_addr.
2105 size_t start_region_idx = sd.addr_to_region_idx(region_start_addr);
2106 size_t end_region_idx = sd.region_count();
2107 size_t accumulated_size = 0;
2108 for (size_t region_idx = start_region_idx; region_idx < end_region_idx; ++region_idx) {
2109 size_t cur_partial_obj_size = sd.region(region_idx)->partial_obj_size();
2110 accumulated_size += cur_partial_obj_size;
2111 if (cur_partial_obj_size != ParallelCompactData::RegionSize) {
2112 break;
2113 }
2114 }
2115 return region_start_addr + accumulated_size;
2116 }
2117
2118 // Use region_idx as the destination region, and evacuate all live objs on its
2119 // source regions to this destination region.
2120 void PSParallelCompact::fill_region(ParCompactionManager* cm, MoveAndUpdateClosure& closure, size_t region_idx)
2121 {
2122 ParMarkBitMap* const bitmap = mark_bitmap();
2123 ParallelCompactData& sd = summary_data();
2124 RegionData* const region_ptr = sd.region(region_idx);
2125
2126 // Get the source region and related info.
2127 size_t src_region_idx = region_ptr->source_region();
2128 SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
2129 HeapWord* src_space_top = _space_info[src_space_id].space()->top();
2130 HeapWord* dest_addr = sd.region_to_addr(region_idx);
2131
2132 closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
2133
2134 // Adjust src_region_idx to prepare for decrementing destination counts (the
2135 // destination count is not decremented when a region is copied to itself).
2136 if (src_region_idx == region_idx) {
2137 src_region_idx += 1;
2138 }
2139
2140 // source-region:
2141 //
2142 // **********
2143 // | ~~~ |
2144 // **********
2145 // ^
2146 // |-- closure.source() / first_src_addr
2147 //
2148 //
2149 // ~~~ : live words
2150 //
2151 // destination-region:
2152 //
2153 // **********
2154 // | |
2155 // **********
2156 // ^
2157 // |-- region-start
2158 if (bitmap->is_unmarked(closure.source())) {
2159 // An object overflows the previous destination region, so this
2160 // destination region should copy the remainder of the object or as much as
2161 // will fit.
2162 HeapWord* const old_src_addr = closure.source();
2163 {
2164 HeapWord* region_start = sd.region_align_down(closure.source());
2165 HeapWord* obj_start = bitmap->find_obj_beg_reverse(region_start, closure.source());
2166 HeapWord* obj_end;
2167 if (obj_start != closure.source()) {
2168 assert(bitmap->is_marked(obj_start), "inv");
2169 // Found the actual obj-start, try to find the obj-end using either
2170 // size() if this obj is completely contained in the current region.
2171 HeapWord* next_region_start = region_start + ParallelCompactData::RegionSize;
2172 HeapWord* partial_obj_start = (next_region_start >= src_space_top)
2173 ? nullptr
2174 : sd.addr_to_region_ptr(next_region_start)->partial_obj_addr();
2175 // This obj extends to next region iff partial_obj_addr of the *next*
2176 // region is the same as obj-start.
2177 if (partial_obj_start == obj_start) {
2178 // This obj extends to next region.
2179 obj_end = partial_obj_end(next_region_start);
2180 } else {
2181 // Completely contained in this region; safe to use size().
2182 obj_end = obj_start + cast_to_oop(obj_start)->size();
2183 }
2184 } else {
2185 // This obj extends to current region.
2186 obj_end = partial_obj_end(region_start);
2187 }
2188 size_t partial_obj_size = pointer_delta(obj_end, closure.source());
2189 closure.copy_partial_obj(partial_obj_size);
2190 }
2191
2192 if (closure.is_full()) {
2193 decrement_destination_counts(cm, src_space_id, src_region_idx, closure.source());
2194 closure.complete_region(dest_addr, region_ptr);
2195 return;
2196 }
2197
2198 // Finished copying without using up the current destination-region
2199 HeapWord* const end_addr = sd.region_align_down(closure.source());
2200 if (sd.region_align_down(old_src_addr) != end_addr) {
2201 assert(sd.region_align_up(old_src_addr) == end_addr, "only one region");
2202 // The partial object was copied from more than one source region.
2203 decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2204
2205 // Move to the next source region, possibly switching spaces as well. All
2206 // args except end_addr may be modified.
2207 src_region_idx = next_src_region(closure, src_space_id, src_space_top, end_addr);
2208 }
2209 }
2210
2211 // Handle the rest obj-by-obj, where we know obj-start.
2212 do {
2213 HeapWord* cur_addr = closure.source();
2214 HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
2215 src_space_top);
2216 // To handle the case where the final obj in source region extends to next region.
2217 HeapWord* final_obj_start = (end_addr == src_space_top)
2218 ? nullptr
2219 : sd.addr_to_region_ptr(end_addr)->partial_obj_addr();
2220 // Apply closure on objs inside [cur_addr, end_addr)
2221 do {
2222 cur_addr = bitmap->find_obj_beg(cur_addr, end_addr);
2223 if (cur_addr == end_addr) {
2224 break;
2225 }
2226 size_t obj_size;
2227 if (final_obj_start == cur_addr) {
2228 obj_size = pointer_delta(partial_obj_end(end_addr), cur_addr);
2229 } else {
2230 // This obj doesn't extend into next region; size() is safe to use.
2231 obj_size = cast_to_oop(cur_addr)->size();
2232 }
2233 closure.do_addr(cur_addr, obj_size);
2234 cur_addr += obj_size;
2235 } while (cur_addr < end_addr && !closure.is_full());
2236
2237 if (closure.is_full()) {
2238 decrement_destination_counts(cm, src_space_id, src_region_idx, closure.source());
2239 closure.complete_region(dest_addr, region_ptr);
2240 return;
2241 }
2242
2243 decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2244
2245 // Move to the next source region, possibly switching spaces as well. All
2246 // args except end_addr may be modified.
2247 src_region_idx = next_src_region(closure, src_space_id, src_space_top, end_addr);
2248 } while (true);
2249 }
2250
2251 void PSParallelCompact::fill_and_update_region(ParCompactionManager* cm, size_t region_idx)
2252 {
2253 MoveAndUpdateClosure cl(mark_bitmap(), region_idx);
2254 fill_region(cm, cl, region_idx);
2255 }
2256
2257 void PSParallelCompact::fill_and_update_shadow_region(ParCompactionManager* cm, size_t region_idx)
2258 {
2259 // Get a shadow region first
2260 ParallelCompactData& sd = summary_data();
2261 RegionData* const region_ptr = sd.region(region_idx);
2262 size_t shadow_region = ParCompactionManager::pop_shadow_region_mt_safe(region_ptr);
2263 // The InvalidShadow return value indicates the corresponding heap region is available,
2264 // so use MoveAndUpdateClosure to fill the normal region. Otherwise, use
2265 // MoveAndUpdateShadowClosure to fill the acquired shadow region.
2266 if (shadow_region == ParCompactionManager::InvalidShadow) {
2267 MoveAndUpdateClosure cl(mark_bitmap(), region_idx);
2268 region_ptr->shadow_to_normal();
2269 return fill_region(cm, cl, region_idx);
2270 } else {
2271 MoveAndUpdateShadowClosure cl(mark_bitmap(), region_idx, shadow_region);
2272 return fill_region(cm, cl, region_idx);
2273 }
2274 }
2275
2276 void PSParallelCompact::copy_back(HeapWord *shadow_addr, HeapWord *region_addr)
2277 {
2278 Copy::aligned_conjoint_words(shadow_addr, region_addr, _summary_data.RegionSize);
2279 }
2280
2281 bool PSParallelCompact::steal_unavailable_region(ParCompactionManager* cm, size_t ®ion_idx)
2282 {
2283 size_t next = cm->next_shadow_region();
2284 ParallelCompactData& sd = summary_data();
2285 size_t old_new_top = sd.addr_to_region_idx(_space_info[old_space_id].new_top());
2286 uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2287
2288 while (next < old_new_top) {
2289 if (sd.region(next)->mark_shadow()) {
2290 region_idx = next;
2291 return true;
2292 }
2293 next = cm->move_next_shadow_region_by(active_gc_threads);
2294 }
2295
2296 return false;
2297 }
2298
2299 // The shadow region is an optimization to address region dependencies in full GC. The basic
2300 // idea is making more regions available by temporally storing their live objects in empty
2301 // shadow regions to resolve dependencies between them and the destination regions. Therefore,
2302 // GC threads need not wait destination regions to be available before processing sources.
2303 //
2304 // A typical workflow would be:
2305 // After draining its own stack and failing to steal from others, a GC worker would pick an
2306 // unavailable region (destination count > 0) and get a shadow region. Then the worker fills
2307 // the shadow region by copying live objects from source regions of the unavailable one. Once
2308 // the unavailable region becomes available, the data in the shadow region will be copied back.
2309 // Shadow regions are empty regions in the to-space and regions between top and end of other spaces.
2310 void PSParallelCompact::initialize_shadow_regions(uint parallel_gc_threads)
2311 {
2312 const ParallelCompactData& sd = PSParallelCompact::summary_data();
2313
2314 for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2315 SpaceInfo* const space_info = _space_info + id;
2316 MutableSpace* const space = space_info->space();
2317
2318 const size_t beg_region =
2319 sd.addr_to_region_idx(sd.region_align_up(MAX2(space_info->new_top(), space->top())));
2320 const size_t end_region =
2321 sd.addr_to_region_idx(sd.region_align_down(space->end()));
2322
2323 for (size_t cur = beg_region; cur < end_region; ++cur) {
2324 ParCompactionManager::push_shadow_region(cur);
2325 }
2326 }
2327
2328 size_t beg_region = sd.addr_to_region_idx(_space_info[old_space_id].dense_prefix());
2329 for (uint i = 0; i < parallel_gc_threads; i++) {
2330 ParCompactionManager *cm = ParCompactionManager::gc_thread_compaction_manager(i);
2331 cm->set_next_shadow_region(beg_region + i);
2332 }
2333 }
2334
2335 void MoveAndUpdateClosure::copy_partial_obj(size_t partial_obj_size)
2336 {
2337 size_t words = MIN2(partial_obj_size, words_remaining());
2338
2339 // This test is necessary; if omitted, the pointer updates to a partial object
2340 // that crosses the dense prefix boundary could be overwritten.
2341 if (source() != copy_destination()) {
2342 DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2343 Copy::aligned_conjoint_words(source(), copy_destination(), words);
2344 }
2345 update_state(words);
2346 }
2347
2348 void MoveAndUpdateClosure::complete_region(HeapWord* dest_addr, PSParallelCompact::RegionData* region_ptr) {
2349 assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::NormalRegion, "Region should be finished");
2350 region_ptr->set_completed();
2351 }
2352
2353 void MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
2354 assert(destination() != nullptr, "sanity");
2355 _source = addr;
2356
2357 // The start_array must be updated even if the object is not moving.
2358 if (_start_array != nullptr) {
2359 _start_array->update_for_block(destination(), destination() + words);
2360 }
2361
2362 // Avoid overflow
2363 words = MIN2(words, words_remaining());
2364 assert(words > 0, "inv");
2365
2366 if (copy_destination() != source()) {
2367 DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
2368 assert(source() != destination(), "inv");
2369 assert(FullGCForwarding::is_forwarded(cast_to_oop(source())), "inv");
2370 assert(FullGCForwarding::forwardee(cast_to_oop(source())) == cast_to_oop(destination()), "inv");
2371 Copy::aligned_conjoint_words(source(), copy_destination(), words);
2372 cast_to_oop(copy_destination())->init_mark();
2373 }
2374
2375 update_state(words);
2376 }
2377
2378 void MoveAndUpdateShadowClosure::complete_region(HeapWord* dest_addr, PSParallelCompact::RegionData* region_ptr) {
2379 assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::ShadowRegion, "Region should be shadow");
2380 // Record the shadow region index
2381 region_ptr->set_shadow_region(_shadow);
2382 // Mark the shadow region as filled to indicate the data is ready to be
2383 // copied back
2384 region_ptr->mark_filled();
2385 // Try to copy the content of the shadow region back to its corresponding
2386 // heap region if available; the GC thread that decreases the destination
2387 // count to zero will do the copying otherwise (see
2388 // PSParallelCompact::decrement_destination_counts).
2389 if (((region_ptr->available() && region_ptr->claim()) || region_ptr->claimed()) && region_ptr->mark_copied()) {
2390 region_ptr->set_completed();
2391 PSParallelCompact::copy_back(PSParallelCompact::summary_data().region_to_addr(_shadow), dest_addr);
2392 ParCompactionManager::push_shadow_region_mt_safe(_shadow);
2393 }
2394 }