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