1 /*
  2  * Copyright (c) 2014, 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 "gc/g1/g1Allocator.inline.hpp"
 26 #include "gc/g1/g1CollectedHeap.inline.hpp"
 27 #include "gc/g1/g1CollectionSet.hpp"
 28 #include "gc/g1/g1EvacFailureRegions.inline.hpp"
 29 #include "gc/g1/g1HeapRegionPrinter.hpp"
 30 #include "gc/g1/g1OopClosures.inline.hpp"
 31 #include "gc/g1/g1ParScanThreadState.inline.hpp"
 32 #include "gc/g1/g1RootClosures.hpp"
 33 #include "gc/g1/g1StringDedup.hpp"
 34 #include "gc/g1/g1Trace.hpp"
 35 #include "gc/g1/g1YoungGCAllocationFailureInjector.inline.hpp"
 36 #include "gc/shared/continuationGCSupport.inline.hpp"
 37 #include "gc/shared/partialArraySplitter.inline.hpp"
 38 #include "gc/shared/partialArrayState.hpp"
 39 #include "gc/shared/partialArrayTaskStats.hpp"
 40 #include "gc/shared/stringdedup/stringDedup.hpp"
 41 #include "gc/shared/taskqueue.inline.hpp"
 42 #include "memory/allocation.inline.hpp"
 43 #include "oops/access.inline.hpp"
 44 #include "oops/oop.inline.hpp"
 45 #include "runtime/mutexLocker.hpp"
 46 #include "runtime/prefetch.inline.hpp"
 47 #include "utilities/globalDefinitions.hpp"
 48 #include "utilities/macros.hpp"
 49 
 50 // In fastdebug builds the code size can get out of hand, potentially
 51 // tripping over compiler limits (which may be bugs, but nevertheless
 52 // need to be taken into consideration).  A side benefit of limiting
 53 // inlining is that we get more call frames that might aid debugging.
 54 // And the fastdebug compile time for this file is much reduced.
 55 // Explicit NOINLINE to block ATTRIBUTE_FLATTENing.
 56 #define MAYBE_INLINE_EVACUATION NOT_DEBUG(inline) DEBUG_ONLY(NOINLINE)
 57 
 58 // Good estimate for the initial table size.
 59 static uint initial_nmethod_table_size(G1CollectedHeap* g1h) {
 60   // The +1 is both to consider the retained old region likely to be added, and avoid zero-sized initial tables.
 61   return MIN3(g1h->collection_set()->num_regions(), g1h->max_num_regions() / 2, g1h->num_available_regions()) + 1;
 62 }
 63 
 64 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h,
 65                                            G1ParScanThreadStateSet* per_thread_states,
 66                                            uint worker_id,
 67                                            uint num_workers,
 68                                            G1CollectionSet* collection_set,
 69                                            G1EvacFailureRegions* evac_failure_regions)
 70   : _g1h(g1h),
 71     _per_thread_states(per_thread_states),
 72     _task_queue(g1h->task_queue(worker_id)),
 73     _ct(g1h->refinement_table()),
 74     _closures(nullptr),
 75     _plab_allocator(nullptr),
 76     _age_table(false),
 77     _tenuring_threshold(g1h->policy()->tenuring_threshold()),
 78     _scanner(g1h, this),
 79     _worker_id(worker_id),
 80     _num_cards_marked_dirty(0),
 81     _num_cards_marked_to_cset(0),
 82     _stack_trim_upper_threshold(GCDrainStackTargetSize * 2 + 1),
 83     _stack_trim_lower_threshold(GCDrainStackTargetSize),
 84     _trim_ticks(),
 85     _surviving_young_words_base(nullptr),
 86     _surviving_young_words(nullptr),
 87     _surviving_words_length(collection_set->num_young_regions() + 1),
 88     _old_gen_is_full(false),
 89     _partial_array_splitter(g1h->partial_array_state_manager(), num_workers),
 90     _string_dedup_requests(),
 91     _max_num_optional_regions(collection_set->num_optional_regions()),
 92     _numa(g1h->numa()),
 93     _obj_alloc_stat(nullptr),
 94     // The initial size estimate is relatively conservative, assuming that all regions
 95     // in the collection set get evacuated into the same amount of new regions.
 96     _nmethods_to_add(initial_nmethod_table_size(g1h),
 97                      MAX2(initial_nmethod_table_size(g1h), _g1h->max_num_regions() / 2)),
 98     ALLOCATION_FAILURE_INJECTOR_ONLY(_allocation_failure_inject_counter(0) COMMA)
 99     _evacuation_failed_info(),
100     _evac_failure_regions(evac_failure_regions),
101     _num_cards_from_evac_failure(0)
102 {
103   // We allocate number of young gen regions in the collection set plus one
104   // entries, since entry 0 keeps track of surviving bytes for non-young regions.
105   // We also add a few elements at the beginning and at the end in
106   // an attempt to eliminate cache contention
107   const size_t padding_elem_num = (DEFAULT_PADDING_SIZE / sizeof(size_t));
108   size_t array_length = padding_elem_num + _surviving_words_length + padding_elem_num;
109 
110   _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length, mtGC);
111   _surviving_young_words = _surviving_young_words_base + padding_elem_num;
112   memset(_surviving_young_words, 0, _surviving_words_length * sizeof(size_t));
113 
114   _plab_allocator = new G1PLABAllocator(_g1h->allocator());
115 
116   _closures = G1EvacuationRootClosures::create_root_closures(_g1h,
117                                                              this,
118                                                              collection_set->only_contains_young_regions());
119 
120   _oops_into_optional_regions = new G1OopStarChunkedList[_max_num_optional_regions];
121 
122   initialize_numa_stats();
123 }
124 
125 size_t G1ParScanThreadState::flush_stats(size_t* surviving_young_words, uint num_workers) {
126   flush_numa_stats();
127   // Update allocation statistics.
128   _plab_allocator->flush_and_retire_stats(num_workers);
129   _g1h->policy()->record_age_table(&_age_table);
130 
131   if (_evacuation_failed_info.has_failed()) {
132     _g1h->gc_tracer_stw()->report_evacuation_failed(_evacuation_failed_info);
133   }
134 
135   size_t sum = 0;
136   for (uint i = 0; i < _surviving_words_length; i++) {
137     surviving_young_words[i] += _surviving_young_words[i];
138     sum += _surviving_young_words[i];
139   }
140   return sum;
141 }
142 
143 G1ParScanThreadState::~G1ParScanThreadState() {
144   auto delete_all = [&] (uint region, G1NmethodSet* nmethods) -> bool {
145     delete nmethods;
146     return true;
147   };
148   _nmethods_to_add.iterate(delete_all);
149 
150   delete _plab_allocator;
151   delete _closures;
152   FREE_C_HEAP_ARRAY(_surviving_young_words_base);
153   delete[] _oops_into_optional_regions;
154   FREE_C_HEAP_ARRAY(_obj_alloc_stat);
155 }
156 
157 size_t G1ParScanThreadState::lab_waste_words() const {
158   return _plab_allocator->waste();
159 }
160 
161 size_t G1ParScanThreadState::lab_undo_waste_words() const {
162   return _plab_allocator->undo_waste();
163 }
164 
165 size_t G1ParScanThreadState::num_cards_pending() const {
166   return _num_cards_marked_dirty + _num_cards_from_evac_failure;
167 }
168 
169 size_t G1ParScanThreadState::num_cards_marked() const {
170   return num_cards_pending() + _num_cards_marked_to_cset;
171 }
172 
173 size_t G1ParScanThreadState::num_cards_from_evac_failure() const {
174   return _num_cards_from_evac_failure;
175 }
176 
177 #ifdef ASSERT
178 void G1ParScanThreadState::verify_task(narrowOop* task) const {
179   assert(task != nullptr, "invariant");
180   assert(UseCompressedOops, "sanity");
181   oop p = RawAccess<>::oop_load(task);
182   assert(_g1h->is_in_reserved(p),
183          "task=" PTR_FORMAT " p=" PTR_FORMAT, p2i(task), p2i(p));
184 }
185 
186 void G1ParScanThreadState::verify_task(oop* task) const {
187   assert(task != nullptr, "invariant");
188   oop p = RawAccess<>::oop_load(task);
189   assert(_g1h->is_in_reserved(p),
190          "task=" PTR_FORMAT " p=" PTR_FORMAT, p2i(task), p2i(p));
191 }
192 
193 void G1ParScanThreadState::verify_task(PartialArrayState* task) const {
194   assert(task != nullptr, "invariant");
195   // Source isn't used for processing, so not recorded in task.
196   assert(task->source() == nullptr, "invariant");
197   oop p = task->destination();
198   assert(_g1h->is_in_reserved(p),
199          "task=" PTR_FORMAT " dest=" PTR_FORMAT, p2i(task), p2i(p));
200 }
201 
202 void G1ParScanThreadState::verify_task(ScannerTask task) const {
203   if (task.is_narrow_oop_ptr()) {
204     verify_task(task.to_narrow_oop_ptr());
205   } else if (task.is_oop_ptr()) {
206     verify_task(task.to_oop_ptr());
207   } else if (task.is_partial_array_state()) {
208     verify_task(task.to_partial_array_state());
209   } else {
210     ShouldNotReachHere();
211   }
212 }
213 #endif // ASSERT
214 
215 template <class T>
216 MAYBE_INLINE_EVACUATION
217 void G1ParScanThreadState::do_oop_evac(T* p) {
218   // Reference should not be null here as such are never pushed to the task queue.
219   oop obj = RawAccess<IS_NOT_NULL>::oop_load(p);
220 
221   // Although we never intentionally push references outside of the collection
222   // set, due to (benign) races in the claim mechanism during RSet scanning more
223   // than one thread might claim the same card. So the same card may be
224   // processed multiple times, and so we might get references into old gen here.
225   // So we need to redo this check.
226   const G1HeapRegionAttr region_attr = _g1h->region_attr(obj);
227   // References pushed onto the work stack should never point to a humongous region
228   // as they are not added to the collection set due to above precondition.
229   assert(!region_attr.is_humongous_candidate(),
230          "Obj " PTR_FORMAT " should not refer to humongous region %u from " PTR_FORMAT,
231          p2i(obj), _g1h->addr_to_region(obj), p2i(p));
232 
233   if (!region_attr.is_in_cset()) {
234     // In this case somebody else already did all the work.
235     return;
236   }
237 
238   markWord m = obj->mark();
239   if (m.is_forwarded()) {
240     obj = obj->forwardee(m);
241   } else {
242     obj = do_copy_to_survivor_space(region_attr, obj, m);
243   }
244   RawAccess<IS_NOT_NULL>::oop_store(p, obj);
245 
246   write_ref_field_post(p, obj);
247 }
248 
249 ALWAYSINLINE
250 void G1ParScanThreadState::process_array_chunk(objArrayOop obj, size_t start, size_t end) {
251   obj->oop_iterate_elements_range(&_scanner,
252                                   checked_cast<int>(start),
253                                   checked_cast<int>(end));
254 }
255 
256 MAYBE_INLINE_EVACUATION
257 void G1ParScanThreadState::do_partial_array(PartialArrayState* state, bool stolen) {
258   // Access state before release by claim().
259   objArrayOop to_array = objArrayOop(state->destination());
260   PartialArraySplitter::Claim claim =
261     _partial_array_splitter.claim(state, _task_queue, stolen);
262   G1HeapRegionAttr dest_attr = _g1h->region_attr(to_array);
263   G1SkipCardMarkSetter x(&_scanner, dest_attr.is_new_survivor());
264   // Process claimed task.
265   assert(to_array->is_objArray(), "Must be");
266   process_array_chunk(to_array, claim._start, claim._end);
267 }
268 
269 MAYBE_INLINE_EVACUATION
270 void G1ParScanThreadState::start_partial_objarray(oop from_obj,
271                                                   oop to_obj) {
272   assert(from_obj->is_forwarded(), "precondition");
273   assert(from_obj->forwardee() == to_obj, "precondition");
274   assert(to_obj->is_objArray(), "precondition");
275   assert(!_scanner.do_metadata(), "precondition");
276   assert(_scanner.skip_card_mark_set(), "precondition");
277 
278   objArrayOop to_array = objArrayOop(to_obj);
279   size_t array_length = to_array->length();
280   size_t initial_chunk_size =
281     // The source array is unused when processing states.
282     _partial_array_splitter.start(_task_queue, nullptr, to_array, array_length, ParGCArrayScanChunk);
283 
284   process_array_chunk(to_array, 0, initial_chunk_size);
285 }
286 
287 MAYBE_INLINE_EVACUATION
288 void G1ParScanThreadState::dispatch_task(ScannerTask task, bool stolen) {
289   verify_task(task);
290   if (task.is_narrow_oop_ptr()) {
291     do_oop_evac(task.to_narrow_oop_ptr());
292   } else if (task.is_oop_ptr()) {
293     do_oop_evac(task.to_oop_ptr());
294   } else {
295     do_partial_array(task.to_partial_array_state(), stolen);
296   }
297 }
298 
299 // Process tasks until overflow queue is empty and local queue
300 // contains no more than threshold entries.  NOINLINE to prevent
301 // inlining into steal_and_trim_queue.
302 ATTRIBUTE_FLATTEN NOINLINE
303 void G1ParScanThreadState::trim_queue_to_threshold(uint threshold) {
304   ScannerTask task;
305   do {
306     while (_task_queue->pop_overflow(task)) {
307       if (!_task_queue->try_push_to_taskqueue(task)) {
308         dispatch_task(task, false);
309       }
310     }
311     while (_task_queue->pop_local(task, threshold)) {
312       dispatch_task(task, false);
313     }
314   } while (!_task_queue->overflow_empty());
315 }
316 
317 ATTRIBUTE_FLATTEN
318 void G1ParScanThreadState::steal_and_trim_queue(G1ScannerTasksQueueSet* task_queues) {
319   ScannerTask stolen_task;
320   while (task_queues->steal(_worker_id, stolen_task)) {
321     dispatch_task(stolen_task, true);
322     // Processing stolen task may have added tasks to our queue.
323     trim_queue();
324   }
325 }
326 
327 HeapWord* G1ParScanThreadState::allocate_in_next_plab(G1HeapRegionAttr* dest,
328                                                       size_t word_sz,
329                                                       bool previous_plab_refill_failed,
330                                                       uint node_index) {
331 
332   assert(dest->is_in_cset_or_humongous_candidate(), "Unexpected dest: %s region attr", dest->get_type_str());
333 
334   // Right now we only have two types of regions (young / old) so
335   // let's keep the logic here simple. We can generalize it when necessary.
336   if (dest->is_young()) {
337     bool plab_refill_in_old_failed = false;
338     HeapWord* const obj_ptr = _plab_allocator->allocate(G1HeapRegionAttr::Old,
339                                                         word_sz,
340                                                         &plab_refill_in_old_failed,
341                                                         node_index);
342     // Make sure that we won't attempt to copy any other objects out
343     // of a survivor region (given that apparently we cannot allocate
344     // any new ones) to avoid coming into this slow path again and again.
345     // Only consider failed PLAB refill here: failed inline allocations are
346     // typically large, so not indicative of remaining space.
347     if (previous_plab_refill_failed) {
348       _tenuring_threshold = 0;
349     }
350 
351     if (obj_ptr != nullptr) {
352       dest->set_old();
353     } else {
354       // We just failed to allocate in old gen. The same idea as explained above
355       // for making survivor gen unavailable for allocation applies for old gen.
356       _old_gen_is_full = plab_refill_in_old_failed;
357     }
358     return obj_ptr;
359   } else {
360     _old_gen_is_full = previous_plab_refill_failed;
361     assert(dest->is_old(), "Unexpected dest region attr: %s", dest->get_type_str());
362     // no other space to try.
363     return nullptr;
364   }
365 }
366 
367 G1HeapRegionAttr G1ParScanThreadState::next_region_attr(G1HeapRegionAttr const region_attr, markWord const m, uint& age) {
368   assert(region_attr.is_young() || region_attr.is_old(), "must be either Young or Old");
369 
370   if (region_attr.is_young()) {
371     age = !m.has_displaced_mark_helper() ? m.age()
372                                          : m.displaced_mark_helper().age();
373     if (age < _tenuring_threshold) {
374       return region_attr;
375     }
376   }
377   // young-to-old (promotion) or old-to-old; destination is old in both cases.
378   return G1HeapRegionAttr::Old;
379 }
380 
381 void G1ParScanThreadState::report_promotion_event(G1HeapRegionAttr const dest_attr,
382                                                   Klass* klass, size_t word_sz, uint age,
383                                                   HeapWord * const obj_ptr, uint node_index) const {
384   PLAB* alloc_buf = _plab_allocator->alloc_buffer(dest_attr, node_index);
385   if (alloc_buf->contains(obj_ptr)) {
386     _g1h->gc_tracer_stw()->report_promotion_in_new_plab_event(klass, word_sz * HeapWordSize, age,
387                                                               dest_attr.type() == G1HeapRegionAttr::Old,
388                                                               alloc_buf->word_sz() * HeapWordSize);
389   } else {
390     _g1h->gc_tracer_stw()->report_promotion_outside_plab_event(klass, word_sz * HeapWordSize, age,
391                                                                dest_attr.type() == G1HeapRegionAttr::Old);
392   }
393 }
394 
395 NOINLINE
396 HeapWord* G1ParScanThreadState::allocate_copy_slow(G1HeapRegionAttr* dest_attr,
397                                                    Klass* klass,
398                                                    size_t word_sz,
399                                                    uint age,
400                                                    uint node_index) {
401   HeapWord* obj_ptr = nullptr;
402   // Try slow-path allocation unless we're allocating old and old is already full.
403   if (!(dest_attr->is_old() && _old_gen_is_full)) {
404     bool plab_refill_failed = false;
405     obj_ptr = _plab_allocator->allocate_direct_or_new_plab(*dest_attr,
406                                                            word_sz,
407                                                            &plab_refill_failed,
408                                                            node_index);
409     if (obj_ptr == nullptr) {
410       obj_ptr = allocate_in_next_plab(dest_attr,
411                                       word_sz,
412                                       plab_refill_failed,
413                                       node_index);
414     }
415   }
416   if (obj_ptr != nullptr) {
417     update_numa_stats(node_index);
418     if (_g1h->gc_tracer_stw()->should_report_promotion_events()) {
419       // The events are checked individually as part of the actual commit
420       report_promotion_event(*dest_attr, klass, word_sz, age, obj_ptr, node_index);
421     }
422   }
423   return obj_ptr;
424 }
425 
426 #if ALLOCATION_FAILURE_INJECTOR
427 bool G1ParScanThreadState::inject_allocation_failure(uint region_idx) {
428   return _g1h->allocation_failure_injector()->allocation_should_fail(_allocation_failure_inject_counter, region_idx);
429 }
430 #endif
431 
432 NOINLINE
433 void G1ParScanThreadState::undo_allocation(G1HeapRegionAttr dest_attr,
434                                            HeapWord* obj_ptr,
435                                            size_t word_sz,
436                                            uint node_index) {
437   _plab_allocator->undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
438 }
439 
440 void G1ParScanThreadState::update_bot_after_copying(oop obj, size_t word_sz) {
441   HeapWord* obj_start = cast_from_oop<HeapWord*>(obj);
442   G1HeapRegion* region = _g1h->heap_region_containing(obj_start);
443   region->update_bot_for_block(obj_start, obj_start + word_sz);
444 }
445 
446 ALWAYSINLINE
447 void G1ParScanThreadState::do_iterate_object(oop const obj,
448                                              oop const old,
449                                              Klass* const klass,
450                                              G1HeapRegionAttr const region_attr,
451                                              G1HeapRegionAttr const dest_attr,
452                                              uint age) {
453     // Most objects are not arrays, so do one array check rather than
454     // checking for each array category for each object.
455     if (klass->is_array_klass()) {
456       assert(!klass->is_stack_chunk_instance_klass(), "must be");
457 
458       if (klass->is_objArray_klass()) {
459         start_partial_objarray(old, obj);
460       } else {
461         // Nothing needs to be done for typeArrays.  Body doesn't contain
462         // any oops to scan, and the type in the klass will already be handled
463         // by processing the built-in module.
464         assert(klass->is_typeArray_klass(), "invariant");
465       }
466       return;
467     }
468 
469     ContinuationGCSupport::transform_stack_chunk(obj, klass);
470 
471     // Check for deduplicating young Strings.
472     if (G1StringDedup::is_candidate_from_evacuation(klass,
473                                                     region_attr,
474                                                     dest_attr,
475                                                     age)) {
476       // Record old; request adds a new weak reference, which reference
477       // processing expects to refer to a from-space object.
478       _string_dedup_requests.add(old);
479     }
480 
481     assert(_scanner.skip_card_mark_set(), "must be");
482     obj->oop_iterate_backwards(&_scanner, klass);
483 }
484 
485 // Private inline function, for direct internal use and providing the
486 // implementation of the public not-inline function.
487 MAYBE_INLINE_EVACUATION
488 oop G1ParScanThreadState::do_copy_to_survivor_space(G1HeapRegionAttr const region_attr,
489                                                     oop const old,
490                                                     markWord const old_mark) {
491   assert(region_attr.is_in_cset(),
492          "Unexpected region attr type: %s", region_attr.get_type_str());
493 
494   // NOTE: With compact headers, it is not safe to load the Klass* from old, because
495   // that would access the mark-word, that might change at any time by concurrent
496   // workers.
497   // This mark word would refer to a forwardee, which may not yet have completed
498   // copying. Therefore we must load the Klass* from the mark-word that we already
499   // loaded. This is safe, because we only enter here if not yet forwarded.
500   assert(!old_mark.is_forwarded(), "precondition");
501   Klass* klass = UseCompactObjectHeaders
502       ? old_mark.klass()
503       : old->klass();
504 
505   const size_t word_sz = old->size_given_klass(klass);
506 
507   // JNI only allows pinning of typeArrays, so we only need to keep those in place.
508   if (region_attr.is_pinned() && klass->is_typeArray_klass()) {
509     return handle_evacuation_failure_par(old, old_mark, klass, region_attr, word_sz, true /* cause_pinned */);
510   }
511 
512   uint age = 0;
513   G1HeapRegionAttr dest_attr = next_region_attr(region_attr, old_mark, age);
514   G1HeapRegion* const from_region = _g1h->heap_region_containing(old);
515   uint node_index = from_region->node_index();
516 
517   HeapWord* obj_ptr = _plab_allocator->plab_allocate(dest_attr, word_sz, node_index);
518 
519   // PLAB allocations should succeed most of the time, so we'll
520   // normally check against null once and that's it.
521   if (obj_ptr == nullptr) {
522     obj_ptr = allocate_copy_slow(&dest_attr, klass, word_sz, age, node_index);
523     if (obj_ptr == nullptr) {
524       // This will either forward-to-self, or detect that someone else has
525       // installed a forwarding pointer.
526       return handle_evacuation_failure_par(old, old_mark, klass, region_attr, word_sz, false /* cause_pinned */);
527     }
528   }
529 
530   assert(obj_ptr != nullptr, "when we get here, allocation should have succeeded");
531   assert(_g1h->is_in_reserved(obj_ptr), "Allocated memory should be in the heap");
532 
533   // Should this evacuation fail?
534   if (inject_allocation_failure(from_region->hrm_index())) {
535     // Doing this after all the allocation attempts also tests the
536     // undo_allocation() method too.
537     undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
538     return handle_evacuation_failure_par(old, old_mark, klass, region_attr, word_sz, false /* cause_pinned */);
539   }
540 
541   // We're going to allocate linearly, so might as well prefetch ahead.
542   Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
543   Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(old), obj_ptr, word_sz);
544 
545   const oop obj = cast_to_oop(obj_ptr);
546   // Because the forwarding is done with memory_order_relaxed there is no
547   // ordering with the above copy.  Clients that get the forwardee must not
548   // examine its contents without other synchronization, since the contents
549   // may not be up to date for them.
550   const oop forward_ptr = old->forward_to_atomic(obj, old_mark, memory_order_relaxed);
551   if (forward_ptr == nullptr) {
552 
553     {
554       const uint young_index = from_region->young_index_in_cset();
555       assert((from_region->is_young() && young_index >  0) ||
556              (!from_region->is_young() && young_index == 0), "invariant" );
557       _surviving_young_words[young_index] += word_sz;
558     }
559 
560     if (dest_attr.is_young()) {
561       if (age < markWord::max_age) {
562         age++;
563         obj->incr_age();
564       }
565       _age_table.add(age, word_sz);
566     } else {
567       update_bot_after_copying(obj, word_sz);
568     }
569 
570     {
571       // Skip the card enqueue iff the object (obj) is in survivor region.
572       // However, G1HeapRegion::is_survivor() is too expensive here.
573       // Instead, we use dest_attr.is_young() because the two values are always
574       // equal: successfully allocated young regions must be survivor regions.
575       assert(dest_attr.is_young() == _g1h->heap_region_containing(obj)->is_survivor(), "must be");
576       G1SkipCardMarkSetter x(&_scanner, dest_attr.is_young());
577       do_iterate_object(obj, old, klass, region_attr, dest_attr, age);
578     }
579 
580     return obj;
581   } else {
582     _plab_allocator->undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
583     return forward_ptr;
584   }
585 }
586 
587 // Public not-inline entry point.
588 ATTRIBUTE_FLATTEN
589 oop G1ParScanThreadState::copy_to_survivor_space(G1HeapRegionAttr region_attr,
590                                                  oop old,
591                                                  markWord old_mark) {
592   return do_copy_to_survivor_space(region_attr, old, old_mark);
593 }
594 
595 G1ParScanThreadState* G1ParScanThreadStateSet::state_for_worker(uint worker_id) {
596   assert(worker_id < _num_workers, "out of bounds access");
597   if (_states[worker_id] == nullptr) {
598     _states[worker_id] =
599       new G1ParScanThreadState(_g1h,
600                                this,
601                                worker_id,
602                                _num_workers,
603                                _collection_set,
604                                _evac_failure_regions);
605   }
606   return _states[worker_id];
607 }
608 
609 const size_t* G1ParScanThreadStateSet::surviving_young_words() const {
610   assert(_flushed, "thread local state from the per thread states should have been flushed");
611   return _surviving_young_words_total;
612 }
613 
614 void G1ParScanThreadStateSet::flush_stats() {
615   assert(!_flushed, "thread local state from the per thread states should be flushed once");
616   for (uint worker_id = 0; worker_id < _num_workers; ++worker_id) {
617     G1ParScanThreadState* pss = _states[worker_id];
618     assert(pss != nullptr, "must be initialized");
619 
620     G1GCPhaseTimes* p = _g1h->phase_times();
621 
622     // Need to get the following two before the call to G1ParThreadScanState::flush()
623     // because it resets the PLAB allocator where we get this info from.
624     size_t lab_waste_bytes = pss->lab_waste_words() * HeapWordSize;
625     size_t lab_undo_waste_bytes = pss->lab_undo_waste_words() * HeapWordSize;
626     size_t copied_bytes = pss->flush_stats(_surviving_young_words_total, _num_workers) * HeapWordSize;
627     size_t pending_cards = pss->num_cards_pending();
628     size_t to_young_gen_cards = pss->num_cards_marked() - pss->num_cards_pending();
629     size_t evac_failure_cards = pss->num_cards_from_evac_failure();
630     size_t marked_cards = pss->num_cards_marked();
631 
632     p->record_or_add_thread_work_item(G1GCPhaseTimes::FlushPSS, worker_id, copied_bytes, G1GCPhaseTimes::FlushPSSCopiedBytes);
633     p->record_or_add_thread_work_item(G1GCPhaseTimes::FlushPSS, worker_id, lab_waste_bytes, G1GCPhaseTimes::FlushPSSLABWasteBytes);
634     p->record_or_add_thread_work_item(G1GCPhaseTimes::FlushPSS, worker_id, lab_undo_waste_bytes, G1GCPhaseTimes::FlushPSSLABUndoWasteBytes);
635     p->record_or_add_thread_work_item(G1GCPhaseTimes::FlushPSS, worker_id, pending_cards, G1GCPhaseTimes::FlushPSSPendingCards);
636     p->record_or_add_thread_work_item(G1GCPhaseTimes::FlushPSS, worker_id, to_young_gen_cards, G1GCPhaseTimes::FlushPSSToYoungGenCards);
637     p->record_or_add_thread_work_item(G1GCPhaseTimes::FlushPSS, worker_id, evac_failure_cards, G1GCPhaseTimes::FlushPSSEvacFail);
638     p->record_or_add_thread_work_item(G1GCPhaseTimes::FlushPSS, worker_id, marked_cards, G1GCPhaseTimes::FlushPSSMarked);
639   }
640 
641   _flushed = true;
642 }
643 
644 void G1ParScanThreadStateSet::destroy_worker_states() {
645   assert(_flushed, "statistics must already be flushed");
646   for (uint worker_id = 0; worker_id < _num_workers; ++worker_id) {
647     delete _states[worker_id];
648     _states[worker_id] = nullptr;
649   }
650 }
651 
652 void G1ParScanThreadStateSet::update_nmethod_regions_to_add(G1NmethodsToAdd* nmethods) {
653   if (nmethods->number_of_entries() == 0) {
654     return;
655   }
656 
657   // Take the key set, look which are not yet in the global set, and update the necessary ones.
658   ResourceMark rm;
659   GrowableArray<uint> regions_to_add = GrowableArray<uint>(nmethods->table_size());
660 
661   nmethods->iterate_all([&] (uint& region, void*) {
662     if (_has_nmethods_to_add.par_set_bit(region, memory_order_relaxed)) {
663       regions_to_add.push(region);
664     }
665   });
666 
667   uint num_regions_to_add = (uint)regions_to_add.length();
668 
669   if (num_regions_to_add == 0) {
670     return;
671   }
672 
673   uint first_index = _num_nmethod_regions_to_add.fetch_then_add(num_regions_to_add, memory_order_relaxed);
674   guarantee(first_index + num_regions_to_add <= _g1h->max_num_regions(), "must be");
675 
676   memcpy(&_nmethod_regions_to_add[first_index], regions_to_add.adr_at(0), num_regions_to_add * sizeof(uint));
677 }
678 
679 void G1ParScanThreadStateSet::par_iterate_nmethod_regions_to_add(G1HeapRegionClosure* cl,
680                                                                  G1HeapRegionClaimer* claimer,
681                                                                  uint worker_id) {
682   _g1h->par_iterate_regions_array(cl, claimer, _nmethod_regions_to_add, num_nmethod_regions_to_add(), worker_id);
683 }
684 
685 void G1ParScanThreadStateSet::record_unused_optional_region(G1HeapRegion* hr) {
686   for (uint worker_index = 0; worker_index < _num_workers; ++worker_index) {
687     G1ParScanThreadState* pss = _states[worker_index];
688     assert(pss != nullptr, "must be initialized");
689 
690     size_t used_memory = pss->oops_into_optional_region(hr)->used_memory();
691     _g1h->phase_times()->record_or_add_thread_work_item(G1GCPhaseTimes::OptScanHR, worker_index, used_memory, G1GCPhaseTimes::ScanHRUsedMemory);
692   }
693 }
694 
695 void G1ParScanThreadState::record_evacuation_failed_region(G1HeapRegion* r, uint worker_id, bool cause_pinned) {
696   if (_evac_failure_regions->record(worker_id, r->hrm_index(), cause_pinned)) {
697     G1HeapRegionPrinter::evac_failure(r);
698   }
699 }
700 
701 NOINLINE
702 oop G1ParScanThreadState::handle_evacuation_failure_par(oop old, markWord m, Klass* klass, G1HeapRegionAttr attr, size_t word_sz, bool cause_pinned) {
703   assert(_g1h->is_in_cset(old), "Object " PTR_FORMAT " should be in the CSet", p2i(old));
704 
705   oop forward_ptr = old->forward_to_self_atomic(m, memory_order_relaxed);
706   if (forward_ptr == nullptr) {
707     // Forward-to-self succeeded. We are the "owner" of the object.
708     G1HeapRegion* r = _g1h->heap_region_containing(old);
709 
710     record_evacuation_failed_region(r, _worker_id, cause_pinned);
711 
712     // Mark the failing object in the marking bitmap and later use the bitmap to handle
713     // evacuation failure recovery.
714     _g1h->mark_evac_failure_object(old);
715 
716     _evacuation_failed_info.register_copy_failure(word_sz);
717 
718     {
719       // For iterating objects that failed evacuation currently we can reuse the
720       // existing closure to scan evacuated objects; since we are iterating from a
721       // collection set region (i.e. never a Survivor region), we always need to
722       // gather cards for this case.
723       G1SkipCardMarkSetter x(&_scanner, false /* skip_card_mark */);
724       do_iterate_object(old, old, klass, attr, attr, m.age());
725     }
726 
727     return old;
728   } else {
729     // Forward-to-self failed. Either someone else managed to allocate
730     // space for this object (old != forward_ptr) or they beat us in
731     // self-forwarding it (old == forward_ptr).
732     assert(old == forward_ptr || !_g1h->is_in_cset(forward_ptr),
733            "Object " PTR_FORMAT " forwarded to: " PTR_FORMAT " "
734            "should not be in the CSet",
735            p2i(old), p2i(forward_ptr));
736     return forward_ptr;
737   }
738 }
739 
740 void G1ParScanThreadState::update_nmethod_regions_to_add() {
741   _per_thread_states->update_nmethod_regions_to_add(&_nmethods_to_add);
742 }
743 
744 void G1ParScanThreadState::initialize_numa_stats() {
745   if (_numa->is_enabled()) {
746     LogTarget(Info, gc, heap, numa) lt;
747 
748     if (lt.is_enabled()) {
749       uint num_nodes = _numa->num_active_nodes();
750       // Record only if there are multiple active nodes.
751       _obj_alloc_stat = NEW_C_HEAP_ARRAY(size_t, num_nodes, mtGC);
752       memset(_obj_alloc_stat, 0, sizeof(size_t) * num_nodes);
753     }
754   }
755 }
756 
757 void G1ParScanThreadState::flush_numa_stats() {
758   if (_obj_alloc_stat != nullptr) {
759     uint node_index = _numa->index_of_current_thread();
760     _numa->copy_statistics(G1NUMAStats::LocalObjProcessAtCopyToSurv, node_index, _obj_alloc_stat);
761   }
762 }
763 
764 void G1ParScanThreadState::update_numa_stats(uint node_index) {
765   if (_obj_alloc_stat != nullptr) {
766     _obj_alloc_stat[node_index]++;
767   }
768 }
769 
770 #if TASKQUEUE_STATS
771 
772 PartialArrayTaskStats* G1ParScanThreadState::partial_array_task_stats() {
773   return _partial_array_splitter.stats();
774 }
775 
776 #endif // TASKQUEUE_STATS
777 
778 G1ParScanThreadStateSet::G1ParScanThreadStateSet(G1CollectedHeap* g1h,
779                                                  uint num_workers,
780                                                  G1CollectionSet* collection_set,
781                                                  G1EvacFailureRegions* evac_failure_regions) :
782     _g1h(g1h),
783     _collection_set(collection_set),
784     _states(NEW_C_HEAP_ARRAY(G1ParScanThreadState*, num_workers, mtGC)),
785     _surviving_young_words_total(NEW_C_HEAP_ARRAY(size_t, collection_set->num_young_regions() + 1, mtGC)),
786     _num_workers(num_workers),
787     _flushed(false),
788     _evac_failure_regions(evac_failure_regions),
789     _has_nmethods_to_add(g1h->max_num_regions(), mtGC),
790     _num_nmethod_regions_to_add(0),
791     _nmethod_regions_to_add(NEW_C_HEAP_ARRAY(uint, g1h->max_num_regions(), mtGC)) // Conservative length estimation.
792 {
793   for (uint i = 0; i < num_workers; ++i) {
794     _states[i] = nullptr;
795   }
796   memset(_surviving_young_words_total, 0, (collection_set->num_young_regions() + 1) * sizeof(size_t));
797 }
798 
799 G1ParScanThreadStateSet::~G1ParScanThreadStateSet() {
800   for (uint i = 0; i < _num_workers; i++) {
801     assert(_states[i] == nullptr, "must be");
802   }
803   FREE_C_HEAP_ARRAY(_nmethod_regions_to_add);
804   FREE_C_HEAP_ARRAY(_states);
805   FREE_C_HEAP_ARRAY(_surviving_young_words_total);
806 }
807 
808 #if TASKQUEUE_STATS
809 
810 void G1ParScanThreadStateSet::print_partial_array_task_stats() {
811   auto get_stats = [&](uint i) {
812     return state_for_worker(i)->partial_array_task_stats();
813   };
814   PartialArrayTaskStats::log_set(_num_workers, get_stats,
815                                  "Young GC Partial Array");
816 }
817 
818 #endif // TASKQUEUE_STATS