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