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