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/plab.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/strongRootsScope.hpp"
  46 #include "memory/space.hpp"
  47 #include "oops/objArrayOop.hpp"
  48 #include "oops/oop.inline.hpp"
  49 #include "runtime/atomic.inline.hpp"
  50 #include "runtime/handles.hpp"
  51 #include "runtime/handles.inline.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/thread.inline.hpp"
  54 #include "utilities/copy.hpp"
  55 #include "utilities/globalDefinitions.hpp"
  56 #include "utilities/stack.inline.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(GenCollectedHeap::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(GenCollectedHeap::heap()->is_in_reserved(cur), "Should be in heap");
 204     assert(!old_gen()->is_in_reserved(cur), "Should be in young gen");
 205     assert(GenCollectedHeap::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     PLAB* 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           PLAB::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 PLAB::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 
 601   ParScanThreadState& par_scan_state = _state_set->thread_state(worker_id);
 602   assert(_state_set->is_valid(worker_id), "Should not have been called");
 603 
 604   par_scan_state.set_young_old_boundary(_young_old_boundary);
 605 
 606   KlassScanClosure klass_scan_closure(&par_scan_state.to_space_root_closure(),
 607                                       gch->rem_set()->klass_rem_set());
 608   CLDToKlassAndOopClosure cld_scan_closure(&klass_scan_closure,
 609                                            &par_scan_state.to_space_root_closure(),
 610                                            false);
 611 
 612   par_scan_state.start_strong_roots();
 613   gch->gen_process_roots(_gen->level(),
 614                          true,  // Process younger gens, if any,
 615                                 // as strong roots.
 616                          false, // no scope; this is parallel code
 617                          GenCollectedHeap::SO_ScavengeCodeCache,
 618                          GenCollectedHeap::StrongAndWeakRoots,
 619                          &par_scan_state.to_space_root_closure(),
 620                          &par_scan_state.older_gen_closure(),
 621                          &cld_scan_closure);
 622 
 623   par_scan_state.end_strong_roots();
 624 
 625   // "evacuate followers".
 626   par_scan_state.evacuate_followers_closure().do_void();
 627 }
 628 
 629 #ifdef _MSC_VER
 630 #pragma warning( push )
 631 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 632 #endif
 633 ParNewGeneration::
 634 ParNewGeneration(ReservedSpace rs, size_t initial_byte_size, int level)
 635   : DefNewGeneration(rs, initial_byte_size, level, "PCopy"),
 636   _overflow_list(NULL),
 637   _is_alive_closure(this),
 638   _plab_stats(YoungPLABSize, PLABWeight)
 639 {
 640   NOT_PRODUCT(_overflow_counter = ParGCWorkQueueOverflowInterval;)
 641   NOT_PRODUCT(_num_par_pushes = 0;)
 642   _task_queues = new ObjToScanQueueSet(ParallelGCThreads);
 643   guarantee(_task_queues != NULL, "task_queues allocation failure.");
 644 
 645   for (uint i1 = 0; i1 < ParallelGCThreads; i1++) {
 646     ObjToScanQueue *q = new ObjToScanQueue();
 647     guarantee(q != NULL, "work_queue Allocation failure.");
 648     _task_queues->register_queue(i1, q);
 649   }
 650 
 651   for (uint i2 = 0; i2 < ParallelGCThreads; i2++)
 652     _task_queues->queue(i2)->initialize();
 653 
 654   _overflow_stacks = NULL;
 655   if (ParGCUseLocalOverflow) {
 656 
 657     // typedef to workaround NEW_C_HEAP_ARRAY macro, which can not deal
 658     // with ','
 659     typedef Stack<oop, mtGC> GCOopStack;
 660 
 661     _overflow_stacks = NEW_C_HEAP_ARRAY(GCOopStack, ParallelGCThreads, mtGC);
 662     for (size_t i = 0; i < ParallelGCThreads; ++i) {
 663       new (_overflow_stacks + i) Stack<oop, mtGC>();
 664     }
 665   }
 666 
 667   if (UsePerfData) {
 668     EXCEPTION_MARK;
 669     ResourceMark rm;
 670 
 671     const char* cname =
 672          PerfDataManager::counter_name(_gen_counters->name_space(), "threads");
 673     PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_None,
 674                                      ParallelGCThreads, CHECK);
 675   }
 676 }
 677 #ifdef _MSC_VER
 678 #pragma warning( pop )
 679 #endif
 680 
 681 // ParNewGeneration::
 682 ParKeepAliveClosure::ParKeepAliveClosure(ParScanWeakRefClosure* cl) :
 683   DefNewGeneration::KeepAliveClosure(cl), _par_cl(cl) {}
 684 
 685 template <class T>
 686 void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop_work(T* p) {
 687 #ifdef ASSERT
 688   {
 689     assert(!oopDesc::is_null(*p), "expected non-null ref");
 690     oop obj = oopDesc::load_decode_heap_oop_not_null(p);
 691     // We never expect to see a null reference being processed
 692     // as a weak reference.
 693     assert(obj->is_oop(), "expected an oop while scanning weak refs");
 694   }
 695 #endif // ASSERT
 696 
 697   _par_cl->do_oop_nv(p);
 698 
 699   if (GenCollectedHeap::heap()->is_in_reserved(p)) {
 700     oop obj = oopDesc::load_decode_heap_oop_not_null(p);
 701     _rs->write_ref_field_gc_par(p, obj);
 702   }
 703 }
 704 
 705 void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(oop* p)       { ParKeepAliveClosure::do_oop_work(p); }
 706 void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(narrowOop* p) { ParKeepAliveClosure::do_oop_work(p); }
 707 
 708 // ParNewGeneration::
 709 KeepAliveClosure::KeepAliveClosure(ScanWeakRefClosure* cl) :
 710   DefNewGeneration::KeepAliveClosure(cl) {}
 711 
 712 template <class T>
 713 void /*ParNewGeneration::*/KeepAliveClosure::do_oop_work(T* p) {
 714 #ifdef ASSERT
 715   {
 716     assert(!oopDesc::is_null(*p), "expected non-null ref");
 717     oop obj = oopDesc::load_decode_heap_oop_not_null(p);
 718     // We never expect to see a null reference being processed
 719     // as a weak reference.
 720     assert(obj->is_oop(), "expected an oop while scanning weak refs");
 721   }
 722 #endif // ASSERT
 723 
 724   _cl->do_oop_nv(p);
 725 
 726   if (GenCollectedHeap::heap()->is_in_reserved(p)) {
 727     oop obj = oopDesc::load_decode_heap_oop_not_null(p);
 728     _rs->write_ref_field_gc_par(p, obj);
 729   }
 730 }
 731 
 732 void /*ParNewGeneration::*/KeepAliveClosure::do_oop(oop* p)       { KeepAliveClosure::do_oop_work(p); }
 733 void /*ParNewGeneration::*/KeepAliveClosure::do_oop(narrowOop* p) { KeepAliveClosure::do_oop_work(p); }
 734 
 735 template <class T> void ScanClosureWithParBarrier::do_oop_work(T* p) {
 736   T heap_oop = oopDesc::load_heap_oop(p);
 737   if (!oopDesc::is_null(heap_oop)) {
 738     oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
 739     if ((HeapWord*)obj < _boundary) {
 740       assert(!_g->to()->is_in_reserved(obj), "Scanning field twice?");
 741       oop new_obj = obj->is_forwarded()
 742                       ? obj->forwardee()
 743                       : _g->DefNewGeneration::copy_to_survivor_space(obj);
 744       oopDesc::encode_store_heap_oop_not_null(p, new_obj);
 745     }
 746     if (_gc_barrier) {
 747       // If p points to a younger generation, mark the card.
 748       if ((HeapWord*)obj < _gen_boundary) {
 749         _rs->write_ref_field_gc_par(p, obj);
 750       }
 751     }
 752   }
 753 }
 754 
 755 void ScanClosureWithParBarrier::do_oop(oop* p)       { ScanClosureWithParBarrier::do_oop_work(p); }
 756 void ScanClosureWithParBarrier::do_oop(narrowOop* p) { ScanClosureWithParBarrier::do_oop_work(p); }
 757 
 758 class ParNewRefProcTaskProxy: public AbstractGangTask {
 759   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
 760 public:
 761   ParNewRefProcTaskProxy(ProcessTask& task,
 762                          ParNewGeneration& gen,
 763                          Generation& old_gen,
 764                          HeapWord* young_old_boundary,
 765                          ParScanThreadStateSet& state_set);
 766 
 767 private:
 768   virtual void work(uint worker_id);
 769   virtual void set_for_termination(int active_workers) {
 770     _state_set.terminator()->reset_for_reuse(active_workers);
 771   }
 772 private:
 773   ParNewGeneration&      _gen;
 774   ProcessTask&           _task;
 775   Generation&            _old_gen;
 776   HeapWord*              _young_old_boundary;
 777   ParScanThreadStateSet& _state_set;
 778 };
 779 
 780 ParNewRefProcTaskProxy::ParNewRefProcTaskProxy(ProcessTask& task,
 781                                                ParNewGeneration& gen,
 782                                                Generation& old_gen,
 783                                                HeapWord* young_old_boundary,
 784                                                ParScanThreadStateSet& state_set)
 785   : AbstractGangTask("ParNewGeneration parallel reference processing"),
 786     _gen(gen),
 787     _task(task),
 788     _old_gen(old_gen),
 789     _young_old_boundary(young_old_boundary),
 790     _state_set(state_set)
 791 {
 792 }
 793 
 794 void ParNewRefProcTaskProxy::work(uint worker_id)
 795 {
 796   ResourceMark rm;
 797   HandleMark hm;
 798   ParScanThreadState& par_scan_state = _state_set.thread_state(worker_id);
 799   par_scan_state.set_young_old_boundary(_young_old_boundary);
 800   _task.work(worker_id, par_scan_state.is_alive_closure(),
 801              par_scan_state.keep_alive_closure(),
 802              par_scan_state.evacuate_followers_closure());
 803 }
 804 
 805 class ParNewRefEnqueueTaskProxy: public AbstractGangTask {
 806   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
 807   EnqueueTask& _task;
 808 
 809 public:
 810   ParNewRefEnqueueTaskProxy(EnqueueTask& task)
 811     : AbstractGangTask("ParNewGeneration parallel reference enqueue"),
 812       _task(task)
 813   { }
 814 
 815   virtual void work(uint worker_id)
 816   {
 817     _task.work(worker_id);
 818   }
 819 };
 820 
 821 
 822 void ParNewRefProcTaskExecutor::execute(ProcessTask& task)
 823 {
 824   GenCollectedHeap* gch = GenCollectedHeap::heap();
 825   FlexibleWorkGang* workers = gch->workers();
 826   assert(workers != NULL, "Need parallel worker threads.");
 827   _state_set.reset(workers->active_workers(), _generation.promotion_failed());
 828   ParNewRefProcTaskProxy rp_task(task, _generation, *_generation.next_gen(),
 829                                  _generation.reserved().end(), _state_set);
 830   workers->run_task(&rp_task);
 831   _state_set.reset(0 /* bad value in debug if not reset */,
 832                    _generation.promotion_failed());
 833 }
 834 
 835 void ParNewRefProcTaskExecutor::execute(EnqueueTask& task)
 836 {
 837   GenCollectedHeap* gch = GenCollectedHeap::heap();
 838   FlexibleWorkGang* workers = gch->workers();
 839   assert(workers != NULL, "Need parallel worker threads.");
 840   ParNewRefEnqueueTaskProxy enq_task(task);
 841   workers->run_task(&enq_task);
 842 }
 843 
 844 void ParNewRefProcTaskExecutor::set_single_threaded_mode()
 845 {
 846   _state_set.flush();
 847   GenCollectedHeap* gch = GenCollectedHeap::heap();
 848   gch->set_par_threads(0);  // 0 ==> non-parallel.
 849   gch->save_marks();
 850 }
 851 
 852 ScanClosureWithParBarrier::
 853 ScanClosureWithParBarrier(ParNewGeneration* g, bool gc_barrier) :
 854   ScanClosure(g, gc_barrier) {}
 855 
 856 EvacuateFollowersClosureGeneral::
 857 EvacuateFollowersClosureGeneral(GenCollectedHeap* gch, int level,
 858                                 OopsInGenClosure* cur,
 859                                 OopsInGenClosure* older) :
 860   _gch(gch), _level(level),
 861   _scan_cur_or_nonheap(cur), _scan_older(older)
 862 {}
 863 
 864 void EvacuateFollowersClosureGeneral::do_void() {
 865   do {
 866     // Beware: this call will lead to closure applications via virtual
 867     // calls.
 868     _gch->oop_since_save_marks_iterate(_level,
 869                                        _scan_cur_or_nonheap,
 870                                        _scan_older);
 871   } while (!_gch->no_allocs_since_save_marks(_level));
 872 }
 873 
 874 
 875 // A Generation that does parallel young-gen collection.
 876 
 877 void ParNewGeneration::handle_promotion_failed(GenCollectedHeap* gch, ParScanThreadStateSet& thread_state_set) {
 878   assert(_promo_failure_scan_stack.is_empty(), "post condition");
 879   _promo_failure_scan_stack.clear(true); // Clear cached segments.
 880 
 881   remove_forwarding_pointers();
 882   if (PrintGCDetails) {
 883     gclog_or_tty->print(" (promotion failed)");
 884   }
 885   // All the spaces are in play for mark-sweep.
 886   swap_spaces();  // Make life simpler for CMS || rescan; see 6483690.
 887   from()->set_next_compaction_space(to());
 888   gch->set_incremental_collection_failed();
 889   // Inform the next generation that a promotion failure occurred.
 890   _old_gen->promotion_failure_occurred();
 891 
 892   // Trace promotion failure in the parallel GC threads
 893   thread_state_set.trace_promotion_failed(gc_tracer());
 894   // Single threaded code may have reported promotion failure to the global state
 895   if (_promotion_failed_info.has_failed()) {
 896     _gc_tracer.report_promotion_failed(_promotion_failed_info);
 897   }
 898   // Reset the PromotionFailureALot counters.
 899   NOT_PRODUCT(gch->reset_promotion_should_fail();)
 900 }
 901 
 902 void ParNewGeneration::collect(bool   full,
 903                                bool   clear_all_soft_refs,
 904                                size_t size,
 905                                bool   is_tlab) {
 906   assert(full || size > 0, "otherwise we don't want to collect");
 907 
 908   GenCollectedHeap* gch = GenCollectedHeap::heap();
 909 
 910   _gc_timer->register_gc_start();
 911 
 912   AdaptiveSizePolicy* size_policy = gch->gen_policy()->size_policy();
 913   FlexibleWorkGang* workers = gch->workers();
 914   assert(workers != NULL, "Need workgang for parallel work");
 915   int active_workers =
 916       AdaptiveSizePolicy::calc_active_workers(workers->total_workers(),
 917                                    workers->active_workers(),
 918                                    Threads::number_of_non_daemon_threads());
 919   workers->set_active_workers(active_workers);
 920   _old_gen = gch->old_gen();
 921 
 922   // If the next generation is too full to accommodate worst-case promotion
 923   // from this generation, pass on collection; let the next generation
 924   // do it.
 925   if (!collection_attempt_is_safe()) {
 926     gch->set_incremental_collection_failed();  // slight lie, in that we did not even attempt one
 927     return;
 928   }
 929   assert(to()->is_empty(), "Else not collection_attempt_is_safe");
 930 
 931   _gc_tracer.report_gc_start(gch->gc_cause(), _gc_timer->gc_start());
 932   gch->trace_heap_before_gc(gc_tracer());
 933 
 934   init_assuming_no_promotion_failure();
 935 
 936   if (UseAdaptiveSizePolicy) {
 937     set_survivor_overflow(false);
 938     size_policy->minor_collection_begin();
 939   }
 940 
 941   GCTraceTime t1(GCCauseString("GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL, _gc_tracer.gc_id());
 942   // Capture heap used before collection (for printing).
 943   size_t gch_prev_used = gch->used();
 944 
 945   age_table()->clear();
 946   to()->clear(SpaceDecorator::Mangle);
 947 
 948   gch->save_marks();
 949   assert(workers != NULL, "Need parallel worker threads.");
 950   int n_workers = active_workers;
 951 
 952   // Set the correct parallelism (number of queues) in the reference processor
 953   ref_processor()->set_active_mt_degree(n_workers);
 954 
 955   // Always set the terminator for the active number of workers
 956   // because only those workers go through the termination protocol.
 957   ParallelTaskTerminator _term(n_workers, task_queues());
 958   ParScanThreadStateSet thread_state_set(workers->active_workers(),
 959                                          *to(), *this, *_old_gen, *task_queues(),
 960                                          _overflow_stacks, desired_plab_sz(), _term);
 961 
 962   ParNewGenTask tsk(this, _old_gen, reserved().end(), &thread_state_set);
 963   gch->set_par_threads(n_workers);
 964   gch->rem_set()->prepare_for_younger_refs_iterate(true);
 965   // It turns out that even when we're using 1 thread, doing the work in a
 966   // separate thread causes wide variance in run times.  We can't help this
 967   // in the multi-threaded case, but we special-case n=1 here to get
 968   // repeatable measurements of the 1-thread overhead of the parallel code.
 969   if (n_workers > 1) {
 970     StrongRootsScope srs;
 971     workers->run_task(&tsk);
 972   } else {
 973     StrongRootsScope srs;
 974     tsk.work(0);
 975   }
 976   thread_state_set.reset(0 /* Bad value in debug if not reset */,
 977                          promotion_failed());
 978 
 979   // Trace and reset failed promotion info.
 980   if (promotion_failed()) {
 981     thread_state_set.trace_promotion_failed(gc_tracer());
 982   }
 983 
 984   // Process (weak) reference objects found during scavenge.
 985   ReferenceProcessor* rp = ref_processor();
 986   IsAliveClosure is_alive(this);
 987   ScanWeakRefClosure scan_weak_ref(this);
 988   KeepAliveClosure keep_alive(&scan_weak_ref);
 989   ScanClosure               scan_without_gc_barrier(this, false);
 990   ScanClosureWithParBarrier scan_with_gc_barrier(this, true);
 991   set_promo_failure_scan_stack_closure(&scan_without_gc_barrier);
 992   EvacuateFollowersClosureGeneral evacuate_followers(gch, _level,
 993     &scan_without_gc_barrier, &scan_with_gc_barrier);
 994   rp->setup_policy(clear_all_soft_refs);
 995   // Can  the mt_degree be set later (at run_task() time would be best)?
 996   rp->set_active_mt_degree(active_workers);
 997   ReferenceProcessorStats stats;
 998   if (rp->processing_is_mt()) {
 999     ParNewRefProcTaskExecutor task_executor(*this, thread_state_set);
1000     stats = rp->process_discovered_references(&is_alive, &keep_alive,
1001                                               &evacuate_followers, &task_executor,
1002                                               _gc_timer, _gc_tracer.gc_id());
1003   } else {
1004     thread_state_set.flush();
1005     gch->set_par_threads(0);  // 0 ==> non-parallel.
1006     gch->save_marks();
1007     stats = rp->process_discovered_references(&is_alive, &keep_alive,
1008                                               &evacuate_followers, NULL,
1009                                               _gc_timer, _gc_tracer.gc_id());
1010   }
1011   _gc_tracer.report_gc_reference_stats(stats);
1012   if (!promotion_failed()) {
1013     // Swap the survivor spaces.
1014     eden()->clear(SpaceDecorator::Mangle);
1015     from()->clear(SpaceDecorator::Mangle);
1016     if (ZapUnusedHeapArea) {
1017       // This is now done here because of the piece-meal mangling which
1018       // can check for valid mangling at intermediate points in the
1019       // collection(s).  When a minor collection fails to collect
1020       // sufficient space resizing of the young generation can occur
1021       // an redistribute the spaces in the young generation.  Mangle
1022       // here so that unzapped regions don't get distributed to
1023       // other spaces.
1024       to()->mangle_unused_area();
1025     }
1026     swap_spaces();
1027 
1028     // A successful scavenge should restart the GC time limit count which is
1029     // for full GC's.
1030     size_policy->reset_gc_overhead_limit_count();
1031 
1032     assert(to()->is_empty(), "to space should be empty now");
1033 
1034     adjust_desired_tenuring_threshold();
1035   } else {
1036     handle_promotion_failed(gch, thread_state_set);
1037   }
1038   // set new iteration safe limit for the survivor spaces
1039   from()->set_concurrent_iteration_safe_limit(from()->top());
1040   to()->set_concurrent_iteration_safe_limit(to()->top());
1041 
1042   if (ResizePLAB) {
1043     plab_stats()->adjust_desired_plab_sz(n_workers);
1044   }
1045 
1046   if (PrintGC && !PrintGCDetails) {
1047     gch->print_heap_change(gch_prev_used);
1048   }
1049 
1050   TASKQUEUE_STATS_ONLY(if (PrintTerminationStats) thread_state_set.print_termination_stats());
1051   TASKQUEUE_STATS_ONLY(if (PrintTaskqueue) thread_state_set.print_taskqueue_stats());
1052 
1053   if (UseAdaptiveSizePolicy) {
1054     size_policy->minor_collection_end(gch->gc_cause());
1055     size_policy->avg_survived()->sample(from()->used());
1056   }
1057 
1058   // We need to use a monotonically non-decreasing time in ms
1059   // or we will see time-warp warnings and os::javaTimeMillis()
1060   // does not guarantee monotonicity.
1061   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
1062   update_time_of_last_gc(now);
1063 
1064   rp->set_enqueuing_is_done(true);
1065   if (rp->processing_is_mt()) {
1066     ParNewRefProcTaskExecutor task_executor(*this, thread_state_set);
1067     rp->enqueue_discovered_references(&task_executor);
1068   } else {
1069     rp->enqueue_discovered_references(NULL);
1070   }
1071   rp->verify_no_references_recorded();
1072 
1073   gch->trace_heap_after_gc(gc_tracer());
1074   _gc_tracer.report_tenuring_threshold(tenuring_threshold());
1075 
1076   _gc_timer->register_gc_end();
1077 
1078   _gc_tracer.report_gc_end(_gc_timer->gc_end(), _gc_timer->time_partitions());
1079 }
1080 
1081 static int sum;
1082 void ParNewGeneration::waste_some_time() {
1083   for (int i = 0; i < 100; i++) {
1084     sum += i;
1085   }
1086 }
1087 
1088 static const oop ClaimedForwardPtr = cast_to_oop<intptr_t>(0x4);
1089 
1090 // Because of concurrency, there are times where an object for which
1091 // "is_forwarded()" is true contains an "interim" forwarding pointer
1092 // value.  Such a value will soon be overwritten with a real value.
1093 // This method requires "obj" to have a forwarding pointer, and waits, if
1094 // necessary for a real one to be inserted, and returns it.
1095 
1096 oop ParNewGeneration::real_forwardee(oop obj) {
1097   oop forward_ptr = obj->forwardee();
1098   if (forward_ptr != ClaimedForwardPtr) {
1099     return forward_ptr;
1100   } else {
1101     return real_forwardee_slow(obj);
1102   }
1103 }
1104 
1105 oop ParNewGeneration::real_forwardee_slow(oop obj) {
1106   // Spin-read if it is claimed but not yet written by another thread.
1107   oop forward_ptr = obj->forwardee();
1108   while (forward_ptr == ClaimedForwardPtr) {
1109     waste_some_time();
1110     assert(obj->is_forwarded(), "precondition");
1111     forward_ptr = obj->forwardee();
1112   }
1113   return forward_ptr;
1114 }
1115 
1116 void ParNewGeneration::preserve_mark_if_necessary(oop obj, markOop m) {
1117   if (m->must_be_preserved_for_promotion_failure(obj)) {
1118     // We should really have separate per-worker stacks, rather
1119     // than use locking of a common pair of stacks.
1120     MutexLocker ml(ParGCRareEvent_lock);
1121     preserve_mark(obj, m);
1122   }
1123 }
1124 
1125 // Multiple GC threads may try to promote an object.  If the object
1126 // is successfully promoted, a forwarding pointer will be installed in
1127 // the object in the young generation.  This method claims the right
1128 // to install the forwarding pointer before it copies the object,
1129 // thus avoiding the need to undo the copy as in
1130 // copy_to_survivor_space_avoiding_with_undo.
1131 
1132 oop ParNewGeneration::copy_to_survivor_space(
1133         ParScanThreadState* par_scan_state, oop old, size_t sz, markOop m) {
1134   // In the sequential version, this assert also says that the object is
1135   // not forwarded.  That might not be the case here.  It is the case that
1136   // the caller observed it to be not forwarded at some time in the past.
1137   assert(is_in_reserved(old), "shouldn't be scavenging this oop");
1138 
1139   // The sequential code read "old->age()" below.  That doesn't work here,
1140   // since the age is in the mark word, and that might be overwritten with
1141   // a forwarding pointer by a parallel thread.  So we must save the mark
1142   // word in a local and then analyze it.
1143   oopDesc dummyOld;
1144   dummyOld.set_mark(m);
1145   assert(!dummyOld.is_forwarded(),
1146          "should not be called with forwarding pointer mark word.");
1147 
1148   oop new_obj = NULL;
1149   oop forward_ptr;
1150 
1151   // Try allocating obj in to-space (unless too old)
1152   if (dummyOld.age() < tenuring_threshold()) {
1153     new_obj = (oop)par_scan_state->alloc_in_to_space(sz);
1154     if (new_obj == NULL) {
1155       set_survivor_overflow(true);
1156     }
1157   }
1158 
1159   if (new_obj == NULL) {
1160     // Either to-space is full or we decided to promote
1161     // try allocating obj tenured
1162 
1163     // Attempt to install a null forwarding pointer (atomically),
1164     // to claim the right to install the real forwarding pointer.
1165     forward_ptr = old->forward_to_atomic(ClaimedForwardPtr);
1166     if (forward_ptr != NULL) {
1167       // someone else beat us to it.
1168         return real_forwardee(old);
1169     }
1170 
1171     if (!_promotion_failed) {
1172       new_obj = _old_gen->par_promote(par_scan_state->thread_num(),
1173                                       old, m, sz);
1174     }
1175 
1176     if (new_obj == NULL) {
1177       // promotion failed, forward to self
1178       _promotion_failed = true;
1179       new_obj = old;
1180 
1181       preserve_mark_if_necessary(old, m);
1182       par_scan_state->register_promotion_failure(sz);
1183     }
1184 
1185     old->forward_to(new_obj);
1186     forward_ptr = NULL;
1187   } else {
1188     // Is in to-space; do copying ourselves.
1189     Copy::aligned_disjoint_words((HeapWord*)old, (HeapWord*)new_obj, sz);
1190     assert(GenCollectedHeap::heap()->is_in_reserved(new_obj), "illegal forwarding pointer value.");
1191     forward_ptr = old->forward_to_atomic(new_obj);
1192     // Restore the mark word copied above.
1193     new_obj->set_mark(m);
1194     // Increment age if obj still in new generation
1195     new_obj->incr_age();
1196     par_scan_state->age_table()->add(new_obj, sz);
1197   }
1198   assert(new_obj != NULL, "just checking");
1199 
1200 #ifndef PRODUCT
1201   // This code must come after the CAS test, or it will print incorrect
1202   // information.
1203   if (TraceScavenge) {
1204     gclog_or_tty->print_cr("{%s %s " PTR_FORMAT " -> " PTR_FORMAT " (%d)}",
1205        is_in_reserved(new_obj) ? "copying" : "tenuring",
1206        new_obj->klass()->internal_name(), p2i(old), p2i(new_obj), new_obj->size());
1207   }
1208 #endif
1209 
1210   if (forward_ptr == NULL) {
1211     oop obj_to_push = new_obj;
1212     if (par_scan_state->should_be_partially_scanned(obj_to_push, old)) {
1213       // Length field used as index of next element to be scanned.
1214       // Real length can be obtained from real_forwardee()
1215       arrayOop(old)->set_length(0);
1216       obj_to_push = old;
1217       assert(obj_to_push->is_forwarded() && obj_to_push->forwardee() != obj_to_push,
1218              "push forwarded object");
1219     }
1220     // Push it on one of the queues of to-be-scanned objects.
1221     bool simulate_overflow = false;
1222     NOT_PRODUCT(
1223       if (ParGCWorkQueueOverflowALot && should_simulate_overflow()) {
1224         // simulate a stack overflow
1225         simulate_overflow = true;
1226       }
1227     )
1228     if (simulate_overflow || !par_scan_state->work_queue()->push(obj_to_push)) {
1229       // Add stats for overflow pushes.
1230       if (Verbose && PrintGCDetails) {
1231         gclog_or_tty->print("queue overflow!\n");
1232       }
1233       push_on_overflow_list(old, par_scan_state);
1234       TASKQUEUE_STATS_ONLY(par_scan_state->taskqueue_stats().record_overflow(0));
1235     }
1236 
1237     return new_obj;
1238   }
1239 
1240   // Oops.  Someone beat us to it.  Undo the allocation.  Where did we
1241   // allocate it?
1242   if (is_in_reserved(new_obj)) {
1243     // Must be in to_space.
1244     assert(to()->is_in_reserved(new_obj), "Checking");
1245     if (forward_ptr == ClaimedForwardPtr) {
1246       // Wait to get the real forwarding pointer value.
1247       forward_ptr = real_forwardee(old);
1248     }
1249     par_scan_state->undo_alloc_in_to_space((HeapWord*)new_obj, sz);
1250   }
1251 
1252   return forward_ptr;
1253 }
1254 
1255 #ifndef PRODUCT
1256 // It's OK to call this multi-threaded;  the worst thing
1257 // that can happen is that we'll get a bunch of closely
1258 // spaced simulated overflows, but that's OK, in fact
1259 // probably good as it would exercise the overflow code
1260 // under contention.
1261 bool ParNewGeneration::should_simulate_overflow() {
1262   if (_overflow_counter-- <= 0) { // just being defensive
1263     _overflow_counter = ParGCWorkQueueOverflowInterval;
1264     return true;
1265   } else {
1266     return false;
1267   }
1268 }
1269 #endif
1270 
1271 // In case we are using compressed oops, we need to be careful.
1272 // If the object being pushed is an object array, then its length
1273 // field keeps track of the "grey boundary" at which the next
1274 // incremental scan will be done (see ParGCArrayScanChunk).
1275 // When using compressed oops, this length field is kept in the
1276 // lower 32 bits of the erstwhile klass word and cannot be used
1277 // for the overflow chaining pointer (OCP below). As such the OCP
1278 // would itself need to be compressed into the top 32-bits in this
1279 // case. Unfortunately, see below, in the event that we have a
1280 // promotion failure, the node to be pushed on the list can be
1281 // outside of the Java heap, so the heap-based pointer compression
1282 // would not work (we would have potential aliasing between C-heap
1283 // and Java-heap pointers). For this reason, when using compressed
1284 // oops, we simply use a worker-thread-local, non-shared overflow
1285 // list in the form of a growable array, with a slightly different
1286 // overflow stack draining strategy. If/when we start using fat
1287 // stacks here, we can go back to using (fat) pointer chains
1288 // (although some performance comparisons would be useful since
1289 // single global lists have their own performance disadvantages
1290 // as we were made painfully aware not long ago, see 6786503).
1291 #define BUSY (cast_to_oop<intptr_t>(0x1aff1aff))
1292 void ParNewGeneration::push_on_overflow_list(oop from_space_obj, ParScanThreadState* par_scan_state) {
1293   assert(is_in_reserved(from_space_obj), "Should be from this generation");
1294   if (ParGCUseLocalOverflow) {
1295     // In the case of compressed oops, we use a private, not-shared
1296     // overflow stack.
1297     par_scan_state->push_on_overflow_stack(from_space_obj);
1298   } else {
1299     assert(!UseCompressedOops, "Error");
1300     // if the object has been forwarded to itself, then we cannot
1301     // use the klass pointer for the linked list.  Instead we have
1302     // to allocate an oopDesc in the C-Heap and use that for the linked list.
1303     // XXX This is horribly inefficient when a promotion failure occurs
1304     // and should be fixed. XXX FIX ME !!!
1305 #ifndef PRODUCT
1306     Atomic::inc_ptr(&_num_par_pushes);
1307     assert(_num_par_pushes > 0, "Tautology");
1308 #endif
1309     if (from_space_obj->forwardee() == from_space_obj) {
1310       oopDesc* listhead = NEW_C_HEAP_ARRAY(oopDesc, 1, mtGC);
1311       listhead->forward_to(from_space_obj);
1312       from_space_obj = listhead;
1313     }
1314     oop observed_overflow_list = _overflow_list;
1315     oop cur_overflow_list;
1316     do {
1317       cur_overflow_list = observed_overflow_list;
1318       if (cur_overflow_list != BUSY) {
1319         from_space_obj->set_klass_to_list_ptr(cur_overflow_list);
1320       } else {
1321         from_space_obj->set_klass_to_list_ptr(NULL);
1322       }
1323       observed_overflow_list =
1324         (oop)Atomic::cmpxchg_ptr(from_space_obj, &_overflow_list, cur_overflow_list);
1325     } while (cur_overflow_list != observed_overflow_list);
1326   }
1327 }
1328 
1329 bool ParNewGeneration::take_from_overflow_list(ParScanThreadState* par_scan_state) {
1330   bool res;
1331 
1332   if (ParGCUseLocalOverflow) {
1333     res = par_scan_state->take_from_overflow_stack();
1334   } else {
1335     assert(!UseCompressedOops, "Error");
1336     res = take_from_overflow_list_work(par_scan_state);
1337   }
1338   return res;
1339 }
1340 
1341 
1342 // *NOTE*: The overflow list manipulation code here and
1343 // in CMSCollector:: are very similar in shape,
1344 // except that in the CMS case we thread the objects
1345 // directly into the list via their mark word, and do
1346 // not need to deal with special cases below related
1347 // to chunking of object arrays and promotion failure
1348 // handling.
1349 // CR 6797058 has been filed to attempt consolidation of
1350 // the common code.
1351 // Because of the common code, if you make any changes in
1352 // the code below, please check the CMS version to see if
1353 // similar changes might be needed.
1354 // See CMSCollector::par_take_from_overflow_list() for
1355 // more extensive documentation comments.
1356 bool ParNewGeneration::take_from_overflow_list_work(ParScanThreadState* par_scan_state) {
1357   ObjToScanQueue* work_q = par_scan_state->work_queue();
1358   // How many to take?
1359   size_t objsFromOverflow = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
1360                                  (size_t)ParGCDesiredObjsFromOverflowList);
1361 
1362   assert(!UseCompressedOops, "Error");
1363   assert(par_scan_state->overflow_stack() == NULL, "Error");
1364   if (_overflow_list == NULL) return false;
1365 
1366   // Otherwise, there was something there; try claiming the list.
1367   oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
1368   // Trim off a prefix of at most objsFromOverflow items
1369   Thread* tid = Thread::current();
1370   size_t spin_count = (size_t)ParallelGCThreads;
1371   size_t sleep_time_millis = MAX2((size_t)1, objsFromOverflow/100);
1372   for (size_t spin = 0; prefix == BUSY && spin < spin_count; spin++) {
1373     // someone grabbed it before we did ...
1374     // ... we spin for a short while...
1375     os::sleep(tid, sleep_time_millis, false);
1376     if (_overflow_list == NULL) {
1377       // nothing left to take
1378       return false;
1379     } else if (_overflow_list != BUSY) {
1380      // try and grab the prefix
1381      prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
1382     }
1383   }
1384   if (prefix == NULL || prefix == BUSY) {
1385      // Nothing to take or waited long enough
1386      if (prefix == NULL) {
1387        // Write back the NULL in case we overwrote it with BUSY above
1388        // and it is still the same value.
1389        (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
1390      }
1391      return false;
1392   }
1393   assert(prefix != NULL && prefix != BUSY, "Error");
1394   size_t i = 1;
1395   oop cur = prefix;
1396   while (i < objsFromOverflow && cur->klass_or_null() != NULL) {
1397     i++; cur = cur->list_ptr_from_klass();
1398   }
1399 
1400   // Reattach remaining (suffix) to overflow list
1401   if (cur->klass_or_null() == NULL) {
1402     // Write back the NULL in lieu of the BUSY we wrote
1403     // above and it is still the same value.
1404     if (_overflow_list == BUSY) {
1405       (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
1406     }
1407   } else {
1408     assert(cur->klass_or_null() != (Klass*)(address)BUSY, "Error");
1409     oop suffix = cur->list_ptr_from_klass();       // suffix will be put back on global list
1410     cur->set_klass_to_list_ptr(NULL);     // break off suffix
1411     // It's possible that the list is still in the empty(busy) state
1412     // we left it in a short while ago; in that case we may be
1413     // able to place back the suffix.
1414     oop observed_overflow_list = _overflow_list;
1415     oop cur_overflow_list = observed_overflow_list;
1416     bool attached = false;
1417     while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
1418       observed_overflow_list =
1419         (oop) Atomic::cmpxchg_ptr(suffix, &_overflow_list, cur_overflow_list);
1420       if (cur_overflow_list == observed_overflow_list) {
1421         attached = true;
1422         break;
1423       } else cur_overflow_list = observed_overflow_list;
1424     }
1425     if (!attached) {
1426       // Too bad, someone else got in in between; we'll need to do a splice.
1427       // Find the last item of suffix list
1428       oop last = suffix;
1429       while (last->klass_or_null() != NULL) {
1430         last = last->list_ptr_from_klass();
1431       }
1432       // Atomically prepend suffix to current overflow list
1433       observed_overflow_list = _overflow_list;
1434       do {
1435         cur_overflow_list = observed_overflow_list;
1436         if (cur_overflow_list != BUSY) {
1437           // Do the splice ...
1438           last->set_klass_to_list_ptr(cur_overflow_list);
1439         } else { // cur_overflow_list == BUSY
1440           last->set_klass_to_list_ptr(NULL);
1441         }
1442         observed_overflow_list =
1443           (oop)Atomic::cmpxchg_ptr(suffix, &_overflow_list, cur_overflow_list);
1444       } while (cur_overflow_list != observed_overflow_list);
1445     }
1446   }
1447 
1448   // Push objects on prefix list onto this thread's work queue
1449   assert(prefix != NULL && prefix != BUSY, "program logic");
1450   cur = prefix;
1451   ssize_t n = 0;
1452   while (cur != NULL) {
1453     oop obj_to_push = cur->forwardee();
1454     oop next        = cur->list_ptr_from_klass();
1455     cur->set_klass(obj_to_push->klass());
1456     // This may be an array object that is self-forwarded. In that case, the list pointer
1457     // space, cur, is not in the Java heap, but rather in the C-heap and should be freed.
1458     if (!is_in_reserved(cur)) {
1459       // This can become a scaling bottleneck when there is work queue overflow coincident
1460       // with promotion failure.
1461       oopDesc* f = cur;
1462       FREE_C_HEAP_ARRAY(oopDesc, f);
1463     } else if (par_scan_state->should_be_partially_scanned(obj_to_push, cur)) {
1464       assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");
1465       obj_to_push = cur;
1466     }
1467     bool ok = work_q->push(obj_to_push);
1468     assert(ok, "Should have succeeded");
1469     cur = next;
1470     n++;
1471   }
1472   TASKQUEUE_STATS_ONLY(par_scan_state->note_overflow_refill(n));
1473 #ifndef PRODUCT
1474   assert(_num_par_pushes >= n, "Too many pops?");
1475   Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);
1476 #endif
1477   return true;
1478 }
1479 #undef BUSY
1480 
1481 void ParNewGeneration::ref_processor_init() {
1482   if (_ref_processor == NULL) {
1483     // Allocate and initialize a reference processor
1484     _ref_processor =
1485       new ReferenceProcessor(_reserved,                  // span
1486                              ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing
1487                              (int) ParallelGCThreads,    // mt processing degree
1488                              refs_discovery_is_mt(),     // mt discovery
1489                              (int) ParallelGCThreads,    // mt discovery degree
1490                              refs_discovery_is_atomic(), // atomic_discovery
1491                              NULL);                      // is_alive_non_header
1492   }
1493 }
1494 
1495 const char* ParNewGeneration::name() const {
1496   return "par new generation";
1497 }