1 /*
  2  * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "gc/g1/g1Allocator.inline.hpp"
 27 #include "gc/g1/g1CollectedHeap.inline.hpp"
 28 #include "gc/g1/g1CollectionSet.hpp"
 29 #include "gc/g1/g1OopClosures.inline.hpp"
 30 #include "gc/g1/g1ParScanThreadState.inline.hpp"
 31 #include "gc/g1/g1RootClosures.hpp"
 32 #include "gc/g1/g1StringDedup.hpp"
 33 #include "gc/g1/g1Trace.hpp"
 34 #include "gc/shared/partialArrayTaskStepper.inline.hpp"
 35 #include "gc/shared/stringdedup/stringDedup.hpp"
 36 #include "gc/shared/taskqueue.inline.hpp"
 37 #include "memory/allocation.inline.hpp"
 38 #include "oops/access.inline.hpp"
 39 #include "oops/oop.inline.hpp"
 40 #include "runtime/atomic.hpp"
 41 #include "runtime/prefetch.inline.hpp"
 42 #include "utilities/globalDefinitions.hpp"
 43 #include "utilities/macros.hpp"
 44 
 45 // In fastdebug builds the code size can get out of hand, potentially
 46 // tripping over compiler limits (which may be bugs, but nevertheless
 47 // need to be taken into consideration).  A side benefit of limiting
 48 // inlining is that we get more call frames that might aid debugging.
 49 // And the fastdebug compile time for this file is much reduced.
 50 // Explicit NOINLINE to block ATTRIBUTE_FLATTENing.
 51 #define MAYBE_INLINE_EVACUATION NOT_DEBUG(inline) DEBUG_ONLY(NOINLINE)
 52 
 53 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h,
 54                                            G1RedirtyCardsQueueSet* rdcqs,
 55                                            uint worker_id,
 56                                            uint n_workers,
 57                                            size_t young_cset_length,
 58                                            size_t optional_cset_length)
 59   : _g1h(g1h),
 60     _task_queue(g1h->task_queue(worker_id)),
 61     _rdc_local_qset(rdcqs),
 62     _ct(g1h->card_table()),
 63     _closures(NULL),
 64     _plab_allocator(NULL),
 65     _age_table(false),
 66     _tenuring_threshold(g1h->policy()->tenuring_threshold()),
 67     _scanner(g1h, this),
 68     _worker_id(worker_id),
 69     _last_enqueued_card(SIZE_MAX),
 70     _stack_trim_upper_threshold(GCDrainStackTargetSize * 2 + 1),
 71     _stack_trim_lower_threshold(GCDrainStackTargetSize),
 72     _trim_ticks(),
 73     _surviving_young_words_base(NULL),
 74     _surviving_young_words(NULL),
 75     _surviving_words_length(young_cset_length + 1),
 76     _old_gen_is_full(false),
 77     _partial_objarray_chunk_size(ParGCArrayScanChunk),
 78     _partial_array_stepper(n_workers),
 79     _string_dedup_requests(),
 80     _num_optional_regions(optional_cset_length),
 81     _numa(g1h->numa()),
 82     _obj_alloc_stat(NULL)
 83 {
 84   // We allocate number of young gen regions in the collection set plus one
 85   // entries, since entry 0 keeps track of surviving bytes for non-young regions.
 86   // We also add a few elements at the beginning and at the end in
 87   // an attempt to eliminate cache contention
 88   const size_t padding_elem_num = (DEFAULT_CACHE_LINE_SIZE / sizeof(size_t));
 89   size_t array_length = padding_elem_num + _surviving_words_length + padding_elem_num;
 90 
 91   _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length, mtGC);
 92   _surviving_young_words = _surviving_young_words_base + padding_elem_num;
 93   memset(_surviving_young_words, 0, _surviving_words_length * sizeof(size_t));
 94 
 95   _plab_allocator = new G1PLABAllocator(_g1h->allocator());
 96 
 97   // The dest for Young is used when the objects are aged enough to
 98   // need to be moved to the next space.
 99   _dest[G1HeapRegionAttr::Young] = G1HeapRegionAttr::Old;
100   _dest[G1HeapRegionAttr::Old]   = G1HeapRegionAttr::Old;
101 
102   _closures = G1EvacuationRootClosures::create_root_closures(this, _g1h);
103 
104   _oops_into_optional_regions = new G1OopStarChunkedList[_num_optional_regions];
105 
106   initialize_numa_stats();
107 }
108 
109 size_t G1ParScanThreadState::flush(size_t* surviving_young_words) {
110   _rdc_local_qset.flush();
111   flush_numa_stats();
112   // Update allocation statistics.
113   _plab_allocator->flush_and_retire_stats();
114   _g1h->policy()->record_age_table(&_age_table);
115 
116   size_t sum = 0;
117   for (uint i = 0; i < _surviving_words_length; i++) {
118     surviving_young_words[i] += _surviving_young_words[i];
119     sum += _surviving_young_words[i];
120   }
121   return sum;
122 }
123 
124 G1ParScanThreadState::~G1ParScanThreadState() {
125   delete _plab_allocator;
126   delete _closures;
127   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base);
128   delete[] _oops_into_optional_regions;
129   FREE_C_HEAP_ARRAY(size_t, _obj_alloc_stat);
130 }
131 
132 size_t G1ParScanThreadState::lab_waste_words() const {
133   return _plab_allocator->waste();
134 }
135 
136 size_t G1ParScanThreadState::lab_undo_waste_words() const {
137   return _plab_allocator->undo_waste();
138 }
139 
140 #ifdef ASSERT
141 void G1ParScanThreadState::verify_task(narrowOop* task) const {
142   assert(task != NULL, "invariant");
143   assert(UseCompressedOops, "sanity");
144   oop p = RawAccess<>::oop_load(task);
145   assert(_g1h->is_in_reserved(p),
146          "task=" PTR_FORMAT " p=" PTR_FORMAT, p2i(task), p2i(p));
147 }
148 
149 void G1ParScanThreadState::verify_task(oop* task) const {
150   assert(task != NULL, "invariant");
151   oop p = RawAccess<>::oop_load(task);
152   assert(_g1h->is_in_reserved(p),
153          "task=" PTR_FORMAT " p=" PTR_FORMAT, p2i(task), p2i(p));
154 }
155 
156 void G1ParScanThreadState::verify_task(PartialArrayScanTask task) const {
157   // Must be in the collection set--it's already been copied.
158   oop p = task.to_source_array();
159   assert(_g1h->is_in_cset(p), "p=" PTR_FORMAT, p2i(p));
160 }
161 
162 void G1ParScanThreadState::verify_task(ScannerTask task) const {
163   if (task.is_narrow_oop_ptr()) {
164     verify_task(task.to_narrow_oop_ptr());
165   } else if (task.is_oop_ptr()) {
166     verify_task(task.to_oop_ptr());
167   } else if (task.is_partial_array_task()) {
168     verify_task(task.to_partial_array_task());
169   } else {
170     ShouldNotReachHere();
171   }
172 }
173 #endif // ASSERT
174 
175 template <class T>
176 MAYBE_INLINE_EVACUATION
177 void G1ParScanThreadState::do_oop_evac(T* p) {
178   // Reference should not be NULL here as such are never pushed to the task queue.
179   oop obj = RawAccess<IS_NOT_NULL>::oop_load(p);
180 
181   // Although we never intentionally push references outside of the collection
182   // set, due to (benign) races in the claim mechanism during RSet scanning more
183   // than one thread might claim the same card. So the same card may be
184   // processed multiple times, and so we might get references into old gen here.
185   // So we need to redo this check.
186   const G1HeapRegionAttr region_attr = _g1h->region_attr(obj);
187   // References pushed onto the work stack should never point to a humongous region
188   // as they are not added to the collection set due to above precondition.
189   assert(!region_attr.is_humongous(),
190          "Obj " PTR_FORMAT " should not refer to humongous region %u from " PTR_FORMAT,
191          p2i(obj), _g1h->addr_to_region(cast_from_oop<HeapWord*>(obj)), p2i(p));
192 
193   if (!region_attr.is_in_cset()) {
194     // In this case somebody else already did all the work.
195     return;
196   }
197 
198   markWord m = obj->mark();
199   if (m.is_marked()) {
200     obj = obj->forwardee(m);
201   } else {
202     obj = do_copy_to_survivor_space(region_attr, obj, m);
203   }
204   RawAccess<IS_NOT_NULL>::oop_store(p, obj);
205 
206   assert(obj != NULL, "Must be");
207   if (HeapRegion::is_in_same_region(p, obj)) {
208     return;
209   }
210   HeapRegion* from = _g1h->heap_region_containing(p);
211   if (!from->is_young()) {
212     enqueue_card_if_tracked(_g1h->region_attr(obj), p, obj);
213   }
214 }
215 
216 MAYBE_INLINE_EVACUATION
217 void G1ParScanThreadState::do_partial_array(PartialArrayScanTask task) {
218   oop from_obj = task.to_source_array();
219 
220   assert(_g1h->is_in_reserved(from_obj), "must be in heap.");
221   assert(from_obj->is_forwarded(), "must be forwarded");
222 
223   oop to_obj = from_obj->forwardee();
224   assert(from_obj != to_obj, "should not be chunking self-forwarded objects");
225   assert(to_obj->is_objArray(), "must be obj array");
226   objArrayOop to_array = objArrayOop(to_obj);
227 
228   PartialArrayTaskStepper::Step step
229     = _partial_array_stepper.next(objArrayOop(from_obj),
230                                   to_array,
231                                   _partial_objarray_chunk_size);
232   for (uint i = 0; i < step._ncreate; ++i) {
233     push_on_queue(ScannerTask(PartialArrayScanTask(from_obj)));
234   }
235 
236   HeapRegion* hr = _g1h->heap_region_containing(to_array);
237   G1ScanInYoungSetter x(&_scanner, hr->is_young());
238   // Process claimed task.  The length of to_array is not correct, but
239   // fortunately the iteration ignores the length field and just relies
240   // on start/end.
241   to_array->oop_iterate_range(&_scanner,
242                               step._index,
243                               step._index + _partial_objarray_chunk_size);
244 }
245 
246 MAYBE_INLINE_EVACUATION
247 void G1ParScanThreadState::start_partial_objarray(G1HeapRegionAttr dest_attr,
248                                                   oop from_obj,
249                                                   oop to_obj) {
250   assert(from_obj->is_forwarded(), "precondition");
251   assert(from_obj->forwardee() == to_obj, "precondition");
252   assert(from_obj != to_obj, "should not be scanning self-forwarded objects");
253   assert(to_obj->is_objArray(), "precondition");
254 
255   objArrayOop to_array = objArrayOop(to_obj);
256 
257   PartialArrayTaskStepper::Step step
258     = _partial_array_stepper.start(objArrayOop(from_obj),
259                                    to_array,
260                                    _partial_objarray_chunk_size);
261 
262   // Push any needed partial scan tasks.  Pushed before processing the
263   // intitial chunk to allow other workers to steal while we're processing.
264   for (uint i = 0; i < step._ncreate; ++i) {
265     push_on_queue(ScannerTask(PartialArrayScanTask(from_obj)));
266   }
267 
268   G1ScanInYoungSetter x(&_scanner, dest_attr.is_young());
269   // Process the initial chunk.  No need to process the type in the
270   // klass, as it will already be handled by processing the built-in
271   // module. The length of to_array is not correct, but fortunately
272   // the iteration ignores that length field and relies on start/end.
273   to_array->oop_iterate_range(&_scanner, 0, step._index);
274 }
275 
276 MAYBE_INLINE_EVACUATION
277 void G1ParScanThreadState::dispatch_task(ScannerTask task) {
278   verify_task(task);
279   if (task.is_narrow_oop_ptr()) {
280     do_oop_evac(task.to_narrow_oop_ptr());
281   } else if (task.is_oop_ptr()) {
282     do_oop_evac(task.to_oop_ptr());
283   } else {
284     do_partial_array(task.to_partial_array_task());
285   }
286 }
287 
288 // Process tasks until overflow queue is empty and local queue
289 // contains no more than threshold entries.  NOINLINE to prevent
290 // inlining into steal_and_trim_queue.
291 ATTRIBUTE_FLATTEN NOINLINE
292 void G1ParScanThreadState::trim_queue_to_threshold(uint threshold) {
293   ScannerTask task;
294   do {
295     while (_task_queue->pop_overflow(task)) {
296       if (!_task_queue->try_push_to_taskqueue(task)) {
297         dispatch_task(task);
298       }
299     }
300     while (_task_queue->pop_local(task, threshold)) {
301       dispatch_task(task);
302     }
303   } while (!_task_queue->overflow_empty());
304 }
305 
306 ATTRIBUTE_FLATTEN
307 void G1ParScanThreadState::steal_and_trim_queue(G1ScannerTasksQueueSet* task_queues) {
308   ScannerTask stolen_task;
309   while (task_queues->steal(_worker_id, stolen_task)) {
310     dispatch_task(stolen_task);
311     // Processing stolen task may have added tasks to our queue.
312     trim_queue();
313   }
314 }
315 
316 HeapWord* G1ParScanThreadState::allocate_in_next_plab(G1HeapRegionAttr* dest,
317                                                       size_t word_sz,
318                                                       bool previous_plab_refill_failed,
319                                                       uint node_index) {
320 
321   assert(dest->is_in_cset_or_humongous(), "Unexpected dest: %s region attr", dest->get_type_str());
322 
323   // Right now we only have two types of regions (young / old) so
324   // let's keep the logic here simple. We can generalize it when necessary.
325   if (dest->is_young()) {
326     bool plab_refill_in_old_failed = false;
327     HeapWord* const obj_ptr = _plab_allocator->allocate(G1HeapRegionAttr::Old,
328                                                         word_sz,
329                                                         &plab_refill_in_old_failed,
330                                                         node_index);
331     // Make sure that we won't attempt to copy any other objects out
332     // of a survivor region (given that apparently we cannot allocate
333     // any new ones) to avoid coming into this slow path again and again.
334     // Only consider failed PLAB refill here: failed inline allocations are
335     // typically large, so not indicative of remaining space.
336     if (previous_plab_refill_failed) {
337       _tenuring_threshold = 0;
338     }
339 
340     if (obj_ptr != NULL) {
341       dest->set_old();
342     } else {
343       // We just failed to allocate in old gen. The same idea as explained above
344       // for making survivor gen unavailable for allocation applies for old gen.
345       _old_gen_is_full = plab_refill_in_old_failed;
346     }
347     return obj_ptr;
348   } else {
349     _old_gen_is_full = previous_plab_refill_failed;
350     assert(dest->is_old(), "Unexpected dest region attr: %s", dest->get_type_str());
351     // no other space to try.
352     return NULL;
353   }
354 }
355 
356 G1HeapRegionAttr G1ParScanThreadState::next_region_attr(G1HeapRegionAttr const region_attr, markWord const m, uint& age) {
357   if (region_attr.is_young()) {
358     age = !m.has_displaced_mark_helper() ? m.age()
359                                          : m.displaced_mark_helper().age();
360     if (age < _tenuring_threshold) {
361       return region_attr;
362     }
363   }
364   return dest(region_attr);
365 }
366 
367 void G1ParScanThreadState::report_promotion_event(G1HeapRegionAttr const dest_attr,
368                                                   oop const old, Klass* klass, size_t word_sz, uint age,
369                                                   HeapWord * const obj_ptr, uint node_index) const {
370   PLAB* alloc_buf = _plab_allocator->alloc_buffer(dest_attr, node_index);
371   if (alloc_buf->contains(obj_ptr)) {
372     _g1h->_gc_tracer_stw->report_promotion_in_new_plab_event(klass, word_sz * HeapWordSize, age,
373                                                              dest_attr.type() == G1HeapRegionAttr::Old,
374                                                              alloc_buf->word_sz() * HeapWordSize);
375   } else {
376     _g1h->_gc_tracer_stw->report_promotion_outside_plab_event(klass, word_sz * HeapWordSize, age,
377                                                               dest_attr.type() == G1HeapRegionAttr::Old);
378   }
379 }
380 
381 NOINLINE
382 HeapWord* G1ParScanThreadState::allocate_copy_slow(G1HeapRegionAttr* dest_attr,
383                                                    oop old,
384                                                    Klass* klass,
385                                                    size_t word_sz,
386                                                    uint age,
387                                                    uint node_index) {
388   HeapWord* obj_ptr = NULL;
389   // Try slow-path allocation unless we're allocating old and old is already full.
390   if (!(dest_attr->is_old() && _old_gen_is_full)) {
391     bool plab_refill_failed = false;
392     obj_ptr = _plab_allocator->allocate_direct_or_new_plab(*dest_attr,
393                                                            word_sz,
394                                                            &plab_refill_failed,
395                                                            node_index);
396     if (obj_ptr == NULL) {
397       obj_ptr = allocate_in_next_plab(dest_attr,
398                                       word_sz,
399                                       plab_refill_failed,
400                                       node_index);
401     }
402   }
403   if (obj_ptr != NULL) {
404     update_numa_stats(node_index);
405     if (_g1h->_gc_tracer_stw->should_report_promotion_events()) {
406       // The events are checked individually as part of the actual commit
407       report_promotion_event(*dest_attr, old, klass, word_sz, age, obj_ptr, node_index);
408     }
409   }
410   return obj_ptr;
411 }
412 
413 NOINLINE
414 void G1ParScanThreadState::undo_allocation(G1HeapRegionAttr dest_attr,
415                                            HeapWord* obj_ptr,
416                                            size_t word_sz,
417                                            uint node_index) {
418   _plab_allocator->undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
419 }
420 
421 // Private inline function, for direct internal use and providing the
422 // implementation of the public not-inline function.
423 MAYBE_INLINE_EVACUATION
424 oop G1ParScanThreadState::do_copy_to_survivor_space(G1HeapRegionAttr const region_attr,
425                                                     oop const old,
426                                                     markWord const old_mark) {
427   assert(region_attr.is_in_cset(),
428          "Unexpected region attr type: %s", region_attr.get_type_str());
429 
430   if (old_mark.is_marked()) {
431     // Already forwarded by somebody else, return forwardee.
432     return old->forwardee(old_mark);
433   }
434   // Get the klass once.  We'll need it again later, and this avoids
435   // re-decoding when it's compressed.
436   Klass* klass;
437 #ifdef _LP64
438   if (UseCompactObjectHeaders) {
439     klass = old_mark.safe_klass();
440   } else
441 #endif
442   {
443     klass = old->klass();
444   }
445   const size_t word_sz = old->size_given_klass(klass);
446 
447   uint age = 0;
448   G1HeapRegionAttr dest_attr = next_region_attr(region_attr, old_mark, age);
449   HeapRegion* const from_region = _g1h->heap_region_containing(old);
450   uint node_index = from_region->node_index();
451 
452   HeapWord* obj_ptr = _plab_allocator->plab_allocate(dest_attr, word_sz, node_index);
453 
454   // PLAB allocations should succeed most of the time, so we'll
455   // normally check against NULL once and that's it.
456   if (obj_ptr == NULL) {
457     obj_ptr = allocate_copy_slow(&dest_attr, old, klass, word_sz, age, node_index);
458     if (obj_ptr == NULL) {
459       // This will either forward-to-self, or detect that someone else has
460       // installed a forwarding pointer.
461       return handle_evacuation_failure_par(old, old_mark);
462     }
463   }
464 
465   assert(obj_ptr != NULL, "when we get here, allocation should have succeeded");
466   assert(_g1h->is_in_reserved(obj_ptr), "Allocated memory should be in the heap");
467 
468 #ifndef PRODUCT
469   // Should this evacuation fail?
470   if (_g1h->evacuation_should_fail()) {
471     // Doing this after all the allocation attempts also tests the
472     // undo_allocation() method too.
473     undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
474     return handle_evacuation_failure_par(old, old_mark);
475   }
476 #endif // !PRODUCT
477 
478   // We're going to allocate linearly, so might as well prefetch ahead.
479   Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
480 
481   const oop obj = cast_to_oop(obj_ptr);
482   const oop forward_ptr = old->forward_to_atomic(obj, old_mark, memory_order_relaxed);
483   if (forward_ptr == NULL) {
484     Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(old), obj_ptr, word_sz);
485 
486     {
487       const uint young_index = from_region->young_index_in_cset();
488       assert((from_region->is_young() && young_index >  0) ||
489              (!from_region->is_young() && young_index == 0), "invariant" );
490       _surviving_young_words[young_index] += word_sz;
491     }
492 
493     if (dest_attr.is_young()) {
494       if (age < markWord::max_age) {
495         age++;
496       }
497       if (old_mark.has_displaced_mark_helper()) {
498         // In this case, we have to install the old mark word containing the
499         // displacement tag, and update the age in the displaced mark word.
500         markWord new_mark = old_mark.displaced_mark_helper().set_age(age);
501         old_mark.set_displaced_mark_helper(new_mark);
502         obj->set_mark(old_mark);
503       } else {
504         obj->set_mark(old_mark.set_age(age));
505       }
506       _age_table.add(age, word_sz);
507     } else {
508       obj->set_mark(old_mark);
509     }
510 
511     // Most objects are not arrays, so do one array check rather than
512     // checking for each array category for each object.
513     if (klass->is_array_klass()) {
514       if (klass->is_objArray_klass()) {
515         start_partial_objarray(dest_attr, old, obj);
516       } else {
517         // Nothing needs to be done for typeArrays.  Body doesn't contain
518         // any oops to scan, and the type in the klass will already be handled
519         // by processing the built-in module.
520         assert(klass->is_typeArray_klass(), "invariant");
521       }
522       return obj;
523     }
524 
525     // Check for deduplicating young Strings.
526     if (G1StringDedup::is_candidate_from_evacuation(klass,
527                                                     region_attr,
528                                                     dest_attr,
529                                                     age)) {
530       // Record old; request adds a new weak reference, which reference
531       // processing expects to refer to a from-space object.
532       _string_dedup_requests.add(old);
533     }
534 
535     G1ScanInYoungSetter x(&_scanner, dest_attr.is_young());
536     obj->oop_iterate_backwards(&_scanner, klass);
537     return obj;
538 
539   } else {
540     _plab_allocator->undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
541     return forward_ptr;
542   }
543 }
544 
545 // Public not-inline entry point.
546 ATTRIBUTE_FLATTEN
547 oop G1ParScanThreadState::copy_to_survivor_space(G1HeapRegionAttr region_attr,
548                                                  oop old,
549                                                  markWord old_mark) {
550   return do_copy_to_survivor_space(region_attr, old, old_mark);
551 }
552 
553 G1ParScanThreadState* G1ParScanThreadStateSet::state_for_worker(uint worker_id) {
554   assert(worker_id < _n_workers, "out of bounds access");
555   if (_states[worker_id] == NULL) {
556     _states[worker_id] =
557       new G1ParScanThreadState(_g1h, _rdcqs,
558                                worker_id, _n_workers,
559                                _young_cset_length, _optional_cset_length);
560   }
561   return _states[worker_id];
562 }
563 
564 const size_t* G1ParScanThreadStateSet::surviving_young_words() const {
565   assert(_flushed, "thread local state from the per thread states should have been flushed");
566   return _surviving_young_words_total;
567 }
568 
569 void G1ParScanThreadStateSet::flush() {
570   assert(!_flushed, "thread local state from the per thread states should be flushed once");
571 
572   for (uint worker_id = 0; worker_id < _n_workers; ++worker_id) {
573     G1ParScanThreadState* pss = _states[worker_id];
574 
575     if (pss == NULL) {
576       continue;
577     }
578 
579     G1GCPhaseTimes* p = _g1h->phase_times();
580 
581     // Need to get the following two before the call to G1ParThreadScanState::flush()
582     // because it resets the PLAB allocator where we get this info from.
583     size_t lab_waste_bytes = pss->lab_waste_words() * HeapWordSize;
584     size_t lab_undo_waste_bytes = pss->lab_undo_waste_words() * HeapWordSize;
585     size_t copied_bytes = pss->flush(_surviving_young_words_total) * HeapWordSize;
586 
587     p->record_or_add_thread_work_item(G1GCPhaseTimes::MergePSS, worker_id, copied_bytes, G1GCPhaseTimes::MergePSSCopiedBytes);
588     p->record_or_add_thread_work_item(G1GCPhaseTimes::MergePSS, worker_id, lab_waste_bytes, G1GCPhaseTimes::MergePSSLABWasteBytes);
589     p->record_or_add_thread_work_item(G1GCPhaseTimes::MergePSS, worker_id, lab_undo_waste_bytes, G1GCPhaseTimes::MergePSSLABUndoWasteBytes);
590 
591     delete pss;
592     _states[worker_id] = NULL;
593   }
594   _flushed = true;
595 }
596 
597 void G1ParScanThreadStateSet::record_unused_optional_region(HeapRegion* hr) {
598   for (uint worker_index = 0; worker_index < _n_workers; ++worker_index) {
599     G1ParScanThreadState* pss = _states[worker_index];
600 
601     if (pss == NULL) {
602       continue;
603     }
604 
605     size_t used_memory = pss->oops_into_optional_region(hr)->used_memory();
606     _g1h->phase_times()->record_or_add_thread_work_item(G1GCPhaseTimes::OptScanHR, worker_index, used_memory, G1GCPhaseTimes::ScanHRUsedMemory);
607   }
608 }
609 
610 NOINLINE
611 oop G1ParScanThreadState::handle_evacuation_failure_par(oop old, markWord m) {
612   assert(_g1h->is_in_cset(old), "Object " PTR_FORMAT " should be in the CSet", p2i(old));
613 
614   oop forward_ptr = old->forward_to_self_atomic(m, memory_order_relaxed);
615   if (forward_ptr == NULL) {
616     // Forward-to-self succeeded. We are the "owner" of the object.
617     HeapRegion* r = _g1h->heap_region_containing(old);
618 
619     if (_g1h->notify_region_failed_evacuation(r->hrm_index())) {
620       _g1h->hr_printer()->evac_failure(r);
621     }
622 
623     _g1h->preserve_mark_during_evac_failure(_worker_id, old, m);
624 
625     G1ScanInYoungSetter x(&_scanner, r->is_young());
626     old->oop_iterate_backwards(&_scanner);
627 
628     return old;
629   } else {
630     // Forward-to-self failed. Either someone else managed to allocate
631     // space for this object (old != forward_ptr) or they beat us in
632     // self-forwarding it (old == forward_ptr).
633     assert(old == forward_ptr || !_g1h->is_in_cset(forward_ptr),
634            "Object " PTR_FORMAT " forwarded to: " PTR_FORMAT " "
635            "should not be in the CSet",
636            p2i(old), p2i(forward_ptr));
637     return forward_ptr;
638   }
639 }
640 
641 void G1ParScanThreadState::initialize_numa_stats() {
642   if (_numa->is_enabled()) {
643     LogTarget(Info, gc, heap, numa) lt;
644 
645     if (lt.is_enabled()) {
646       uint num_nodes = _numa->num_active_nodes();
647       // Record only if there are multiple active nodes.
648       _obj_alloc_stat = NEW_C_HEAP_ARRAY(size_t, num_nodes, mtGC);
649       memset(_obj_alloc_stat, 0, sizeof(size_t) * num_nodes);
650     }
651   }
652 }
653 
654 void G1ParScanThreadState::flush_numa_stats() {
655   if (_obj_alloc_stat != NULL) {
656     uint node_index = _numa->index_of_current_thread();
657     _numa->copy_statistics(G1NUMAStats::LocalObjProcessAtCopyToSurv, node_index, _obj_alloc_stat);
658   }
659 }
660 
661 void G1ParScanThreadState::update_numa_stats(uint node_index) {
662   if (_obj_alloc_stat != NULL) {
663     _obj_alloc_stat[node_index]++;
664   }
665 }
666 
667 G1ParScanThreadStateSet::G1ParScanThreadStateSet(G1CollectedHeap* g1h,
668                                                  G1RedirtyCardsQueueSet* rdcqs,
669                                                  uint n_workers,
670                                                  size_t young_cset_length,
671                                                  size_t optional_cset_length) :
672     _g1h(g1h),
673     _rdcqs(rdcqs),
674     _states(NEW_C_HEAP_ARRAY(G1ParScanThreadState*, n_workers, mtGC)),
675     _surviving_young_words_total(NEW_C_HEAP_ARRAY(size_t, young_cset_length + 1, mtGC)),
676     _young_cset_length(young_cset_length),
677     _optional_cset_length(optional_cset_length),
678     _n_workers(n_workers),
679     _flushed(false) {
680   for (uint i = 0; i < n_workers; ++i) {
681     _states[i] = NULL;
682   }
683   memset(_surviving_young_words_total, 0, (young_cset_length + 1) * sizeof(size_t));
684 }
685 
686 G1ParScanThreadStateSet::~G1ParScanThreadStateSet() {
687   assert(_flushed, "thread local state from the per thread states should have been flushed");
688   FREE_C_HEAP_ARRAY(G1ParScanThreadState*, _states);
689   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_total);
690 }