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