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   write_ref_field_post(p, obj);
207 }
208 
209 MAYBE_INLINE_EVACUATION
210 void G1ParScanThreadState::do_partial_array(PartialArrayScanTask task) {
211   oop from_obj = task.to_source_array();
212 
213   assert(_g1h->is_in_reserved(from_obj), "must be in heap.");

214   assert(from_obj->is_forwarded(), "must be forwarded");
215 
216   oop to_obj = from_obj->forwardee();
217   assert(from_obj != to_obj, "should not be chunking self-forwarded objects");
218   assert(to_obj->is_objArray(), "must be obj array");
219   objArrayOop to_array = objArrayOop(to_obj);
220 
221   PartialArrayTaskStepper::Step step
222     = _partial_array_stepper.next(objArrayOop(from_obj),
223                                   to_array,
224                                   _partial_objarray_chunk_size);
225   for (uint i = 0; i < step._ncreate; ++i) {
226     push_on_queue(ScannerTask(PartialArrayScanTask(from_obj)));
227   }
228 
229   HeapRegion* hr = _g1h->heap_region_containing(to_array);
230   G1ScanInYoungSetter x(&_scanner, hr->is_young());
231   // Process claimed task.  The length of to_array is not correct, but
232   // fortunately the iteration ignores the length field and just relies
233   // on start/end.
234   to_array->oop_iterate_range(&_scanner,
235                               step._index,
236                               step._index + _partial_objarray_chunk_size);
237 }
238 
239 MAYBE_INLINE_EVACUATION
240 void G1ParScanThreadState::start_partial_objarray(G1HeapRegionAttr dest_attr,
241                                                   oop from_obj,
242                                                   oop to_obj) {

243   assert(from_obj->is_forwarded(), "precondition");
244   assert(from_obj->forwardee() == to_obj, "precondition");
245   assert(from_obj != to_obj, "should not be scanning self-forwarded objects");
246   assert(to_obj->is_objArray(), "precondition");
247 
248   objArrayOop to_array = objArrayOop(to_obj);
249 
250   PartialArrayTaskStepper::Step step
251     = _partial_array_stepper.start(objArrayOop(from_obj),
252                                    to_array,
253                                    _partial_objarray_chunk_size);
254 
255   // Push any needed partial scan tasks.  Pushed before processing the
256   // intitial chunk to allow other workers to steal while we're processing.
257   for (uint i = 0; i < step._ncreate; ++i) {
258     push_on_queue(ScannerTask(PartialArrayScanTask(from_obj)));
259   }
260 
261   G1ScanInYoungSetter x(&_scanner, dest_attr.is_young());
262   // Process the initial chunk.  No need to process the type in the
263   // klass, as it will already be handled by processing the built-in
264   // module. The length of to_array is not correct, but fortunately
265   // the iteration ignores that length field and relies on start/end.
266   to_array->oop_iterate_range(&_scanner, 0, step._index);
267 }
268 
269 MAYBE_INLINE_EVACUATION
270 void G1ParScanThreadState::dispatch_task(ScannerTask task) {
271   verify_task(task);
272   if (task.is_narrow_oop_ptr()) {
273     do_oop_evac(task.to_narrow_oop_ptr());
274   } else if (task.is_oop_ptr()) {
275     do_oop_evac(task.to_oop_ptr());
276   } else {
277     do_partial_array(task.to_partial_array_task());
278   }
279 }
280 
281 // Process tasks until overflow queue is empty and local queue
282 // contains no more than threshold entries.  NOINLINE to prevent
283 // inlining into steal_and_trim_queue.
284 ATTRIBUTE_FLATTEN NOINLINE
285 void G1ParScanThreadState::trim_queue_to_threshold(uint threshold) {
286   ScannerTask task;
287   do {
288     while (_task_queue->pop_overflow(task)) {
289       if (!_task_queue->try_push_to_taskqueue(task)) {
290         dispatch_task(task);
291       }
292     }
293     while (_task_queue->pop_local(task, threshold)) {
294       dispatch_task(task);
295     }
296   } while (!_task_queue->overflow_empty());
297 }
298 
299 ATTRIBUTE_FLATTEN
300 void G1ParScanThreadState::steal_and_trim_queue(G1ScannerTasksQueueSet* task_queues) {
301   ScannerTask stolen_task;
302   while (task_queues->steal(_worker_id, stolen_task)) {
303     dispatch_task(stolen_task);
304     // Processing stolen task may have added tasks to our queue.
305     trim_queue();
306   }
307 }
308 
309 HeapWord* G1ParScanThreadState::allocate_in_next_plab(G1HeapRegionAttr* dest,
310                                                       size_t word_sz,
311                                                       bool previous_plab_refill_failed,
312                                                       uint node_index) {
313 
314   assert(dest->is_in_cset_or_humongous(), "Unexpected dest: %s region attr", dest->get_type_str());
315 
316   // Right now we only have two types of regions (young / old) so
317   // let's keep the logic here simple. We can generalize it when necessary.
318   if (dest->is_young()) {
319     bool plab_refill_in_old_failed = false;
320     HeapWord* const obj_ptr = _plab_allocator->allocate(G1HeapRegionAttr::Old,
321                                                         word_sz,
322                                                         &plab_refill_in_old_failed,
323                                                         node_index);
324     // Make sure that we won't attempt to copy any other objects out
325     // of a survivor region (given that apparently we cannot allocate
326     // any new ones) to avoid coming into this slow path again and again.
327     // Only consider failed PLAB refill here: failed inline allocations are
328     // typically large, so not indicative of remaining space.
329     if (previous_plab_refill_failed) {
330       _tenuring_threshold = 0;
331     }
332 
333     if (obj_ptr != NULL) {
334       dest->set_old();
335     } else {
336       // We just failed to allocate in old gen. The same idea as explained above
337       // for making survivor gen unavailable for allocation applies for old gen.
338       _old_gen_is_full = plab_refill_in_old_failed;
339     }
340     return obj_ptr;
341   } else {
342     _old_gen_is_full = previous_plab_refill_failed;
343     assert(dest->is_old(), "Unexpected dest region attr: %s", dest->get_type_str());
344     // no other space to try.
345     return NULL;
346   }
347 }
348 
349 G1HeapRegionAttr G1ParScanThreadState::next_region_attr(G1HeapRegionAttr const region_attr, markWord const m, uint& age) {
350   if (region_attr.is_young()) {
351     age = !m.has_displaced_mark_helper() ? m.age()
352                                          : m.displaced_mark_helper().age();
353     if (age < _tenuring_threshold) {
354       return region_attr;
355     }
356   }
357   return dest(region_attr);
358 }
359 
360 void G1ParScanThreadState::report_promotion_event(G1HeapRegionAttr const dest_attr,
361                                                   oop const old, Klass* klass, size_t word_sz, uint age,
362                                                   HeapWord * const obj_ptr, uint node_index) const {
363   PLAB* alloc_buf = _plab_allocator->alloc_buffer(dest_attr, node_index);
364   if (alloc_buf->contains(obj_ptr)) {
365     _g1h->_gc_tracer_stw->report_promotion_in_new_plab_event(klass, word_sz * HeapWordSize, age,
366                                                              dest_attr.type() == G1HeapRegionAttr::Old,
367                                                              alloc_buf->word_sz() * HeapWordSize);
368   } else {
369     _g1h->_gc_tracer_stw->report_promotion_outside_plab_event(klass, word_sz * HeapWordSize, age,
370                                                               dest_attr.type() == G1HeapRegionAttr::Old);
371   }
372 }
373 
374 NOINLINE
375 HeapWord* G1ParScanThreadState::allocate_copy_slow(G1HeapRegionAttr* dest_attr,
376                                                    oop old,
377                                                    Klass* klass,
378                                                    size_t word_sz,
379                                                    uint age,
380                                                    uint node_index) {
381   HeapWord* obj_ptr = NULL;
382   // Try slow-path allocation unless we're allocating old and old is already full.
383   if (!(dest_attr->is_old() && _old_gen_is_full)) {
384     bool plab_refill_failed = false;
385     obj_ptr = _plab_allocator->allocate_direct_or_new_plab(*dest_attr,
386                                                            word_sz,
387                                                            &plab_refill_failed,
388                                                            node_index);
389     if (obj_ptr == NULL) {
390       obj_ptr = allocate_in_next_plab(dest_attr,
391                                       word_sz,
392                                       plab_refill_failed,
393                                       node_index);
394     }
395   }
396   if (obj_ptr != NULL) {
397     update_numa_stats(node_index);
398     if (_g1h->_gc_tracer_stw->should_report_promotion_events()) {
399       // The events are checked individually as part of the actual commit
400       report_promotion_event(*dest_attr, old, klass, word_sz, age, obj_ptr, node_index);
401     }
402   }
403   return obj_ptr;
404 }
405 
406 NOINLINE
407 void G1ParScanThreadState::undo_allocation(G1HeapRegionAttr dest_attr,
408                                            HeapWord* obj_ptr,
409                                            size_t word_sz,
410                                            uint node_index) {
411   _plab_allocator->undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
412 }
413 
414 // Private inline function, for direct internal use and providing the
415 // implementation of the public not-inline function.
416 MAYBE_INLINE_EVACUATION
417 oop G1ParScanThreadState::do_copy_to_survivor_space(G1HeapRegionAttr const region_attr,
418                                                     oop const old,
419                                                     markWord const old_mark) {
420   assert(region_attr.is_in_cset(),
421          "Unexpected region attr type: %s", region_attr.get_type_str());
422 
423   if (old_mark.is_marked()) {
424     // Already forwarded by somebody else, return forwardee.
425     return old->forwardee(old_mark);
426   }
427   // Get the klass once.  We'll need it again later, and this avoids
428   // re-decoding when it's compressed.
429   Klass* klass;
430 #ifdef _LP64
431   if (UseCompactObjectHeaders) {
432     klass = old_mark.safe_klass();
433   } else
434 #endif
435   {
436     klass = old->klass();
437   }
438   const size_t word_sz = old->size_given_klass(klass);
439 
440   uint age = 0;
441   G1HeapRegionAttr dest_attr = next_region_attr(region_attr, old_mark, age);
442   HeapRegion* const from_region = _g1h->heap_region_containing(old);
443   uint node_index = from_region->node_index();
444 
445   HeapWord* obj_ptr = _plab_allocator->plab_allocate(dest_attr, word_sz, node_index);
446 
447   // PLAB allocations should succeed most of the time, so we'll
448   // normally check against NULL once and that's it.
449   if (obj_ptr == NULL) {
450     obj_ptr = allocate_copy_slow(&dest_attr, old, klass, word_sz, age, node_index);
451     if (obj_ptr == NULL) {
452       // This will either forward-to-self, or detect that someone else has
453       // installed a forwarding pointer.
454       return handle_evacuation_failure_par(old, old_mark);
455     }
456   }
457 
458   assert(obj_ptr != NULL, "when we get here, allocation should have succeeded");
459   assert(_g1h->is_in_reserved(obj_ptr), "Allocated memory should be in the heap");
460 
461 #ifndef PRODUCT
462   // Should this evacuation fail?
463   if (_g1h->evacuation_should_fail()) {
464     // Doing this after all the allocation attempts also tests the
465     // undo_allocation() method too.
466     undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
467     return handle_evacuation_failure_par(old, old_mark);
468   }
469 #endif // !PRODUCT
470 
471   // We're going to allocate linearly, so might as well prefetch ahead.
472   Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
473 
474   const oop obj = cast_to_oop(obj_ptr);
475   const oop forward_ptr = old->forward_to_atomic(obj, old_mark, memory_order_relaxed);
476   if (forward_ptr == NULL) {
477     Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(old), obj_ptr, word_sz);
478 
479     {
480       const uint young_index = from_region->young_index_in_cset();
481       assert((from_region->is_young() && young_index >  0) ||
482              (!from_region->is_young() && young_index == 0), "invariant" );
483       _surviving_young_words[young_index] += word_sz;
484     }
485 
486     if (dest_attr.is_young()) {
487       if (age < markWord::max_age) {
488         age++;
489       }
490       if (old_mark.has_displaced_mark_helper()) {
491         // In this case, we have to install the old mark word containing the
492         // displacement tag, and update the age in the displaced mark word.
493         markWord new_mark = old_mark.displaced_mark_helper().set_age(age);
494         old_mark.set_displaced_mark_helper(new_mark);
495         obj->set_mark(old_mark);
496       } else {
497         obj->set_mark(old_mark.set_age(age));
498       }
499       _age_table.add(age, word_sz);
500     } else {
501       obj->set_mark(old_mark);
502     }
503 
504     // Most objects are not arrays, so do one array check rather than
505     // checking for each array category for each object.
506     if (klass->is_array_klass()) {
507       if (klass->is_objArray_klass()) {
508         start_partial_objarray(dest_attr, old, obj);
509       } else {
510         // Nothing needs to be done for typeArrays.  Body doesn't contain
511         // any oops to scan, and the type in the klass will already be handled
512         // by processing the built-in module.
513         assert(klass->is_typeArray_klass(), "invariant");
514       }
515       return obj;
516     }
517 
518     // Check for deduplicating young Strings.
519     if (G1StringDedup::is_candidate_from_evacuation(klass,
520                                                     region_attr,
521                                                     dest_attr,
522                                                     age)) {
523       // Record old; request adds a new weak reference, which reference
524       // processing expects to refer to a from-space object.
525       _string_dedup_requests.add(old);
526     }
527 
528     G1ScanInYoungSetter x(&_scanner, dest_attr.is_young());
529     obj->oop_iterate_backwards(&_scanner, klass);
530     return obj;
531 
532   } else {
533     _plab_allocator->undo_allocation(dest_attr, obj_ptr, word_sz, node_index);
534     return forward_ptr;
535   }
536 }
537 
538 // Public not-inline entry point.
539 ATTRIBUTE_FLATTEN
540 oop G1ParScanThreadState::copy_to_survivor_space(G1HeapRegionAttr region_attr,
541                                                  oop old,
542                                                  markWord old_mark) {
543   return do_copy_to_survivor_space(region_attr, old, old_mark);
544 }
545 
546 G1ParScanThreadState* G1ParScanThreadStateSet::state_for_worker(uint worker_id) {
547   assert(worker_id < _n_workers, "out of bounds access");
548   if (_states[worker_id] == NULL) {
549     _states[worker_id] =
550       new G1ParScanThreadState(_g1h, _rdcqs,
551                                worker_id, _n_workers,
552                                _young_cset_length, _optional_cset_length);
553   }
554   return _states[worker_id];
555 }
556 
557 const size_t* G1ParScanThreadStateSet::surviving_young_words() const {
558   assert(_flushed, "thread local state from the per thread states should have been flushed");
559   return _surviving_young_words_total;
560 }
561 
562 void G1ParScanThreadStateSet::flush() {
563   assert(!_flushed, "thread local state from the per thread states should be flushed once");
564 
565   for (uint worker_id = 0; worker_id < _n_workers; ++worker_id) {
566     G1ParScanThreadState* pss = _states[worker_id];
567 
568     if (pss == NULL) {
569       continue;
570     }
571 
572     G1GCPhaseTimes* p = _g1h->phase_times();
573 
574     // Need to get the following two before the call to G1ParThreadScanState::flush()
575     // because it resets the PLAB allocator where we get this info from.
576     size_t lab_waste_bytes = pss->lab_waste_words() * HeapWordSize;
577     size_t lab_undo_waste_bytes = pss->lab_undo_waste_words() * HeapWordSize;
578     size_t copied_bytes = pss->flush(_surviving_young_words_total) * HeapWordSize;
579 
580     p->record_or_add_thread_work_item(G1GCPhaseTimes::MergePSS, worker_id, copied_bytes, G1GCPhaseTimes::MergePSSCopiedBytes);
581     p->record_or_add_thread_work_item(G1GCPhaseTimes::MergePSS, worker_id, lab_waste_bytes, G1GCPhaseTimes::MergePSSLABWasteBytes);
582     p->record_or_add_thread_work_item(G1GCPhaseTimes::MergePSS, worker_id, lab_undo_waste_bytes, G1GCPhaseTimes::MergePSSLABUndoWasteBytes);
583 
584     delete pss;
585     _states[worker_id] = NULL;
586   }
587   _flushed = true;
588 }
589 
590 void G1ParScanThreadStateSet::record_unused_optional_region(HeapRegion* hr) {
591   for (uint worker_index = 0; worker_index < _n_workers; ++worker_index) {
592     G1ParScanThreadState* pss = _states[worker_index];
593 
594     if (pss == NULL) {
595       continue;
596     }
597 
598     size_t used_memory = pss->oops_into_optional_region(hr)->used_memory();
599     _g1h->phase_times()->record_or_add_thread_work_item(G1GCPhaseTimes::OptScanHR, worker_index, used_memory, G1GCPhaseTimes::ScanHRUsedMemory);
600   }
601 }
602 
603 NOINLINE
604 oop G1ParScanThreadState::handle_evacuation_failure_par(oop old, markWord m) {
605   assert(_g1h->is_in_cset(old), "Object " PTR_FORMAT " should be in the CSet", p2i(old));
606 
607   oop forward_ptr = old->forward_to_self_atomic(m, memory_order_relaxed);
608   if (forward_ptr == NULL) {
609     // Forward-to-self succeeded. We are the "owner" of the object.
610     HeapRegion* r = _g1h->heap_region_containing(old);
611 
612     if (_g1h->notify_region_failed_evacuation(r->hrm_index())) {
613       _g1h->hr_printer()->evac_failure(r);
614     }
615 
616     _g1h->preserve_mark_during_evac_failure(_worker_id, old, m);
617 
618     G1ScanInYoungSetter x(&_scanner, r->is_young());
619     old->oop_iterate_backwards(&_scanner);
620 
621     return old;
622   } else {
623     // Forward-to-self failed. Either someone else managed to allocate
624     // space for this object (old != forward_ptr) or they beat us in
625     // self-forwarding it (old == forward_ptr).
626     assert(old == forward_ptr || !_g1h->is_in_cset(forward_ptr),
627            "Object " PTR_FORMAT " forwarded to: " PTR_FORMAT " "
628            "should not be in the CSet",
629            p2i(old), p2i(forward_ptr));
630     return forward_ptr;
631   }
632 }
633 
634 void G1ParScanThreadState::initialize_numa_stats() {
635   if (_numa->is_enabled()) {
636     LogTarget(Info, gc, heap, numa) lt;
637 
638     if (lt.is_enabled()) {
639       uint num_nodes = _numa->num_active_nodes();
640       // Record only if there are multiple active nodes.
641       _obj_alloc_stat = NEW_C_HEAP_ARRAY(size_t, num_nodes, mtGC);
642       memset(_obj_alloc_stat, 0, sizeof(size_t) * num_nodes);
643     }
644   }
645 }
646 
647 void G1ParScanThreadState::flush_numa_stats() {
648   if (_obj_alloc_stat != NULL) {
649     uint node_index = _numa->index_of_current_thread();
650     _numa->copy_statistics(G1NUMAStats::LocalObjProcessAtCopyToSurv, node_index, _obj_alloc_stat);
651   }
652 }
653 
654 void G1ParScanThreadState::update_numa_stats(uint node_index) {
655   if (_obj_alloc_stat != NULL) {
656     _obj_alloc_stat[node_index]++;
657   }
658 }
659 
660 G1ParScanThreadStateSet::G1ParScanThreadStateSet(G1CollectedHeap* g1h,
661                                                  G1RedirtyCardsQueueSet* rdcqs,
662                                                  uint n_workers,
663                                                  size_t young_cset_length,
664                                                  size_t optional_cset_length) :
665     _g1h(g1h),
666     _rdcqs(rdcqs),
667     _states(NEW_C_HEAP_ARRAY(G1ParScanThreadState*, n_workers, mtGC)),
668     _surviving_young_words_total(NEW_C_HEAP_ARRAY(size_t, young_cset_length + 1, mtGC)),
669     _young_cset_length(young_cset_length),
670     _optional_cset_length(optional_cset_length),
671     _n_workers(n_workers),
672     _flushed(false) {
673   for (uint i = 0; i < n_workers; ++i) {
674     _states[i] = NULL;
675   }
676   memset(_surviving_young_words_total, 0, (young_cset_length + 1) * sizeof(size_t));
677 }
678 
679 G1ParScanThreadStateSet::~G1ParScanThreadStateSet() {
680   assert(_flushed, "thread local state from the per thread states should have been flushed");
681   FREE_C_HEAP_ARRAY(G1ParScanThreadState*, _states);
682   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_total);
683 }
--- EOF ---