1 /*
   2  * Copyright (c) 2001, 2018, 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/cms/cmsHeap.inline.hpp"
  27 #include "gc/cms/compactibleFreeListSpace.hpp"
  28 #include "gc/cms/concurrentMarkSweepGeneration.hpp"
  29 #include "gc/cms/parNewGeneration.inline.hpp"
  30 #include "gc/cms/parOopClosures.inline.hpp"
  31 #include "gc/serial/defNewGeneration.inline.hpp"
  32 #include "gc/shared/adaptiveSizePolicy.hpp"
  33 #include "gc/shared/ageTable.inline.hpp"
  34 #include "gc/shared/copyFailedInfo.hpp"
  35 #include "gc/shared/gcHeapSummary.hpp"
  36 #include "gc/shared/gcTimer.hpp"
  37 #include "gc/shared/gcTrace.hpp"
  38 #include "gc/shared/gcTraceTime.inline.hpp"
  39 #include "gc/shared/genOopClosures.inline.hpp"
  40 #include "gc/shared/generation.hpp"
  41 #include "gc/shared/plab.inline.hpp"
  42 #include "gc/shared/preservedMarks.inline.hpp"
  43 #include "gc/shared/referencePolicy.hpp"
  44 #include "gc/shared/space.hpp"
  45 #include "gc/shared/spaceDecorator.hpp"
  46 #include "gc/shared/strongRootsScope.hpp"
  47 #include "gc/shared/taskqueue.inline.hpp"
  48 #include "gc/shared/weakProcessor.hpp"
  49 #include "gc/shared/workgroup.hpp"
  50 #include "logging/log.hpp"
  51 #include "logging/logStream.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "oops/access.inline.hpp"
  54 #include "oops/compressedOops.inline.hpp"
  55 #include "oops/objArrayOop.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "runtime/atomic.hpp"
  58 #include "runtime/handles.hpp"
  59 #include "runtime/handles.inline.hpp"
  60 #include "runtime/java.hpp"
  61 #include "runtime/thread.inline.hpp"
  62 #include "utilities/copy.hpp"
  63 #include "utilities/globalDefinitions.hpp"
  64 #include "utilities/stack.inline.hpp"
  65 
  66 ParScanThreadState::ParScanThreadState(Space* to_space_,
  67                                        ParNewGeneration* young_gen_,
  68                                        Generation* old_gen_,
  69                                        int thread_num_,
  70                                        ObjToScanQueueSet* work_queue_set_,
  71                                        Stack<oop, mtGC>* overflow_stacks_,
  72                                        PreservedMarks* preserved_marks_,
  73                                        size_t desired_plab_sz_,
  74                                        ParallelTaskTerminator& term_) :
  75   _to_space(to_space_),
  76   _old_gen(old_gen_),
  77   _young_gen(young_gen_),
  78   _thread_num(thread_num_),
  79   _work_queue(work_queue_set_->queue(thread_num_)),
  80   _to_space_full(false),
  81   _overflow_stack(overflow_stacks_ ? overflow_stacks_ + thread_num_ : NULL),
  82   _preserved_marks(preserved_marks_),
  83   _ageTable(false), // false ==> not the global age table, no perf data.
  84   _to_space_alloc_buffer(desired_plab_sz_),
  85   _to_space_closure(young_gen_, this),
  86   _old_gen_closure(young_gen_, this),
  87   _to_space_root_closure(young_gen_, this),
  88   _old_gen_root_closure(young_gen_, this),
  89   _older_gen_closure(young_gen_, this),
  90   _evacuate_followers(this, &_to_space_closure, &_old_gen_closure,
  91                       &_to_space_root_closure, young_gen_, &_old_gen_root_closure,
  92                       work_queue_set_, &term_),
  93   _is_alive_closure(young_gen_),
  94   _scan_weak_ref_closure(young_gen_, this),
  95   _keep_alive_closure(&_scan_weak_ref_closure),
  96   _strong_roots_time(0.0),
  97   _term_time(0.0)
  98 {
  99   #if TASKQUEUE_STATS
 100   _term_attempts = 0;
 101   _overflow_refills = 0;
 102   _overflow_refill_objs = 0;
 103   #endif // TASKQUEUE_STATS
 104 
 105   _survivor_chunk_array = (ChunkArray*) old_gen()->get_data_recorder(thread_num());
 106   _hash_seed = 17;  // Might want to take time-based random value.
 107   _start = os::elapsedTime();
 108   _old_gen_closure.set_generation(old_gen_);
 109   _old_gen_root_closure.set_generation(old_gen_);
 110 }
 111 
 112 void ParScanThreadState::record_survivor_plab(HeapWord* plab_start,
 113                                               size_t plab_word_size) {
 114   ChunkArray* sca = survivor_chunk_array();
 115   if (sca != NULL) {
 116     // A non-null SCA implies that we want the PLAB data recorded.
 117     sca->record_sample(plab_start, plab_word_size);
 118   }
 119 }
 120 
 121 bool ParScanThreadState::should_be_partially_scanned(oop new_obj, oop old_obj) const {
 122   return new_obj->is_objArray() &&
 123          arrayOop(new_obj)->length() > ParGCArrayScanChunk &&
 124          new_obj != old_obj;
 125 }
 126 
 127 void ParScanThreadState::scan_partial_array_and_push_remainder(oop old) {
 128   assert(old->is_objArray(), "must be obj array");
 129   assert(old->is_forwarded(), "must be forwarded");
 130   assert(CMSHeap::heap()->is_in_reserved(old), "must be in heap.");
 131   assert(!old_gen()->is_in(old), "must be in young generation.");
 132 
 133   objArrayOop obj = objArrayOop(old->forwardee());
 134   // Process ParGCArrayScanChunk elements now
 135   // and push the remainder back onto queue
 136   int start     = arrayOop(old)->length();
 137   int end       = obj->length();
 138   int remainder = end - start;
 139   assert(start <= end, "just checking");
 140   if (remainder > 2 * ParGCArrayScanChunk) {
 141     // Test above combines last partial chunk with a full chunk
 142     end = start + ParGCArrayScanChunk;
 143     arrayOop(old)->set_length(end);
 144     // Push remainder.
 145     bool ok = work_queue()->push(old);
 146     assert(ok, "just popped, push must be okay");
 147   } else {
 148     // Restore length so that it can be used if there
 149     // is a promotion failure and forwarding pointers
 150     // must be removed.
 151     arrayOop(old)->set_length(end);
 152   }
 153 
 154   // process our set of indices (include header in first chunk)
 155   // should make sure end is even (aligned to HeapWord in case of compressed oops)
 156   if ((HeapWord *)obj < young_old_boundary()) {
 157     // object is in to_space
 158     obj->oop_iterate_range(&_to_space_closure, start, end);
 159   } else {
 160     // object is in old generation
 161     obj->oop_iterate_range(&_old_gen_closure, start, end);
 162   }
 163 }
 164 
 165 void ParScanThreadState::trim_queues(int max_size) {
 166   ObjToScanQueue* queue = work_queue();
 167   do {
 168     while (queue->size() > (juint)max_size) {
 169       oop obj_to_scan;
 170       if (queue->pop_local(obj_to_scan)) {
 171         if ((HeapWord *)obj_to_scan < young_old_boundary()) {
 172           if (obj_to_scan->is_objArray() &&
 173               obj_to_scan->is_forwarded() &&
 174               obj_to_scan->forwardee() != obj_to_scan) {
 175             scan_partial_array_and_push_remainder(obj_to_scan);
 176           } else {
 177             // object is in to_space
 178             obj_to_scan->oop_iterate(&_to_space_closure);
 179           }
 180         } else {
 181           // object is in old generation
 182           obj_to_scan->oop_iterate(&_old_gen_closure);
 183         }
 184       }
 185     }
 186     // For the  case of compressed oops, we have a private, non-shared
 187     // overflow stack, so we eagerly drain it so as to more evenly
 188     // distribute load early. Note: this may be good to do in
 189     // general rather than delay for the final stealing phase.
 190     // If applicable, we'll transfer a set of objects over to our
 191     // work queue, allowing them to be stolen and draining our
 192     // private overflow stack.
 193   } while (ParGCTrimOverflow && young_gen()->take_from_overflow_list(this));
 194 }
 195 
 196 bool ParScanThreadState::take_from_overflow_stack() {
 197   assert(ParGCUseLocalOverflow, "Else should not call");
 198   assert(young_gen()->overflow_list() == NULL, "Error");
 199   ObjToScanQueue* queue = work_queue();
 200   Stack<oop, mtGC>* const of_stack = overflow_stack();
 201   const size_t num_overflow_elems = of_stack->size();
 202   const size_t space_available = queue->max_elems() - queue->size();
 203   const size_t num_take_elems = MIN3(space_available / 4,
 204                                      ParGCDesiredObjsFromOverflowList,
 205                                      num_overflow_elems);
 206   // Transfer the most recent num_take_elems from the overflow
 207   // stack to our work queue.
 208   for (size_t i = 0; i != num_take_elems; i++) {
 209     oop cur = of_stack->pop();
 210     oop obj_to_push = cur->forwardee();
 211     assert(CMSHeap::heap()->is_in_reserved(cur), "Should be in heap");
 212     assert(!old_gen()->is_in_reserved(cur), "Should be in young gen");
 213     assert(CMSHeap::heap()->is_in_reserved(obj_to_push), "Should be in heap");
 214     if (should_be_partially_scanned(obj_to_push, cur)) {
 215       assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");
 216       obj_to_push = cur;
 217     }
 218     bool ok = queue->push(obj_to_push);
 219     assert(ok, "Should have succeeded");
 220   }
 221   assert(young_gen()->overflow_list() == NULL, "Error");
 222   return num_take_elems > 0;  // was something transferred?
 223 }
 224 
 225 void ParScanThreadState::push_on_overflow_stack(oop p) {
 226   assert(ParGCUseLocalOverflow, "Else should not call");
 227   overflow_stack()->push(p);
 228   assert(young_gen()->overflow_list() == NULL, "Error");
 229 }
 230 
 231 HeapWord* ParScanThreadState::alloc_in_to_space_slow(size_t word_sz) {
 232   // If the object is small enough, try to reallocate the buffer.
 233   HeapWord* obj = NULL;
 234   if (!_to_space_full) {
 235     PLAB* const plab = to_space_alloc_buffer();
 236     Space* const sp  = to_space();
 237     if (word_sz * 100 < ParallelGCBufferWastePct * plab->word_sz()) {
 238       // Is small enough; abandon this buffer and start a new one.
 239       plab->retire();
 240       // The minimum size has to be twice SurvivorAlignmentInBytes to
 241       // allow for padding used in the alignment of 1 word.  A padding
 242       // of 1 is too small for a filler word so the padding size will
 243       // be increased by SurvivorAlignmentInBytes.
 244       size_t min_usable_size = 2 * static_cast<size_t>(SurvivorAlignmentInBytes >> LogHeapWordSize);
 245       size_t buf_size = MAX2(plab->word_sz(), min_usable_size);
 246       HeapWord* buf_space = sp->par_allocate(buf_size);
 247       if (buf_space == NULL) {
 248         const size_t min_bytes = MAX2(PLAB::min_size(), min_usable_size) << LogHeapWordSize;
 249         size_t free_bytes = sp->free();
 250         while(buf_space == NULL && free_bytes >= min_bytes) {
 251           buf_size = free_bytes >> LogHeapWordSize;
 252           assert(buf_size == (size_t)align_object_size(buf_size), "Invariant");
 253           buf_space  = sp->par_allocate(buf_size);
 254           free_bytes = sp->free();
 255         }
 256       }
 257       if (buf_space != NULL) {
 258         plab->set_buf(buf_space, buf_size);
 259         record_survivor_plab(buf_space, buf_size);
 260         obj = plab->allocate_aligned(word_sz, SurvivorAlignmentInBytes);
 261         // Note that we cannot compare buf_size < word_sz below
 262         // because of AlignmentReserve (see PLAB::allocate()).
 263         assert(obj != NULL || plab->words_remaining() < word_sz,
 264                "Else should have been able to allocate requested object size "
 265                SIZE_FORMAT ", PLAB size " SIZE_FORMAT ", SurvivorAlignmentInBytes "
 266                SIZE_FORMAT ", words_remaining " SIZE_FORMAT,
 267                word_sz, buf_size, SurvivorAlignmentInBytes, plab->words_remaining());
 268         // It's conceivable that we may be able to use the
 269         // buffer we just grabbed for subsequent small requests
 270         // even if not for this one.
 271       } else {
 272         // We're used up.
 273         _to_space_full = true;
 274       }
 275     } else {
 276       // Too large; allocate the object individually.
 277       obj = sp->par_allocate(word_sz);
 278     }
 279   }
 280   return obj;
 281 }
 282 
 283 void ParScanThreadState::undo_alloc_in_to_space(HeapWord* obj, size_t word_sz) {
 284   to_space_alloc_buffer()->undo_allocation(obj, word_sz);
 285 }
 286 
 287 void ParScanThreadState::print_promotion_failure_size() {
 288   if (_promotion_failed_info.has_failed()) {
 289     log_trace(gc, promotion)(" (%d: promotion failure size = " SIZE_FORMAT ") ",
 290                              _thread_num, _promotion_failed_info.first_size());
 291   }
 292 }
 293 
 294 class ParScanThreadStateSet: StackObj {
 295 public:
 296   // Initializes states for the specified number of threads;
 297   ParScanThreadStateSet(int                     num_threads,
 298                         Space&                  to_space,
 299                         ParNewGeneration&       young_gen,
 300                         Generation&             old_gen,
 301                         ObjToScanQueueSet&      queue_set,
 302                         Stack<oop, mtGC>*       overflow_stacks_,
 303                         PreservedMarksSet&      preserved_marks_set,
 304                         size_t                  desired_plab_sz,
 305                         ParallelTaskTerminator& term);
 306 
 307   ~ParScanThreadStateSet() { TASKQUEUE_STATS_ONLY(reset_stats()); }
 308 
 309   inline ParScanThreadState& thread_state(int i);
 310 
 311   void trace_promotion_failed(const YoungGCTracer* gc_tracer);
 312   void reset(uint active_workers, bool promotion_failed);
 313   void flush();
 314 
 315   #if TASKQUEUE_STATS
 316   static void
 317     print_termination_stats_hdr(outputStream* const st);
 318   void print_termination_stats();
 319   static void
 320     print_taskqueue_stats_hdr(outputStream* const st);
 321   void print_taskqueue_stats();
 322   void reset_stats();
 323   #endif // TASKQUEUE_STATS
 324 
 325 private:
 326   ParallelTaskTerminator& _term;
 327   ParNewGeneration&       _young_gen;
 328   Generation&             _old_gen;
 329   ParScanThreadState*     _per_thread_states;
 330   const int               _num_threads;
 331  public:
 332   bool is_valid(int id) const { return id < _num_threads; }
 333   ParallelTaskTerminator* terminator() { return &_term; }
 334 };
 335 
 336 ParScanThreadStateSet::ParScanThreadStateSet(int num_threads,
 337                                              Space& to_space,
 338                                              ParNewGeneration& young_gen,
 339                                              Generation& old_gen,
 340                                              ObjToScanQueueSet& queue_set,
 341                                              Stack<oop, mtGC>* overflow_stacks,
 342                                              PreservedMarksSet& preserved_marks_set,
 343                                              size_t desired_plab_sz,
 344                                              ParallelTaskTerminator& term)
 345   : _young_gen(young_gen),
 346     _old_gen(old_gen),
 347     _term(term),
 348     _per_thread_states(NEW_RESOURCE_ARRAY(ParScanThreadState, num_threads)),
 349     _num_threads(num_threads)
 350 {
 351   assert(num_threads > 0, "sanity check!");
 352   assert(ParGCUseLocalOverflow == (overflow_stacks != NULL),
 353          "overflow_stack allocation mismatch");
 354   // Initialize states.
 355   for (int i = 0; i < num_threads; ++i) {
 356     new(_per_thread_states + i)
 357       ParScanThreadState(&to_space, &young_gen, &old_gen, i, &queue_set,
 358                          overflow_stacks, preserved_marks_set.get(i),
 359                          desired_plab_sz, term);
 360   }
 361 }
 362 
 363 inline ParScanThreadState& ParScanThreadStateSet::thread_state(int i) {
 364   assert(i >= 0 && i < _num_threads, "sanity check!");
 365   return _per_thread_states[i];
 366 }
 367 
 368 void ParScanThreadStateSet::trace_promotion_failed(const YoungGCTracer* gc_tracer) {
 369   for (int i = 0; i < _num_threads; ++i) {
 370     if (thread_state(i).promotion_failed()) {
 371       gc_tracer->report_promotion_failed(thread_state(i).promotion_failed_info());
 372       thread_state(i).promotion_failed_info().reset();
 373     }
 374   }
 375 }
 376 
 377 void ParScanThreadStateSet::reset(uint active_threads, bool promotion_failed) {
 378   _term.reset_for_reuse(active_threads);
 379   if (promotion_failed) {
 380     for (int i = 0; i < _num_threads; ++i) {
 381       thread_state(i).print_promotion_failure_size();
 382     }
 383   }
 384 }
 385 
 386 #if TASKQUEUE_STATS
 387 void ParScanThreadState::reset_stats() {
 388   taskqueue_stats().reset();
 389   _term_attempts = 0;
 390   _overflow_refills = 0;
 391   _overflow_refill_objs = 0;
 392 }
 393 
 394 void ParScanThreadStateSet::reset_stats() {
 395   for (int i = 0; i < _num_threads; ++i) {
 396     thread_state(i).reset_stats();
 397   }
 398 }
 399 
 400 void ParScanThreadStateSet::print_termination_stats_hdr(outputStream* const st) {
 401   st->print_raw_cr("GC Termination Stats");
 402   st->print_raw_cr("     elapsed  --strong roots-- -------termination-------");
 403   st->print_raw_cr("thr     ms        ms       %       ms       %   attempts");
 404   st->print_raw_cr("--- --------- --------- ------ --------- ------ --------");
 405 }
 406 
 407 void ParScanThreadStateSet::print_termination_stats() {
 408   Log(gc, task, stats) log;
 409   if (!log.is_debug()) {
 410     return;
 411   }
 412 
 413   ResourceMark rm;
 414   LogStream ls(log.debug());
 415   outputStream* st = &ls;
 416 
 417   print_termination_stats_hdr(st);
 418 
 419   for (int i = 0; i < _num_threads; ++i) {
 420     const ParScanThreadState & pss = thread_state(i);
 421     const double elapsed_ms = pss.elapsed_time() * 1000.0;
 422     const double s_roots_ms = pss.strong_roots_time() * 1000.0;
 423     const double term_ms = pss.term_time() * 1000.0;
 424     st->print_cr("%3d %9.2f %9.2f %6.2f %9.2f %6.2f " SIZE_FORMAT_W(8),
 425                  i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
 426                  term_ms, term_ms * 100 / elapsed_ms, pss.term_attempts());
 427   }
 428 }
 429 
 430 // Print stats related to work queue activity.
 431 void ParScanThreadStateSet::print_taskqueue_stats_hdr(outputStream* const st) {
 432   st->print_raw_cr("GC Task Stats");
 433   st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
 434   st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
 435 }
 436 
 437 void ParScanThreadStateSet::print_taskqueue_stats() {
 438   if (!log_develop_is_enabled(Trace, gc, task, stats)) {
 439     return;
 440   }
 441   Log(gc, task, stats) log;
 442   ResourceMark rm;
 443   LogStream ls(log.trace());
 444   outputStream* st = &ls;
 445   print_taskqueue_stats_hdr(st);
 446 
 447   TaskQueueStats totals;
 448   for (int i = 0; i < _num_threads; ++i) {
 449     const ParScanThreadState & pss = thread_state(i);
 450     const TaskQueueStats & stats = pss.taskqueue_stats();
 451     st->print("%3d ", i); stats.print(st); st->cr();
 452     totals += stats;
 453 
 454     if (pss.overflow_refills() > 0) {
 455       st->print_cr("    " SIZE_FORMAT_W(10) " overflow refills    "
 456                    SIZE_FORMAT_W(10) " overflow objects",
 457                    pss.overflow_refills(), pss.overflow_refill_objs());
 458     }
 459   }
 460   st->print("tot "); totals.print(st); st->cr();
 461 
 462   DEBUG_ONLY(totals.verify());
 463 }
 464 #endif // TASKQUEUE_STATS
 465 
 466 void ParScanThreadStateSet::flush() {
 467   // Work in this loop should be kept as lightweight as
 468   // possible since this might otherwise become a bottleneck
 469   // to scaling. Should we add heavy-weight work into this
 470   // loop, consider parallelizing the loop into the worker threads.
 471   for (int i = 0; i < _num_threads; ++i) {
 472     ParScanThreadState& par_scan_state = thread_state(i);
 473 
 474     // Flush stats related to To-space PLAB activity and
 475     // retire the last buffer.
 476     par_scan_state.to_space_alloc_buffer()->flush_and_retire_stats(_young_gen.plab_stats());
 477 
 478     // Every thread has its own age table.  We need to merge
 479     // them all into one.
 480     AgeTable *local_table = par_scan_state.age_table();
 481     _young_gen.age_table()->merge(local_table);
 482 
 483     // Inform old gen that we're done.
 484     _old_gen.par_promote_alloc_done(i);
 485   }
 486 
 487   if (UseConcMarkSweepGC) {
 488     // We need to call this even when ResizeOldPLAB is disabled
 489     // so as to avoid breaking some asserts. While we may be able
 490     // to avoid this by reorganizing the code a bit, I am loathe
 491     // to do that unless we find cases where ergo leads to bad
 492     // performance.
 493     CompactibleFreeListSpaceLAB::compute_desired_plab_size();
 494   }
 495 }
 496 
 497 ParScanClosure::ParScanClosure(ParNewGeneration* g,
 498                                ParScanThreadState* par_scan_state) :
 499   OopsInClassLoaderDataOrGenClosure(g), _par_scan_state(par_scan_state), _g(g) {
 500   _boundary = _g->reserved().end();
 501 }
 502 
 503 void ParScanWithBarrierClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, true, false); }
 504 void ParScanWithBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, true, false); }
 505 
 506 void ParScanWithoutBarrierClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, false, false); }
 507 void ParScanWithoutBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, false, false); }
 508 
 509 void ParRootScanWithBarrierTwoGensClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, true, true); }
 510 void ParRootScanWithBarrierTwoGensClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, true, true); }
 511 
 512 void ParRootScanWithoutBarrierClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, false, true); }
 513 void ParRootScanWithoutBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, false, true); }
 514 
 515 ParScanWeakRefClosure::ParScanWeakRefClosure(ParNewGeneration* g,
 516                                              ParScanThreadState* par_scan_state)
 517   : ScanWeakRefClosure(g), _par_scan_state(par_scan_state)
 518 {}
 519 
 520 void ParScanWeakRefClosure::do_oop(oop* p)       { ParScanWeakRefClosure::do_oop_work(p); }
 521 void ParScanWeakRefClosure::do_oop(narrowOop* p) { ParScanWeakRefClosure::do_oop_work(p); }
 522 
 523 #ifdef WIN32
 524 #pragma warning(disable: 4786) /* identifier was truncated to '255' characters in the browser information */
 525 #endif
 526 
 527 ParEvacuateFollowersClosure::ParEvacuateFollowersClosure(
 528     ParScanThreadState* par_scan_state_,
 529     ParScanWithoutBarrierClosure* to_space_closure_,
 530     ParScanWithBarrierClosure* old_gen_closure_,
 531     ParRootScanWithoutBarrierClosure* to_space_root_closure_,
 532     ParNewGeneration* par_gen_,
 533     ParRootScanWithBarrierTwoGensClosure* old_gen_root_closure_,
 534     ObjToScanQueueSet* task_queues_,
 535     ParallelTaskTerminator* terminator_) :
 536 
 537     _par_scan_state(par_scan_state_),
 538     _to_space_closure(to_space_closure_),
 539     _old_gen_closure(old_gen_closure_),
 540     _to_space_root_closure(to_space_root_closure_),
 541     _old_gen_root_closure(old_gen_root_closure_),
 542     _par_gen(par_gen_),
 543     _task_queues(task_queues_),
 544     _terminator(terminator_)
 545 {}
 546 
 547 void ParEvacuateFollowersClosure::do_void() {
 548   ObjToScanQueue* work_q = par_scan_state()->work_queue();
 549 
 550   while (true) {
 551     // Scan to-space and old-gen objs until we run out of both.
 552     oop obj_to_scan;
 553     par_scan_state()->trim_queues(0);
 554 
 555     // We have no local work, attempt to steal from other threads.
 556 
 557     // Attempt to steal work from promoted.
 558     if (task_queues()->steal(par_scan_state()->thread_num(),
 559                              par_scan_state()->hash_seed(),
 560                              obj_to_scan)) {
 561       bool res = work_q->push(obj_to_scan);
 562       assert(res, "Empty queue should have room for a push.");
 563 
 564       // If successful, goto Start.
 565       continue;
 566 
 567       // Try global overflow list.
 568     } else if (par_gen()->take_from_overflow_list(par_scan_state())) {
 569       continue;
 570     }
 571 
 572     // Otherwise, offer termination.
 573     par_scan_state()->start_term_time();
 574     if (terminator()->offer_termination()) break;
 575     par_scan_state()->end_term_time();
 576   }
 577   assert(par_gen()->_overflow_list == NULL && par_gen()->_num_par_pushes == 0,
 578          "Broken overflow list?");
 579   // Finish the last termination pause.
 580   par_scan_state()->end_term_time();
 581 }
 582 
 583 ParNewGenTask::ParNewGenTask(ParNewGeneration* young_gen,
 584                              Generation* old_gen,
 585                              HeapWord* young_old_boundary,
 586                              ParScanThreadStateSet* state_set,
 587                              StrongRootsScope* strong_roots_scope) :
 588     AbstractGangTask("ParNewGeneration collection"),
 589     _young_gen(young_gen), _old_gen(old_gen),
 590     _young_old_boundary(young_old_boundary),
 591     _state_set(state_set),
 592     _strong_roots_scope(strong_roots_scope)
 593 {}
 594 
 595 void ParNewGenTask::work(uint worker_id) {
 596   CMSHeap* heap = CMSHeap::heap();
 597   // Since this is being done in a separate thread, need new resource
 598   // and handle marks.
 599   ResourceMark rm;
 600   HandleMark hm;
 601 
 602   ParScanThreadState& par_scan_state = _state_set->thread_state(worker_id);
 603   assert(_state_set->is_valid(worker_id), "Should not have been called");
 604 
 605   par_scan_state.set_young_old_boundary(_young_old_boundary);
 606 
 607   CLDScanClosure cld_scan_closure(&par_scan_state.to_space_root_closure(),
 608                                   heap->rem_set()->cld_rem_set()->accumulate_modified_oops());
 609 
 610   par_scan_state.start_strong_roots();
 611   heap->young_process_roots(_strong_roots_scope,
 612                            &par_scan_state.to_space_root_closure(),
 613                            &par_scan_state.older_gen_closure(),
 614                            &cld_scan_closure);
 615 
 616   par_scan_state.end_strong_roots();
 617 
 618   // "evacuate followers".
 619   par_scan_state.evacuate_followers_closure().do_void();
 620 
 621   // This will collapse this worker's promoted object list that's
 622   // created during the main ParNew parallel phase of ParNew. This has
 623   // to be called after all workers have finished promoting objects
 624   // and scanning promoted objects. It should be safe calling it from
 625   // here, given that we can only reach here after all thread have
 626   // offered termination, i.e., after there is no more work to be
 627   // done. It will also disable promotion tracking for the rest of
 628   // this GC as it's not necessary to be on during reference processing.
 629   _old_gen->par_oop_since_save_marks_iterate_done((int) worker_id);
 630 }
 631 
 632 ParNewGeneration::ParNewGeneration(ReservedSpace rs, size_t initial_byte_size)
 633   : DefNewGeneration(rs, initial_byte_size, "PCopy"),
 634   _overflow_list(NULL),
 635   _is_alive_closure(this),
 636   _plab_stats("Young", YoungPLABSize, PLABWeight)
 637 {
 638   NOT_PRODUCT(_overflow_counter = ParGCWorkQueueOverflowInterval;)
 639   NOT_PRODUCT(_num_par_pushes = 0;)
 640   _task_queues = new ObjToScanQueueSet(ParallelGCThreads);
 641   guarantee(_task_queues != NULL, "task_queues allocation failure.");
 642 
 643   for (uint i = 0; i < ParallelGCThreads; i++) {
 644     ObjToScanQueue *q = new ObjToScanQueue();
 645     guarantee(q != NULL, "work_queue Allocation failure.");
 646     _task_queues->register_queue(i, q);
 647   }
 648 
 649   for (uint i = 0; i < ParallelGCThreads; i++) {
 650     _task_queues->queue(i)->initialize();
 651   }
 652 
 653   _overflow_stacks = NULL;
 654   if (ParGCUseLocalOverflow) {
 655     // typedef to workaround NEW_C_HEAP_ARRAY macro, which can not deal with ','
 656     typedef Stack<oop, mtGC> GCOopStack;
 657 
 658     _overflow_stacks = NEW_C_HEAP_ARRAY(GCOopStack, ParallelGCThreads, mtGC);
 659     for (size_t i = 0; i < ParallelGCThreads; ++i) {
 660       new (_overflow_stacks + i) Stack<oop, mtGC>();
 661     }
 662   }
 663 
 664   if (UsePerfData) {
 665     EXCEPTION_MARK;
 666     ResourceMark rm;
 667 
 668     const char* cname =
 669          PerfDataManager::counter_name(_gen_counters->name_space(), "threads");
 670     PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_None,
 671                                      ParallelGCThreads, CHECK);
 672   }
 673 }
 674 
 675 // ParNewGeneration::
 676 ParKeepAliveClosure::ParKeepAliveClosure(ParScanWeakRefClosure* cl) :
 677   DefNewGeneration::KeepAliveClosure(cl), _par_cl(cl) {}
 678 
 679 template <class T>
 680 void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop_work(T* p) {
 681 #ifdef ASSERT
 682   {
 683     oop obj = RawAccess<OOP_NOT_NULL>::oop_load(p);
 684     // We never expect to see a null reference being processed
 685     // as a weak reference.
 686     assert(oopDesc::is_oop(obj), "expected an oop while scanning weak refs");
 687   }
 688 #endif // ASSERT
 689 
 690   _par_cl->do_oop_nv(p);
 691 
 692   if (CMSHeap::heap()->is_in_reserved(p)) {
 693     oop obj = RawAccess<OOP_NOT_NULL>::oop_load(p);;
 694     _rs->write_ref_field_gc_par(p, obj);
 695   }
 696 }
 697 
 698 void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(oop* p)       { ParKeepAliveClosure::do_oop_work(p); }
 699 void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(narrowOop* p) { ParKeepAliveClosure::do_oop_work(p); }
 700 
 701 // ParNewGeneration::
 702 KeepAliveClosure::KeepAliveClosure(ScanWeakRefClosure* cl) :
 703   DefNewGeneration::KeepAliveClosure(cl) {}
 704 
 705 template <class T>
 706 void /*ParNewGeneration::*/KeepAliveClosure::do_oop_work(T* p) {
 707 #ifdef ASSERT
 708   {
 709     oop obj = RawAccess<OOP_NOT_NULL>::oop_load(p);
 710     // We never expect to see a null reference being processed
 711     // as a weak reference.
 712     assert(oopDesc::is_oop(obj), "expected an oop while scanning weak refs");
 713   }
 714 #endif // ASSERT
 715 
 716   _cl->do_oop_nv(p);
 717 
 718   if (CMSHeap::heap()->is_in_reserved(p)) {
 719     oop obj = RawAccess<OOP_NOT_NULL>::oop_load(p);
 720     _rs->write_ref_field_gc_par(p, obj);
 721   }
 722 }
 723 
 724 void /*ParNewGeneration::*/KeepAliveClosure::do_oop(oop* p)       { KeepAliveClosure::do_oop_work(p); }
 725 void /*ParNewGeneration::*/KeepAliveClosure::do_oop(narrowOop* p) { KeepAliveClosure::do_oop_work(p); }
 726 
 727 template <class T> void ScanClosureWithParBarrier::do_oop_work(T* p) {
 728   T heap_oop = RawAccess<>::oop_load(p);
 729   if (!CompressedOops::is_null(heap_oop)) {
 730     oop obj = CompressedOops::decode_not_null(heap_oop);
 731     if ((HeapWord*)obj < _boundary) {
 732       assert(!_g->to()->is_in_reserved(obj), "Scanning field twice?");
 733       oop new_obj = obj->is_forwarded()
 734                       ? obj->forwardee()
 735                       : _g->DefNewGeneration::copy_to_survivor_space(obj);
 736       RawAccess<OOP_NOT_NULL>::oop_store(p, new_obj);
 737     }
 738     if (_gc_barrier) {
 739       // If p points to a younger generation, mark the card.
 740       if ((HeapWord*)obj < _gen_boundary) {
 741         _rs->write_ref_field_gc_par(p, obj);
 742       }
 743     }
 744   }
 745 }
 746 
 747 void ScanClosureWithParBarrier::do_oop(oop* p)       { ScanClosureWithParBarrier::do_oop_work(p); }
 748 void ScanClosureWithParBarrier::do_oop(narrowOop* p) { ScanClosureWithParBarrier::do_oop_work(p); }
 749 
 750 class ParNewRefProcTaskProxy: public AbstractGangTask {
 751   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
 752 public:
 753   ParNewRefProcTaskProxy(ProcessTask& task,
 754                          ParNewGeneration& young_gen,
 755                          Generation& old_gen,
 756                          HeapWord* young_old_boundary,
 757                          ParScanThreadStateSet& state_set);
 758 
 759 private:
 760   virtual void work(uint worker_id);
 761 private:
 762   ParNewGeneration&      _young_gen;
 763   ProcessTask&           _task;
 764   Generation&            _old_gen;
 765   HeapWord*              _young_old_boundary;
 766   ParScanThreadStateSet& _state_set;
 767 };
 768 
 769 ParNewRefProcTaskProxy::ParNewRefProcTaskProxy(ProcessTask& task,
 770                                                ParNewGeneration& young_gen,
 771                                                Generation& old_gen,
 772                                                HeapWord* young_old_boundary,
 773                                                ParScanThreadStateSet& state_set)
 774   : AbstractGangTask("ParNewGeneration parallel reference processing"),
 775     _young_gen(young_gen),
 776     _task(task),
 777     _old_gen(old_gen),
 778     _young_old_boundary(young_old_boundary),
 779     _state_set(state_set)
 780 { }
 781 
 782 void ParNewRefProcTaskProxy::work(uint worker_id) {
 783   ResourceMark rm;
 784   HandleMark hm;
 785   ParScanThreadState& par_scan_state = _state_set.thread_state(worker_id);
 786   par_scan_state.set_young_old_boundary(_young_old_boundary);
 787   _task.work(worker_id, par_scan_state.is_alive_closure(),
 788              par_scan_state.keep_alive_closure(),
 789              par_scan_state.evacuate_followers_closure());
 790 }
 791 
 792 void ParNewRefProcTaskExecutor::execute(ProcessTask& task) {
 793   CMSHeap* gch = CMSHeap::heap();
 794   WorkGang* workers = gch->workers();
 795   assert(workers != NULL, "Need parallel worker threads.");
 796   _state_set.reset(workers->active_workers(), _young_gen.promotion_failed());
 797   ParNewRefProcTaskProxy rp_task(task, _young_gen, _old_gen,
 798                                  _young_gen.reserved().end(), _state_set);
 799   workers->run_task(&rp_task);
 800   _state_set.reset(0 /* bad value in debug if not reset */,
 801                    _young_gen.promotion_failed());
 802 }
 803 
 804 void ParNewRefProcTaskExecutor::set_single_threaded_mode() {
 805   _state_set.flush();
 806   CMSHeap* heap = CMSHeap::heap();
 807   heap->save_marks();
 808 }
 809 
 810 ScanClosureWithParBarrier::
 811 ScanClosureWithParBarrier(ParNewGeneration* g, bool gc_barrier) :
 812   ScanClosure(g, gc_barrier)
 813 { }
 814 
 815 template <typename OopClosureType1, typename OopClosureType2>
 816 EvacuateFollowersClosureGeneral<OopClosureType1, OopClosureType2>::
 817 EvacuateFollowersClosureGeneral(CMSHeap* heap,
 818                                 OopClosureType1* cur,
 819                                 OopClosureType2* older) :
 820   _heap(heap),
 821   _scan_cur_or_nonheap(cur), _scan_older(older)
 822 { }
 823 
 824 template <typename OopClosureType1, typename OopClosureType2>
 825 void EvacuateFollowersClosureGeneral<OopClosureType1, OopClosureType2>::do_void() {
 826   do {
 827     _heap->oop_since_save_marks_iterate(_scan_cur_or_nonheap,
 828                                         _scan_older);
 829   } while (!_heap->no_allocs_since_save_marks());
 830 }
 831 
 832 // A Generation that does parallel young-gen collection.
 833 
 834 void ParNewGeneration::handle_promotion_failed(CMSHeap* gch, ParScanThreadStateSet& thread_state_set) {
 835   assert(_promo_failure_scan_stack.is_empty(), "post condition");
 836   _promo_failure_scan_stack.clear(true); // Clear cached segments.
 837 
 838   remove_forwarding_pointers();
 839   log_info(gc, promotion)("Promotion failed");
 840   // All the spaces are in play for mark-sweep.
 841   swap_spaces();  // Make life simpler for CMS || rescan; see 6483690.
 842   from()->set_next_compaction_space(to());
 843   gch->set_incremental_collection_failed();
 844   // Inform the next generation that a promotion failure occurred.
 845   _old_gen->promotion_failure_occurred();
 846 
 847   // Trace promotion failure in the parallel GC threads
 848   thread_state_set.trace_promotion_failed(gc_tracer());
 849   // Single threaded code may have reported promotion failure to the global state
 850   if (_promotion_failed_info.has_failed()) {
 851     _gc_tracer.report_promotion_failed(_promotion_failed_info);
 852   }
 853   // Reset the PromotionFailureALot counters.
 854   NOT_PRODUCT(gch->reset_promotion_should_fail();)
 855 }
 856 
 857 void ParNewGeneration::collect(bool   full,
 858                                bool   clear_all_soft_refs,
 859                                size_t size,
 860                                bool   is_tlab) {
 861   assert(full || size > 0, "otherwise we don't want to collect");
 862 
 863   CMSHeap* gch = CMSHeap::heap();
 864 
 865   _gc_timer->register_gc_start();
 866 
 867   AdaptiveSizePolicy* size_policy = gch->size_policy();
 868   WorkGang* workers = gch->workers();
 869   assert(workers != NULL, "Need workgang for parallel work");
 870   uint active_workers =
 871        AdaptiveSizePolicy::calc_active_workers(workers->total_workers(),
 872                                                workers->active_workers(),
 873                                                Threads::number_of_non_daemon_threads());
 874   active_workers = workers->update_active_workers(active_workers);
 875   log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers->total_workers());
 876 
 877   _old_gen = gch->old_gen();
 878 
 879   // If the next generation is too full to accommodate worst-case promotion
 880   // from this generation, pass on collection; let the next generation
 881   // do it.
 882   if (!collection_attempt_is_safe()) {
 883     gch->set_incremental_collection_failed();  // slight lie, in that we did not even attempt one
 884     return;
 885   }
 886   assert(to()->is_empty(), "Else not collection_attempt_is_safe");
 887 
 888   _gc_tracer.report_gc_start(gch->gc_cause(), _gc_timer->gc_start());
 889   gch->trace_heap_before_gc(gc_tracer());
 890 
 891   init_assuming_no_promotion_failure();
 892 
 893   if (UseAdaptiveSizePolicy) {
 894     set_survivor_overflow(false);
 895     size_policy->minor_collection_begin();
 896   }
 897 
 898   GCTraceTime(Trace, gc, phases) t1("ParNew", NULL, gch->gc_cause());
 899 
 900   age_table()->clear();
 901   to()->clear(SpaceDecorator::Mangle);
 902 
 903   gch->save_marks();
 904 
 905   // Set the correct parallelism (number of queues) in the reference processor
 906   ref_processor()->set_active_mt_degree(active_workers);
 907 
 908   // Need to initialize the preserved marks before the ThreadStateSet c'tor.
 909   _preserved_marks_set.init(active_workers);
 910 
 911   // Always set the terminator for the active number of workers
 912   // because only those workers go through the termination protocol.
 913   ParallelTaskTerminator _term(active_workers, task_queues());
 914   ParScanThreadStateSet thread_state_set(active_workers,
 915                                          *to(), *this, *_old_gen, *task_queues(),
 916                                          _overflow_stacks, _preserved_marks_set,
 917                                          desired_plab_sz(), _term);
 918 
 919   thread_state_set.reset(active_workers, promotion_failed());
 920 
 921   {
 922     StrongRootsScope srs(active_workers);
 923 
 924     ParNewGenTask tsk(this, _old_gen, reserved().end(), &thread_state_set, &srs);
 925     gch->rem_set()->prepare_for_younger_refs_iterate(true);
 926     // It turns out that even when we're using 1 thread, doing the work in a
 927     // separate thread causes wide variance in run times.  We can't help this
 928     // in the multi-threaded case, but we special-case n=1 here to get
 929     // repeatable measurements of the 1-thread overhead of the parallel code.
 930     // Might multiple workers ever be used?  If yes, initialization
 931     // has been done such that the single threaded path should not be used.
 932     if (workers->total_workers() > 1) {
 933       workers->run_task(&tsk);
 934     } else {
 935       tsk.work(0);
 936     }
 937   }
 938 
 939   thread_state_set.reset(0 /* Bad value in debug if not reset */,
 940                          promotion_failed());
 941 
 942   // Trace and reset failed promotion info.
 943   if (promotion_failed()) {
 944     thread_state_set.trace_promotion_failed(gc_tracer());
 945   }
 946 
 947   // Process (weak) reference objects found during scavenge.
 948   ReferenceProcessor* rp = ref_processor();
 949   IsAliveClosure is_alive(this);
 950   ScanWeakRefClosure scan_weak_ref(this);
 951   KeepAliveClosure keep_alive(&scan_weak_ref);
 952   ScanClosure               scan_without_gc_barrier(this, false);
 953   ScanClosureWithParBarrier scan_with_gc_barrier(this, true);
 954   set_promo_failure_scan_stack_closure(&scan_without_gc_barrier);
 955   EvacuateFollowersClosureGeneral<ScanClosure, ScanClosureWithParBarrier> evacuate_followers(
 956       gch, &scan_without_gc_barrier, &scan_with_gc_barrier);
 957   rp->setup_policy(clear_all_soft_refs);
 958   // Can  the mt_degree be set later (at run_task() time would be best)?
 959   rp->set_active_mt_degree(active_workers);
 960   ReferenceProcessorStats stats;
 961   ReferenceProcessorPhaseTimes pt(_gc_timer, rp->num_queues());
 962   if (rp->processing_is_mt()) {
 963     ParNewRefProcTaskExecutor task_executor(*this, *_old_gen, thread_state_set);
 964     stats = rp->process_discovered_references(&is_alive, &keep_alive,
 965                                               &evacuate_followers, &task_executor,
 966                                               &pt);
 967   } else {
 968     thread_state_set.flush();
 969     gch->save_marks();
 970     stats = rp->process_discovered_references(&is_alive, &keep_alive,
 971                                               &evacuate_followers, NULL,
 972                                               &pt);
 973   }
 974   _gc_tracer.report_gc_reference_stats(stats);
 975   _gc_tracer.report_tenuring_threshold(tenuring_threshold());
 976   pt.print_all_references();
 977 
 978   assert(gch->no_allocs_since_save_marks(), "evacuation should be done at this point");
 979 
 980   WeakProcessor::weak_oops_do(&is_alive, &keep_alive);
 981 
 982   // Verify that the usage of keep_alive only forwarded
 983   // the oops and did not find anything new to copy.
 984   assert(gch->no_allocs_since_save_marks(), "unexpectedly copied objects");
 985 
 986   if (!promotion_failed()) {
 987     // Swap the survivor spaces.
 988     eden()->clear(SpaceDecorator::Mangle);
 989     from()->clear(SpaceDecorator::Mangle);
 990     if (ZapUnusedHeapArea) {
 991       // This is now done here because of the piece-meal mangling which
 992       // can check for valid mangling at intermediate points in the
 993       // collection(s).  When a young collection fails to collect
 994       // sufficient space resizing of the young generation can occur
 995       // and redistribute the spaces in the young generation.  Mangle
 996       // here so that unzapped regions don't get distributed to
 997       // other spaces.
 998       to()->mangle_unused_area();
 999     }
1000     swap_spaces();
1001 
1002     // A successful scavenge should restart the GC time limit count which is
1003     // for full GC's.
1004     size_policy->reset_gc_overhead_limit_count();
1005 
1006     assert(to()->is_empty(), "to space should be empty now");
1007 
1008     adjust_desired_tenuring_threshold();
1009   } else {
1010     handle_promotion_failed(gch, thread_state_set);
1011   }
1012   _preserved_marks_set.reclaim();
1013   // set new iteration safe limit for the survivor spaces
1014   from()->set_concurrent_iteration_safe_limit(from()->top());
1015   to()->set_concurrent_iteration_safe_limit(to()->top());
1016 
1017   plab_stats()->adjust_desired_plab_sz();
1018 
1019   TASKQUEUE_STATS_ONLY(thread_state_set.print_termination_stats());
1020   TASKQUEUE_STATS_ONLY(thread_state_set.print_taskqueue_stats());
1021 
1022   if (UseAdaptiveSizePolicy) {
1023     size_policy->minor_collection_end(gch->gc_cause());
1024     size_policy->avg_survived()->sample(from()->used());
1025   }
1026 
1027   // We need to use a monotonically non-decreasing time in ms
1028   // or we will see time-warp warnings and os::javaTimeMillis()
1029   // does not guarantee monotonicity.
1030   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
1031   update_time_of_last_gc(now);
1032 
1033   rp->set_enqueuing_is_done(true);
1034   rp->verify_no_references_recorded();
1035 
1036   gch->trace_heap_after_gc(gc_tracer());
1037 
1038   _gc_timer->register_gc_end();
1039 
1040   _gc_tracer.report_gc_end(_gc_timer->gc_end(), _gc_timer->time_partitions());
1041 }
1042 
1043 size_t ParNewGeneration::desired_plab_sz() {
1044   return _plab_stats.desired_plab_sz(CMSHeap::heap()->workers()->active_workers());
1045 }
1046 
1047 static int sum;
1048 void ParNewGeneration::waste_some_time() {
1049   for (int i = 0; i < 100; i++) {
1050     sum += i;
1051   }
1052 }
1053 
1054 static const oop ClaimedForwardPtr = cast_to_oop<intptr_t>(0x4);
1055 
1056 // Because of concurrency, there are times where an object for which
1057 // "is_forwarded()" is true contains an "interim" forwarding pointer
1058 // value.  Such a value will soon be overwritten with a real value.
1059 // This method requires "obj" to have a forwarding pointer, and waits, if
1060 // necessary for a real one to be inserted, and returns it.
1061 
1062 oop ParNewGeneration::real_forwardee(oop obj) {
1063   oop forward_ptr = obj->forwardee();
1064   if (forward_ptr != ClaimedForwardPtr) {
1065     return forward_ptr;
1066   } else {
1067     return real_forwardee_slow(obj);
1068   }
1069 }
1070 
1071 oop ParNewGeneration::real_forwardee_slow(oop obj) {
1072   // Spin-read if it is claimed but not yet written by another thread.
1073   oop forward_ptr = obj->forwardee();
1074   while (forward_ptr == ClaimedForwardPtr) {
1075     waste_some_time();
1076     assert(obj->is_forwarded(), "precondition");
1077     forward_ptr = obj->forwardee();
1078   }
1079   return forward_ptr;
1080 }
1081 
1082 // Multiple GC threads may try to promote an object.  If the object
1083 // is successfully promoted, a forwarding pointer will be installed in
1084 // the object in the young generation.  This method claims the right
1085 // to install the forwarding pointer before it copies the object,
1086 // thus avoiding the need to undo the copy as in
1087 // copy_to_survivor_space_avoiding_with_undo.
1088 
1089 oop ParNewGeneration::copy_to_survivor_space(ParScanThreadState* par_scan_state,
1090                                              oop old,
1091                                              size_t sz,
1092                                              markOop m) {
1093   // In the sequential version, this assert also says that the object is
1094   // not forwarded.  That might not be the case here.  It is the case that
1095   // the caller observed it to be not forwarded at some time in the past.
1096   assert(is_in_reserved(old), "shouldn't be scavenging this oop");
1097 
1098   // The sequential code read "old->age()" below.  That doesn't work here,
1099   // since the age is in the mark word, and that might be overwritten with
1100   // a forwarding pointer by a parallel thread.  So we must save the mark
1101   // word in a local and then analyze it.
1102   oopDesc dummyOld;
1103   dummyOld.set_mark_raw(m);
1104   assert(!dummyOld.is_forwarded(),
1105          "should not be called with forwarding pointer mark word.");
1106 
1107   oop new_obj = NULL;
1108   oop forward_ptr;
1109 
1110   // Try allocating obj in to-space (unless too old)
1111   if (dummyOld.age() < tenuring_threshold()) {
1112     new_obj = (oop)par_scan_state->alloc_in_to_space(sz);
1113     if (new_obj == NULL) {
1114       set_survivor_overflow(true);
1115     }
1116   }
1117 
1118   if (new_obj == NULL) {
1119     // Either to-space is full or we decided to promote try allocating obj tenured
1120 
1121     // Attempt to install a null forwarding pointer (atomically),
1122     // to claim the right to install the real forwarding pointer.
1123     forward_ptr = old->forward_to_atomic(ClaimedForwardPtr);
1124     if (forward_ptr != NULL) {
1125       // someone else beat us to it.
1126         return real_forwardee(old);
1127     }
1128 
1129     if (!_promotion_failed) {
1130       new_obj = _old_gen->par_promote(par_scan_state->thread_num(),
1131                                       old, m, sz);
1132     }
1133 
1134     if (new_obj == NULL) {
1135       // promotion failed, forward to self
1136       _promotion_failed = true;
1137       new_obj = old;
1138 
1139       par_scan_state->preserved_marks()->push_if_necessary(old, m);
1140       par_scan_state->register_promotion_failure(sz);
1141     }
1142 
1143     old->forward_to(new_obj);
1144     forward_ptr = NULL;
1145   } else {
1146     // Is in to-space; do copying ourselves.
1147     Copy::aligned_disjoint_words((HeapWord*)old, (HeapWord*)new_obj, sz);
1148     assert(CMSHeap::heap()->is_in_reserved(new_obj), "illegal forwarding pointer value.");
1149     forward_ptr = old->forward_to_atomic(new_obj);
1150     // Restore the mark word copied above.
1151     new_obj->set_mark_raw(m);
1152     // Increment age if obj still in new generation
1153     new_obj->incr_age();
1154     par_scan_state->age_table()->add(new_obj, sz);
1155   }
1156   assert(new_obj != NULL, "just checking");
1157 
1158   // This code must come after the CAS test, or it will print incorrect
1159   // information.
1160   log_develop_trace(gc, scavenge)("{%s %s " PTR_FORMAT " -> " PTR_FORMAT " (%d)}",
1161                                   is_in_reserved(new_obj) ? "copying" : "tenuring",
1162                                   new_obj->klass()->internal_name(), p2i(old), p2i(new_obj), new_obj->size());
1163 
1164   if (forward_ptr == NULL) {
1165     oop obj_to_push = new_obj;
1166     if (par_scan_state->should_be_partially_scanned(obj_to_push, old)) {
1167       // Length field used as index of next element to be scanned.
1168       // Real length can be obtained from real_forwardee()
1169       arrayOop(old)->set_length(0);
1170       obj_to_push = old;
1171       assert(obj_to_push->is_forwarded() && obj_to_push->forwardee() != obj_to_push,
1172              "push forwarded object");
1173     }
1174     // Push it on one of the queues of to-be-scanned objects.
1175     bool simulate_overflow = false;
1176     NOT_PRODUCT(
1177       if (ParGCWorkQueueOverflowALot && should_simulate_overflow()) {
1178         // simulate a stack overflow
1179         simulate_overflow = true;
1180       }
1181     )
1182     if (simulate_overflow || !par_scan_state->work_queue()->push(obj_to_push)) {
1183       // Add stats for overflow pushes.
1184       log_develop_trace(gc)("Queue Overflow");
1185       push_on_overflow_list(old, par_scan_state);
1186       TASKQUEUE_STATS_ONLY(par_scan_state->taskqueue_stats().record_overflow(0));
1187     }
1188 
1189     return new_obj;
1190   }
1191 
1192   // Oops.  Someone beat us to it.  Undo the allocation.  Where did we
1193   // allocate it?
1194   if (is_in_reserved(new_obj)) {
1195     // Must be in to_space.
1196     assert(to()->is_in_reserved(new_obj), "Checking");
1197     if (forward_ptr == ClaimedForwardPtr) {
1198       // Wait to get the real forwarding pointer value.
1199       forward_ptr = real_forwardee(old);
1200     }
1201     par_scan_state->undo_alloc_in_to_space((HeapWord*)new_obj, sz);
1202   }
1203 
1204   return forward_ptr;
1205 }
1206 
1207 #ifndef PRODUCT
1208 // It's OK to call this multi-threaded;  the worst thing
1209 // that can happen is that we'll get a bunch of closely
1210 // spaced simulated overflows, but that's OK, in fact
1211 // probably good as it would exercise the overflow code
1212 // under contention.
1213 bool ParNewGeneration::should_simulate_overflow() {
1214   if (_overflow_counter-- <= 0) { // just being defensive
1215     _overflow_counter = ParGCWorkQueueOverflowInterval;
1216     return true;
1217   } else {
1218     return false;
1219   }
1220 }
1221 #endif
1222 
1223 // In case we are using compressed oops, we need to be careful.
1224 // If the object being pushed is an object array, then its length
1225 // field keeps track of the "grey boundary" at which the next
1226 // incremental scan will be done (see ParGCArrayScanChunk).
1227 // When using compressed oops, this length field is kept in the
1228 // lower 32 bits of the erstwhile klass word and cannot be used
1229 // for the overflow chaining pointer (OCP below). As such the OCP
1230 // would itself need to be compressed into the top 32-bits in this
1231 // case. Unfortunately, see below, in the event that we have a
1232 // promotion failure, the node to be pushed on the list can be
1233 // outside of the Java heap, so the heap-based pointer compression
1234 // would not work (we would have potential aliasing between C-heap
1235 // and Java-heap pointers). For this reason, when using compressed
1236 // oops, we simply use a worker-thread-local, non-shared overflow
1237 // list in the form of a growable array, with a slightly different
1238 // overflow stack draining strategy. If/when we start using fat
1239 // stacks here, we can go back to using (fat) pointer chains
1240 // (although some performance comparisons would be useful since
1241 // single global lists have their own performance disadvantages
1242 // as we were made painfully aware not long ago, see 6786503).
1243 #define BUSY (cast_to_oop<intptr_t>(0x1aff1aff))
1244 void ParNewGeneration::push_on_overflow_list(oop from_space_obj, ParScanThreadState* par_scan_state) {
1245   assert(is_in_reserved(from_space_obj), "Should be from this generation");
1246   if (ParGCUseLocalOverflow) {
1247     // In the case of compressed oops, we use a private, not-shared
1248     // overflow stack.
1249     par_scan_state->push_on_overflow_stack(from_space_obj);
1250   } else {
1251     assert(!UseCompressedOops, "Error");
1252     // if the object has been forwarded to itself, then we cannot
1253     // use the klass pointer for the linked list.  Instead we have
1254     // to allocate an oopDesc in the C-Heap and use that for the linked list.
1255     // XXX This is horribly inefficient when a promotion failure occurs
1256     // and should be fixed. XXX FIX ME !!!
1257 #ifndef PRODUCT
1258     Atomic::inc(&_num_par_pushes);
1259     assert(_num_par_pushes > 0, "Tautology");
1260 #endif
1261     if (from_space_obj->forwardee() == from_space_obj) {
1262       oopDesc* listhead = NEW_C_HEAP_ARRAY(oopDesc, 1, mtGC);
1263       listhead->forward_to(from_space_obj);
1264       from_space_obj = listhead;
1265     }
1266     oop observed_overflow_list = _overflow_list;
1267     oop cur_overflow_list;
1268     do {
1269       cur_overflow_list = observed_overflow_list;
1270       if (cur_overflow_list != BUSY) {
1271         from_space_obj->set_klass_to_list_ptr(cur_overflow_list);
1272       } else {
1273         from_space_obj->set_klass_to_list_ptr(NULL);
1274       }
1275       observed_overflow_list =
1276         Atomic::cmpxchg((oopDesc*)from_space_obj, &_overflow_list, (oopDesc*)cur_overflow_list);
1277     } while (cur_overflow_list != observed_overflow_list);
1278   }
1279 }
1280 
1281 bool ParNewGeneration::take_from_overflow_list(ParScanThreadState* par_scan_state) {
1282   bool res;
1283 
1284   if (ParGCUseLocalOverflow) {
1285     res = par_scan_state->take_from_overflow_stack();
1286   } else {
1287     assert(!UseCompressedOops, "Error");
1288     res = take_from_overflow_list_work(par_scan_state);
1289   }
1290   return res;
1291 }
1292 
1293 
1294 // *NOTE*: The overflow list manipulation code here and
1295 // in CMSCollector:: are very similar in shape,
1296 // except that in the CMS case we thread the objects
1297 // directly into the list via their mark word, and do
1298 // not need to deal with special cases below related
1299 // to chunking of object arrays and promotion failure
1300 // handling.
1301 // CR 6797058 has been filed to attempt consolidation of
1302 // the common code.
1303 // Because of the common code, if you make any changes in
1304 // the code below, please check the CMS version to see if
1305 // similar changes might be needed.
1306 // See CMSCollector::par_take_from_overflow_list() for
1307 // more extensive documentation comments.
1308 bool ParNewGeneration::take_from_overflow_list_work(ParScanThreadState* par_scan_state) {
1309   ObjToScanQueue* work_q = par_scan_state->work_queue();
1310   // How many to take?
1311   size_t objsFromOverflow = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
1312                                  (size_t)ParGCDesiredObjsFromOverflowList);
1313 
1314   assert(!UseCompressedOops, "Error");
1315   assert(par_scan_state->overflow_stack() == NULL, "Error");
1316   if (_overflow_list == NULL) return false;
1317 
1318   // Otherwise, there was something there; try claiming the list.
1319   oop prefix = cast_to_oop(Atomic::xchg((oopDesc*)BUSY, &_overflow_list));
1320   // Trim off a prefix of at most objsFromOverflow items
1321   Thread* tid = Thread::current();
1322   size_t spin_count = ParallelGCThreads;
1323   size_t sleep_time_millis = MAX2((size_t)1, objsFromOverflow/100);
1324   for (size_t spin = 0; prefix == BUSY && spin < spin_count; spin++) {
1325     // someone grabbed it before we did ...
1326     // ... we spin for a short while...
1327     os::sleep(tid, sleep_time_millis, false);
1328     if (_overflow_list == NULL) {
1329       // nothing left to take
1330       return false;
1331     } else if (_overflow_list != BUSY) {
1332      // try and grab the prefix
1333      prefix = cast_to_oop(Atomic::xchg((oopDesc*)BUSY, &_overflow_list));
1334     }
1335   }
1336   if (prefix == NULL || prefix == BUSY) {
1337      // Nothing to take or waited long enough
1338      if (prefix == NULL) {
1339        // Write back the NULL in case we overwrote it with BUSY above
1340        // and it is still the same value.
1341        (void) Atomic::cmpxchg((oopDesc*)NULL, &_overflow_list, (oopDesc*)BUSY);
1342      }
1343      return false;
1344   }
1345   assert(prefix != NULL && prefix != BUSY, "Error");
1346   oop cur = prefix;
1347   for (size_t i = 1; i < objsFromOverflow; ++i) {
1348     oop next = cur->list_ptr_from_klass();
1349     if (next == NULL) break;
1350     cur = next;
1351   }
1352   assert(cur != NULL, "Loop postcondition");
1353 
1354   // Reattach remaining (suffix) to overflow list
1355   oop suffix = cur->list_ptr_from_klass();
1356   if (suffix == NULL) {
1357     // Write back the NULL in lieu of the BUSY we wrote
1358     // above and it is still the same value.
1359     if (_overflow_list == BUSY) {
1360       (void) Atomic::cmpxchg((oopDesc*)NULL, &_overflow_list, (oopDesc*)BUSY);
1361     }
1362   } else {
1363     assert(suffix != BUSY, "Error");
1364     // suffix will be put back on global list
1365     cur->set_klass_to_list_ptr(NULL);     // break off suffix
1366     // It's possible that the list is still in the empty(busy) state
1367     // we left it in a short while ago; in that case we may be
1368     // able to place back the suffix.
1369     oop observed_overflow_list = _overflow_list;
1370     oop cur_overflow_list = observed_overflow_list;
1371     bool attached = false;
1372     while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
1373       observed_overflow_list =
1374         Atomic::cmpxchg((oopDesc*)suffix, &_overflow_list, (oopDesc*)cur_overflow_list);
1375       if (cur_overflow_list == observed_overflow_list) {
1376         attached = true;
1377         break;
1378       } else cur_overflow_list = observed_overflow_list;
1379     }
1380     if (!attached) {
1381       // Too bad, someone else got in in between; we'll need to do a splice.
1382       // Find the last item of suffix list
1383       oop last = suffix;
1384       while (true) {
1385         oop next = last->list_ptr_from_klass();
1386         if (next == NULL) break;
1387         last = next;
1388       }
1389       // Atomically prepend suffix to current overflow list
1390       observed_overflow_list = _overflow_list;
1391       do {
1392         cur_overflow_list = observed_overflow_list;
1393         if (cur_overflow_list != BUSY) {
1394           // Do the splice ...
1395           last->set_klass_to_list_ptr(cur_overflow_list);
1396         } else { // cur_overflow_list == BUSY
1397           last->set_klass_to_list_ptr(NULL);
1398         }
1399         observed_overflow_list =
1400           Atomic::cmpxchg((oopDesc*)suffix, &_overflow_list, (oopDesc*)cur_overflow_list);
1401       } while (cur_overflow_list != observed_overflow_list);
1402     }
1403   }
1404 
1405   // Push objects on prefix list onto this thread's work queue
1406   assert(prefix != NULL && prefix != BUSY, "program logic");
1407   cur = prefix;
1408   ssize_t n = 0;
1409   while (cur != NULL) {
1410     oop obj_to_push = cur->forwardee();
1411     oop next        = cur->list_ptr_from_klass();
1412     cur->set_klass(obj_to_push->klass());
1413     // This may be an array object that is self-forwarded. In that case, the list pointer
1414     // space, cur, is not in the Java heap, but rather in the C-heap and should be freed.
1415     if (!is_in_reserved(cur)) {
1416       // This can become a scaling bottleneck when there is work queue overflow coincident
1417       // with promotion failure.
1418       oopDesc* f = cur;
1419       FREE_C_HEAP_ARRAY(oopDesc, f);
1420     } else if (par_scan_state->should_be_partially_scanned(obj_to_push, cur)) {
1421       assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");
1422       obj_to_push = cur;
1423     }
1424     bool ok = work_q->push(obj_to_push);
1425     assert(ok, "Should have succeeded");
1426     cur = next;
1427     n++;
1428   }
1429   TASKQUEUE_STATS_ONLY(par_scan_state->note_overflow_refill(n));
1430 #ifndef PRODUCT
1431   assert(_num_par_pushes >= n, "Too many pops?");
1432   Atomic::sub(n, &_num_par_pushes);
1433 #endif
1434   return true;
1435 }
1436 #undef BUSY
1437 
1438 void ParNewGeneration::ref_processor_init() {
1439   if (_ref_processor == NULL) {
1440     // Allocate and initialize a reference processor
1441     _span_based_discoverer.set_span(_reserved);
1442     _ref_processor =
1443       new ReferenceProcessor(&_span_based_discoverer,    // span
1444                              ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing
1445                              ParallelGCThreads,          // mt processing degree
1446                              refs_discovery_is_mt(),     // mt discovery
1447                              ParallelGCThreads,          // mt discovery degree
1448                              refs_discovery_is_atomic(), // atomic_discovery
1449                              NULL);                      // is_alive_non_header
1450   }
1451 }
1452 
1453 const char* ParNewGeneration::name() const {
1454   return "par new generation";
1455 }
1456 
1457 void ParNewGeneration::restore_preserved_marks() {
1458   SharedRestorePreservedMarksTaskExecutor task_executor(CMSHeap::heap()->workers());
1459   _preserved_marks_set.restore(&task_executor);
1460 }