parNewGeneration.cpp 62.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30
#include "precompiled.hpp"
#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"
#include "gc_implementation/parNew/parNewGeneration.hpp"
#include "gc_implementation/parNew/parOopClosures.inline.hpp"
#include "gc_implementation/shared/adaptiveSizePolicy.hpp"
#include "gc_implementation/shared/ageTable.hpp"
31
#include "gc_implementation/shared/copyFailedInfo.hpp"
S
sla 已提交
32 33 34 35
#include "gc_implementation/shared/gcHeapSummary.hpp"
#include "gc_implementation/shared/gcTimer.hpp"
#include "gc_implementation/shared/gcTrace.hpp"
#include "gc_implementation/shared/gcTraceTime.hpp"
36
#include "gc_implementation/shared/parGCAllocBuffer.inline.hpp"
37 38 39 40 41 42
#include "gc_implementation/shared/spaceDecorator.hpp"
#include "memory/defNewGeneration.inline.hpp"
#include "memory/genCollectedHeap.hpp"
#include "memory/genOopClosures.inline.hpp"
#include "memory/generation.hpp"
#include "memory/generation.inline.hpp"
43
#include "memory/heapInspection.hpp"
44 45 46 47 48 49 50 51 52 53
#include "memory/referencePolicy.hpp"
#include "memory/resourceArea.hpp"
#include "memory/sharedHeap.hpp"
#include "memory/space.hpp"
#include "oops/objArrayOop.hpp"
#include "oops/oop.inline.hpp"
#include "oops/oop.pcgc.inline.hpp"
#include "runtime/handles.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/java.hpp"
54
#include "runtime/thread.inline.hpp"
55 56 57
#include "utilities/copy.hpp"
#include "utilities/globalDefinitions.hpp"
#include "utilities/workgroup.hpp"
D
duke 已提交
58

59 60
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

D
duke 已提交
61 62 63 64 65 66 67 68 69
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable:4355 ) // 'this' : used in base member initializer list
#endif
ParScanThreadState::ParScanThreadState(Space* to_space_,
                                       ParNewGeneration* gen_,
                                       Generation* old_gen_,
                                       int thread_num_,
                                       ObjToScanQueueSet* work_queue_set_,
Z
zgu 已提交
70
                                       Stack<oop, mtGC>* overflow_stacks_,
D
duke 已提交
71 72
                                       size_t desired_plab_sz_,
                                       ParallelTaskTerminator& term_) :
73
  _to_space(to_space_), _old_gen(old_gen_), _young_gen(gen_), _thread_num(thread_num_),
D
duke 已提交
74
  _work_queue(work_queue_set_->queue(thread_num_)), _to_space_full(false),
75
  _overflow_stack(overflow_stacks_ ? overflow_stacks_ + thread_num_ : NULL),
D
duke 已提交
76 77 78 79 80 81 82 83 84 85 86 87
  _ageTable(false), // false ==> not the global age table, no perf data.
  _to_space_alloc_buffer(desired_plab_sz_),
  _to_space_closure(gen_, this), _old_gen_closure(gen_, this),
  _to_space_root_closure(gen_, this), _old_gen_root_closure(gen_, this),
  _older_gen_closure(gen_, this),
  _evacuate_followers(this, &_to_space_closure, &_old_gen_closure,
                      &_to_space_root_closure, gen_, &_old_gen_root_closure,
                      work_queue_set_, &term_),
  _is_alive_closure(gen_), _scan_weak_ref_closure(gen_, this),
  _keep_alive_closure(&_scan_weak_ref_closure),
  _strong_roots_time(0.0), _term_time(0.0)
{
88 89 90 91 92 93
  #if TASKQUEUE_STATS
  _term_attempts = 0;
  _overflow_refills = 0;
  _overflow_refill_objs = 0;
  #endif // TASKQUEUE_STATS

D
duke 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  _survivor_chunk_array =
    (ChunkArray*) old_gen()->get_data_recorder(thread_num());
  _hash_seed = 17;  // Might want to take time-based random value.
  _start = os::elapsedTime();
  _old_gen_closure.set_generation(old_gen_);
  _old_gen_root_closure.set_generation(old_gen_);
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif

void ParScanThreadState::record_survivor_plab(HeapWord* plab_start,
                                              size_t plab_word_size) {
  ChunkArray* sca = survivor_chunk_array();
  if (sca != NULL) {
    // A non-null SCA implies that we want the PLAB data recorded.
    sca->record_sample(plab_start, plab_word_size);
  }
}

bool ParScanThreadState::should_be_partially_scanned(oop new_obj, oop old_obj) const {
  return new_obj->is_objArray() &&
         arrayOop(new_obj)->length() > ParGCArrayScanChunk &&
         new_obj != old_obj;
}

void ParScanThreadState::scan_partial_array_and_push_remainder(oop old) {
  assert(old->is_objArray(), "must be obj array");
  assert(old->is_forwarded(), "must be forwarded");
  assert(Universe::heap()->is_in_reserved(old), "must be in heap.");
124
  assert(!old_gen()->is_in(old), "must be in young generation.");
D
duke 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

  objArrayOop obj = objArrayOop(old->forwardee());
  // Process ParGCArrayScanChunk elements now
  // and push the remainder back onto queue
  int start     = arrayOop(old)->length();
  int end       = obj->length();
  int remainder = end - start;
  assert(start <= end, "just checking");
  if (remainder > 2 * ParGCArrayScanChunk) {
    // Test above combines last partial chunk with a full chunk
    end = start + ParGCArrayScanChunk;
    arrayOop(old)->set_length(end);
    // Push remainder.
    bool ok = work_queue()->push(old);
    assert(ok, "just popped, push must be okay");
  } else {
    // Restore length so that it can be used if there
    // is a promotion failure and forwarding pointers
    // must be removed.
    arrayOop(old)->set_length(end);
  }
146

D
duke 已提交
147
  // process our set of indices (include header in first chunk)
148
  // should make sure end is even (aligned to HeapWord in case of compressed oops)
D
duke 已提交
149 150
  if ((HeapWord *)obj < young_old_boundary()) {
    // object is in to_space
151
    obj->oop_iterate_range(&_to_space_closure, start, end);
D
duke 已提交
152 153
  } else {
    // object is in old generation
154
    obj->oop_iterate_range(&_old_gen_closure, start, end);
D
duke 已提交
155 156 157 158 159 160
  }
}


void ParScanThreadState::trim_queues(int max_size) {
  ObjToScanQueue* queue = work_queue();
161 162 163 164 165 166 167 168 169 170 171 172 173
  do {
    while (queue->size() > (juint)max_size) {
      oop obj_to_scan;
      if (queue->pop_local(obj_to_scan)) {
        if ((HeapWord *)obj_to_scan < young_old_boundary()) {
          if (obj_to_scan->is_objArray() &&
              obj_to_scan->is_forwarded() &&
              obj_to_scan->forwardee() != obj_to_scan) {
            scan_partial_array_and_push_remainder(obj_to_scan);
          } else {
            // object is in to_space
            obj_to_scan->oop_iterate(&_to_space_closure);
          }
D
duke 已提交
174
        } else {
175 176
          // object is in old generation
          obj_to_scan->oop_iterate(&_old_gen_closure);
D
duke 已提交
177 178 179
        }
      }
    }
180 181 182 183 184 185 186 187 188 189 190
    // For the  case of compressed oops, we have a private, non-shared
    // overflow stack, so we eagerly drain it so as to more evenly
    // distribute load early. Note: this may be good to do in
    // general rather than delay for the final stealing phase.
    // If applicable, we'll transfer a set of objects over to our
    // work queue, allowing them to be stolen and draining our
    // private overflow stack.
  } while (ParGCTrimOverflow && young_gen()->take_from_overflow_list(this));
}

bool ParScanThreadState::take_from_overflow_stack() {
191
  assert(ParGCUseLocalOverflow, "Else should not call");
192 193
  assert(young_gen()->overflow_list() == NULL, "Error");
  ObjToScanQueue* queue = work_queue();
Z
zgu 已提交
194
  Stack<oop, mtGC>* const of_stack = overflow_stack();
195 196 197 198 199
  const size_t num_overflow_elems = of_stack->size();
  const size_t space_available = queue->max_elems() - queue->size();
  const size_t num_take_elems = MIN3(space_available / 4,
                                     ParGCDesiredObjsFromOverflowList,
                                     num_overflow_elems);
200 201 202 203 204 205 206 207 208 209 210 211 212 213
  // Transfer the most recent num_take_elems from the overflow
  // stack to our work queue.
  for (size_t i = 0; i != num_take_elems; i++) {
    oop cur = of_stack->pop();
    oop obj_to_push = cur->forwardee();
    assert(Universe::heap()->is_in_reserved(cur), "Should be in heap");
    assert(!old_gen()->is_in_reserved(cur), "Should be in young gen");
    assert(Universe::heap()->is_in_reserved(obj_to_push), "Should be in heap");
    if (should_be_partially_scanned(obj_to_push, cur)) {
      assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");
      obj_to_push = cur;
    }
    bool ok = queue->push(obj_to_push);
    assert(ok, "Should have succeeded");
D
duke 已提交
214
  }
215 216 217 218 219
  assert(young_gen()->overflow_list() == NULL, "Error");
  return num_take_elems > 0;  // was something transferred?
}

void ParScanThreadState::push_on_overflow_stack(oop p) {
220
  assert(ParGCUseLocalOverflow, "Else should not call");
221 222
  overflow_stack()->push(p);
  assert(young_gen()->overflow_list() == NULL, "Error");
D
duke 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
}

HeapWord* ParScanThreadState::alloc_in_to_space_slow(size_t word_sz) {

  // Otherwise, if the object is small enough, try to reallocate the
  // buffer.
  HeapWord* obj = NULL;
  if (!_to_space_full) {
    ParGCAllocBuffer* const plab = to_space_alloc_buffer();
    Space*            const sp   = to_space();
    if (word_sz * 100 <
        ParallelGCBufferWastePct * plab->word_sz()) {
      // Is small enough; abandon this buffer and start a new one.
      plab->retire(false, false);
      size_t buf_size = plab->word_sz();
      HeapWord* buf_space = sp->par_allocate(buf_size);
      if (buf_space == NULL) {
        const size_t min_bytes =
          ParGCAllocBuffer::min_size() << LogHeapWordSize;
        size_t free_bytes = sp->free();
        while(buf_space == NULL && free_bytes >= min_bytes) {
          buf_size = free_bytes >> LogHeapWordSize;
          assert(buf_size == (size_t)align_object_size(buf_size),
                 "Invariant");
          buf_space  = sp->par_allocate(buf_size);
          free_bytes = sp->free();
        }
      }
      if (buf_space != NULL) {
        plab->set_word_size(buf_size);
        plab->set_buf(buf_space);
        record_survivor_plab(buf_space, buf_size);
255
        obj = plab->allocate_aligned(word_sz, SurvivorAlignmentInBytes);
D
duke 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        // Note that we cannot compare buf_size < word_sz below
        // because of AlignmentReserve (see ParGCAllocBuffer::allocate()).
        assert(obj != NULL || plab->words_remaining() < word_sz,
               "Else should have been able to allocate");
        // It's conceivable that we may be able to use the
        // buffer we just grabbed for subsequent small requests
        // even if not for this one.
      } else {
        // We're used up.
        _to_space_full = true;
      }

    } else {
      // Too large; allocate the object individually.
      obj = sp->par_allocate(word_sz);
    }
  }
  return obj;
}


void ParScanThreadState::undo_alloc_in_to_space(HeapWord* obj,
                                                size_t word_sz) {
  // Is the alloc in the current alloc buffer?
  if (to_space_alloc_buffer()->contains(obj)) {
    assert(to_space_alloc_buffer()->contains(obj + word_sz - 1),
           "Should contain whole object.");
    to_space_alloc_buffer()->undo_allocation(obj, word_sz);
  } else {
285
    CollectedHeap::fill_with_object(obj, word_sz);
D
duke 已提交
286 287 288
  }
}

S
sla 已提交
289 290 291 292
void ParScanThreadState::print_promotion_failure_size() {
  if (_promotion_failed_info.has_failed() && PrintPromotionFailure) {
    gclog_or_tty->print(" (%d: promotion failure size = " SIZE_FORMAT ") ",
                        _thread_num, _promotion_failed_info.first_size());
293 294 295
  }
}

D
duke 已提交
296 297 298 299 300 301 302 303
class ParScanThreadStateSet: private ResourceArray {
public:
  // Initializes states for the specified number of threads;
  ParScanThreadStateSet(int                     num_threads,
                        Space&                  to_space,
                        ParNewGeneration&       gen,
                        Generation&             old_gen,
                        ObjToScanQueueSet&      queue_set,
Z
zgu 已提交
304
                        Stack<oop, mtGC>*       overflow_stacks_,
D
duke 已提交
305 306
                        size_t                  desired_plab_sz,
                        ParallelTaskTerminator& term);
307 308 309

  ~ParScanThreadStateSet() { TASKQUEUE_STATS_ONLY(reset_stats()); }

310
  inline ParScanThreadState& thread_state(int i);
311

S
sla 已提交
312
  void trace_promotion_failed(YoungGCTracer& gc_tracer);
313
  void reset(int active_workers, bool promotion_failed);
D
duke 已提交
314
  void flush();
315 316 317 318 319 320 321 322 323 324 325

  #if TASKQUEUE_STATS
  static void
    print_termination_stats_hdr(outputStream* const st = gclog_or_tty);
  void print_termination_stats(outputStream* const st = gclog_or_tty);
  static void
    print_taskqueue_stats_hdr(outputStream* const st = gclog_or_tty);
  void print_taskqueue_stats(outputStream* const st = gclog_or_tty);
  void reset_stats();
  #endif // TASKQUEUE_STATS

D
duke 已提交
326 327 328 329
private:
  ParallelTaskTerminator& _term;
  ParNewGeneration&       _gen;
  Generation&             _next_gen;
330 331 332
 public:
  bool is_valid(int id) const { return id < length(); }
  ParallelTaskTerminator* terminator() { return &_term; }
D
duke 已提交
333 334 335 336 337 338
};


ParScanThreadStateSet::ParScanThreadStateSet(
  int num_threads, Space& to_space, ParNewGeneration& gen,
  Generation& old_gen, ObjToScanQueueSet& queue_set,
Z
zgu 已提交
339
  Stack<oop, mtGC>* overflow_stacks,
D
duke 已提交
340 341
  size_t desired_plab_sz, ParallelTaskTerminator& term)
  : ResourceArray(sizeof(ParScanThreadState), num_threads),
342
    _gen(gen), _next_gen(old_gen), _term(term)
D
duke 已提交
343 344
{
  assert(num_threads > 0, "sanity check!");
345 346
  assert(ParGCUseLocalOverflow == (overflow_stacks != NULL),
         "overflow_stack allocation mismatch");
D
duke 已提交
347 348 349 350
  // Initialize states.
  for (int i = 0; i < num_threads; ++i) {
    new ((ParScanThreadState*)_data + i)
        ParScanThreadState(&to_space, &gen, &old_gen, i, &queue_set,
351
                           overflow_stacks, desired_plab_sz, term);
D
duke 已提交
352 353 354
  }
}

355
inline ParScanThreadState& ParScanThreadStateSet::thread_state(int i)
D
duke 已提交
356 357 358 359 360
{
  assert(i >= 0 && i < length(), "sanity check!");
  return ((ParScanThreadState*)_data)[i];
}

S
sla 已提交
361 362 363 364 365 366 367 368
void ParScanThreadStateSet::trace_promotion_failed(YoungGCTracer& gc_tracer) {
  for (int i = 0; i < length(); ++i) {
    if (thread_state(i).promotion_failed()) {
      gc_tracer.report_promotion_failed(thread_state(i).promotion_failed_info());
      thread_state(i).promotion_failed_info().reset();
    }
  }
}
D
duke 已提交
369

370
void ParScanThreadStateSet::reset(int active_threads, bool promotion_failed)
D
duke 已提交
371
{
372
  _term.reset_for_reuse(active_threads);
373 374
  if (promotion_failed) {
    for (int i = 0; i < length(); ++i) {
S
sla 已提交
375
      thread_state(i).print_promotion_failure_size();
376 377
    }
  }
D
duke 已提交
378 379
}

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
#if TASKQUEUE_STATS
void
ParScanThreadState::reset_stats()
{
  taskqueue_stats().reset();
  _term_attempts = 0;
  _overflow_refills = 0;
  _overflow_refill_objs = 0;
}

void ParScanThreadStateSet::reset_stats()
{
  for (int i = 0; i < length(); ++i) {
    thread_state(i).reset_stats();
  }
}

void
ParScanThreadStateSet::print_termination_stats_hdr(outputStream* const st)
{
  st->print_raw_cr("GC Termination Stats");
  st->print_raw_cr("     elapsed  --strong roots-- "
                   "-------termination-------");
  st->print_raw_cr("thr     ms        ms       %   "
                   "    ms       %   attempts");
  st->print_raw_cr("--- --------- --------- ------ "
                   "--------- ------ --------");
}

void ParScanThreadStateSet::print_termination_stats(outputStream* const st)
{
  print_termination_stats_hdr(st);

  for (int i = 0; i < length(); ++i) {
    const ParScanThreadState & pss = thread_state(i);
    const double elapsed_ms = pss.elapsed_time() * 1000.0;
    const double s_roots_ms = pss.strong_roots_time() * 1000.0;
    const double term_ms = pss.term_time() * 1000.0;
    st->print_cr("%3d %9.2f %9.2f %6.2f "
                 "%9.2f %6.2f " SIZE_FORMAT_W(8),
                 i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
                 term_ms, term_ms * 100 / elapsed_ms, pss.term_attempts());
  }
}

// Print stats related to work queue activity.
void ParScanThreadStateSet::print_taskqueue_stats_hdr(outputStream* const st)
{
  st->print_raw_cr("GC Task Stats");
  st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
  st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
}

void ParScanThreadStateSet::print_taskqueue_stats(outputStream* const st)
{
  print_taskqueue_stats_hdr(st);

  TaskQueueStats totals;
  for (int i = 0; i < length(); ++i) {
    const ParScanThreadState & pss = thread_state(i);
    const TaskQueueStats & stats = pss.taskqueue_stats();
    st->print("%3d ", i); stats.print(st); st->cr();
    totals += stats;

    if (pss.overflow_refills() > 0) {
      st->print_cr("    " SIZE_FORMAT_W(10) " overflow refills    "
                   SIZE_FORMAT_W(10) " overflow objects",
                   pss.overflow_refills(), pss.overflow_refill_objs());
    }
  }
  st->print("tot "); totals.print(st); st->cr();

  DEBUG_ONLY(totals.verify());
}
#endif // TASKQUEUE_STATS

D
duke 已提交
456 457
void ParScanThreadStateSet::flush()
{
458 459 460 461
  // Work in this loop should be kept as lightweight as
  // possible since this might otherwise become a bottleneck
  // to scaling. Should we add heavy-weight work into this
  // loop, consider parallelizing the loop into the worker threads.
D
duke 已提交
462
  for (int i = 0; i < length(); ++i) {
463
    ParScanThreadState& par_scan_state = thread_state(i);
D
duke 已提交
464 465 466 467 468

    // Flush stats related to To-space PLAB activity and
    // retire the last buffer.
    par_scan_state.to_space_alloc_buffer()->
      flush_stats_and_retire(_gen.plab_stats(),
469 470
                             true /* end_of_gc */,
                             false /* retain */);
D
duke 已提交
471 472 473 474 475 476 477 478 479 480

    // Every thread has its own age table.  We need to merge
    // them all into one.
    ageTable *local_table = par_scan_state.age_table();
    _gen.age_table()->merge(local_table);

    // Inform old gen that we're done.
    _next_gen.par_promote_alloc_done(i);
    _next_gen.par_oop_since_save_marks_iterate_done(i);
  }
481

482 483 484 485 486 487 488 489
  if (UseConcMarkSweepGC && ParallelGCThreads > 0) {
    // We need to call this even when ResizeOldPLAB is disabled
    // so as to avoid breaking some asserts. While we may be able
    // to avoid this by reorganizing the code a bit, I am loathe
    // to do that unless we find cases where ergo leads to bad
    // performance.
    CFLS_LAB::compute_desired_plab_size();
  }
D
duke 已提交
490 491 492 493
}

ParScanClosure::ParScanClosure(ParNewGeneration* g,
                               ParScanThreadState* par_scan_state) :
494
  OopsInKlassOrGenClosure(g), _par_scan_state(par_scan_state), _g(g)
D
duke 已提交
495 496 497 498 499
{
  assert(_g->level() == 0, "Optimized for youngest generation");
  _boundary = _g->reserved().end();
}

500 501 502 503 504 505 506 507 508 509 510 511
void ParScanWithBarrierClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, true, false); }
void ParScanWithBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, true, false); }

void ParScanWithoutBarrierClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, false, false); }
void ParScanWithoutBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, false, false); }

void ParRootScanWithBarrierTwoGensClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, true, true); }
void ParRootScanWithBarrierTwoGensClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, true, true); }

void ParRootScanWithoutBarrierClosure::do_oop(oop* p)       { ParScanClosure::do_oop_work(p, false, true); }
void ParRootScanWithoutBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, false, true); }

D
duke 已提交
512 513 514
ParScanWeakRefClosure::ParScanWeakRefClosure(ParNewGeneration* g,
                                             ParScanThreadState* par_scan_state)
  : ScanWeakRefClosure(g), _par_scan_state(par_scan_state)
515 516 517 518
{}

void ParScanWeakRefClosure::do_oop(oop* p)       { ParScanWeakRefClosure::do_oop_work(p); }
void ParScanWeakRefClosure::do_oop(narrowOop* p) { ParScanWeakRefClosure::do_oop_work(p); }
D
duke 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574

#ifdef WIN32
#pragma warning(disable: 4786) /* identifier was truncated to '255' characters in the browser information */
#endif

ParEvacuateFollowersClosure::ParEvacuateFollowersClosure(
    ParScanThreadState* par_scan_state_,
    ParScanWithoutBarrierClosure* to_space_closure_,
    ParScanWithBarrierClosure* old_gen_closure_,
    ParRootScanWithoutBarrierClosure* to_space_root_closure_,
    ParNewGeneration* par_gen_,
    ParRootScanWithBarrierTwoGensClosure* old_gen_root_closure_,
    ObjToScanQueueSet* task_queues_,
    ParallelTaskTerminator* terminator_) :

    _par_scan_state(par_scan_state_),
    _to_space_closure(to_space_closure_),
    _old_gen_closure(old_gen_closure_),
    _to_space_root_closure(to_space_root_closure_),
    _old_gen_root_closure(old_gen_root_closure_),
    _par_gen(par_gen_),
    _task_queues(task_queues_),
    _terminator(terminator_)
{}

void ParEvacuateFollowersClosure::do_void() {
  ObjToScanQueue* work_q = par_scan_state()->work_queue();

  while (true) {

    // Scan to-space and old-gen objs until we run out of both.
    oop obj_to_scan;
    par_scan_state()->trim_queues(0);

    // We have no local work, attempt to steal from other threads.

    // attempt to steal work from promoted.
    if (task_queues()->steal(par_scan_state()->thread_num(),
                             par_scan_state()->hash_seed(),
                             obj_to_scan)) {
      bool res = work_q->push(obj_to_scan);
      assert(res, "Empty queue should have room for a push.");

      //   if successful, goto Start.
      continue;

      // try global overflow list.
    } else if (par_gen()->take_from_overflow_list(par_scan_state())) {
      continue;
    }

    // Otherwise, offer termination.
    par_scan_state()->start_term_time();
    if (terminator()->offer_termination()) break;
    par_scan_state()->end_term_time();
  }
575 576
  assert(par_gen()->_overflow_list == NULL && par_gen()->_num_par_pushes == 0,
         "Broken overflow list?");
D
duke 已提交
577 578 579 580 581 582 583 584 585 586 587 588
  // Finish the last termination pause.
  par_scan_state()->end_term_time();
}

ParNewGenTask::ParNewGenTask(ParNewGeneration* gen, Generation* next_gen,
                HeapWord* young_old_boundary, ParScanThreadStateSet* state_set) :
    AbstractGangTask("ParNewGeneration collection"),
    _gen(gen), _next_gen(next_gen),
    _young_old_boundary(young_old_boundary),
    _state_set(state_set)
  {}

589 590 591 592 593 594 595 596 597 598
// Reset the terminator for the given number of
// active threads.
void ParNewGenTask::set_for_termination(int active_workers) {
  _state_set->reset(active_workers, _gen->promotion_failed());
  // Should the heap be passed in?  There's only 1 for now so
  // grab it instead.
  GenCollectedHeap* gch = GenCollectedHeap::heap();
  gch->set_n_termination(active_workers);
}

599
void ParNewGenTask::work(uint worker_id) {
D
duke 已提交
600
  GenCollectedHeap* gch = GenCollectedHeap::heap();
601 602 603
  GenGCPhaseTimes* phase_times = gch->gen_policy()->phase_times();
  phase_times->record_time_secs(GenGCPhaseTimes::GCWorkerStart, worker_id, os::elapsedTime());

D
duke 已提交
604 605 606 607 608
  // Since this is being done in a separate thread, need new resource
  // and handle marks.
  ResourceMark rm;
  HandleMark hm;
  // We would need multiple old-gen queues otherwise.
609
  assert(gch->n_gens() == 2, "Par young collection currently only works with one older gen.");
D
duke 已提交
610 611 612

  Generation* old_gen = gch->next_gen(_gen);

613 614
  ParScanThreadState& par_scan_state = _state_set->thread_state(worker_id);
  assert(_state_set->is_valid(worker_id), "Should not have been called");
615

D
duke 已提交
616 617
  par_scan_state.set_young_old_boundary(_young_old_boundary);

618 619
  KlassScanClosure klass_scan_closure(&par_scan_state.to_space_root_closure(),
                                      gch->rem_set()->klass_rem_set());
620 621 622
  CLDToKlassAndOopClosure cld_scan_closure(&klass_scan_closure,
                                           &par_scan_state.to_space_root_closure(),
                                           false);
623

D
duke 已提交
624
  par_scan_state.start_strong_roots();
625 626 627 628
  gch->gen_process_roots(_gen->level(),
                         true,  // Process younger gens, if any,
                                // as strong roots.
                         false, // no scope; this is parallel code
629
                         GenCollectedHeap::SO_ScavengeCodeCache,
630 631 632
                         GenCollectedHeap::StrongAndWeakRoots,
                         &par_scan_state.to_space_root_closure(),
                         &par_scan_state.older_gen_closure(),
633 634 635
                         &cld_scan_closure,
                         phase_times,
                         worker_id);
636

D
duke 已提交
637 638 639 640
  par_scan_state.end_strong_roots();

  // "evacuate followers".
  par_scan_state.evacuate_followers_closure().do_void();
641
  phase_times->record_time_secs(GenGCPhaseTimes::GCWorkerEnd, worker_id, os::elapsedTime());
D
duke 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654
}

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable:4355 ) // 'this' : used in base member initializer list
#endif
ParNewGeneration::
ParNewGeneration(ReservedSpace rs, size_t initial_byte_size, int level)
  : DefNewGeneration(rs, initial_byte_size, level, "PCopy"),
  _overflow_list(NULL),
  _is_alive_closure(this),
  _plab_stats(YoungPLABSize, PLABWeight)
{
655 656
  NOT_PRODUCT(_overflow_counter = ParGCWorkQueueOverflowInterval;)
  NOT_PRODUCT(_num_par_pushes = 0;)
D
duke 已提交
657 658 659 660
  _task_queues = new ObjToScanQueueSet(ParallelGCThreads);
  guarantee(_task_queues != NULL, "task_queues allocation failure.");

  for (uint i1 = 0; i1 < ParallelGCThreads; i1++) {
J
jcoomes 已提交
661 662 663
    ObjToScanQueue *q = new ObjToScanQueue();
    guarantee(q != NULL, "work_queue Allocation failure.");
    _task_queues->register_queue(i1, q);
D
duke 已提交
664 665 666 667 668
  }

  for (uint i2 = 0; i2 < ParallelGCThreads; i2++)
    _task_queues->queue(i2)->initialize();

669 670
  _overflow_stacks = NULL;
  if (ParGCUseLocalOverflow) {
Z
zgu 已提交
671 672 673 674 675 676

    // typedef to workaround NEW_C_HEAP_ARRAY macro, which can not deal
    // with ','
    typedef Stack<oop, mtGC> GCOopStack;

    _overflow_stacks = NEW_C_HEAP_ARRAY(GCOopStack, ParallelGCThreads, mtGC);
677
    for (size_t i = 0; i < ParallelGCThreads; ++i) {
Z
zgu 已提交
678
      new (_overflow_stacks + i) Stack<oop, mtGC>();
679 680 681
    }
  }

D
duke 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
  if (UsePerfData) {
    EXCEPTION_MARK;
    ResourceMark rm;

    const char* cname =
         PerfDataManager::counter_name(_gen_counters->name_space(), "threads");
    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_None,
                                     ParallelGCThreads, CHECK);
  }
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif

// ParNewGeneration::
ParKeepAliveClosure::ParKeepAliveClosure(ParScanWeakRefClosure* cl) :
  DefNewGeneration::KeepAliveClosure(cl), _par_cl(cl) {}

700 701 702 703 704 705 706 707 708 709 710
template <class T>
void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop_work(T* p) {
#ifdef ASSERT
  {
    assert(!oopDesc::is_null(*p), "expected non-null ref");
    oop obj = oopDesc::load_decode_heap_oop_not_null(p);
    // We never expect to see a null reference being processed
    // as a weak reference.
    assert(obj->is_oop(), "expected an oop while scanning weak refs");
  }
#endif // ASSERT
D
duke 已提交
711 712 713 714

  _par_cl->do_oop_nv(p);

  if (Universe::heap()->is_in_reserved(p)) {
715 716
    oop obj = oopDesc::load_decode_heap_oop_not_null(p);
    _rs->write_ref_field_gc_par(p, obj);
D
duke 已提交
717 718 719
  }
}

720 721 722
void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(oop* p)       { ParKeepAliveClosure::do_oop_work(p); }
void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(narrowOop* p) { ParKeepAliveClosure::do_oop_work(p); }

D
duke 已提交
723 724 725 726
// ParNewGeneration::
KeepAliveClosure::KeepAliveClosure(ScanWeakRefClosure* cl) :
  DefNewGeneration::KeepAliveClosure(cl) {}

727 728 729 730 731 732 733 734 735 736 737
template <class T>
void /*ParNewGeneration::*/KeepAliveClosure::do_oop_work(T* p) {
#ifdef ASSERT
  {
    assert(!oopDesc::is_null(*p), "expected non-null ref");
    oop obj = oopDesc::load_decode_heap_oop_not_null(p);
    // We never expect to see a null reference being processed
    // as a weak reference.
    assert(obj->is_oop(), "expected an oop while scanning weak refs");
  }
#endif // ASSERT
D
duke 已提交
738 739 740 741

  _cl->do_oop_nv(p);

  if (Universe::heap()->is_in_reserved(p)) {
742 743
    oop obj = oopDesc::load_decode_heap_oop_not_null(p);
    _rs->write_ref_field_gc_par(p, obj);
D
duke 已提交
744 745 746
  }
}

747 748 749 750 751 752 753
void /*ParNewGeneration::*/KeepAliveClosure::do_oop(oop* p)       { KeepAliveClosure::do_oop_work(p); }
void /*ParNewGeneration::*/KeepAliveClosure::do_oop(narrowOop* p) { KeepAliveClosure::do_oop_work(p); }

template <class T> void ScanClosureWithParBarrier::do_oop_work(T* p) {
  T heap_oop = oopDesc::load_heap_oop(p);
  if (!oopDesc::is_null(heap_oop)) {
    oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
D
duke 已提交
754 755
    if ((HeapWord*)obj < _boundary) {
      assert(!_g->to()->is_in_reserved(obj), "Scanning field twice?");
756 757 758 759
      oop new_obj = obj->is_forwarded()
                      ? obj->forwardee()
                      : _g->DefNewGeneration::copy_to_survivor_space(obj);
      oopDesc::encode_store_heap_oop_not_null(p, new_obj);
D
duke 已提交
760 761 762 763 764 765 766 767 768 769
    }
    if (_gc_barrier) {
      // If p points to a younger generation, mark the card.
      if ((HeapWord*)obj < _gen_boundary) {
        _rs->write_ref_field_gc_par(p, obj);
      }
    }
  }
}

770 771 772
void ScanClosureWithParBarrier::do_oop(oop* p)       { ScanClosureWithParBarrier::do_oop_work(p); }
void ScanClosureWithParBarrier::do_oop(narrowOop* p) { ScanClosureWithParBarrier::do_oop_work(p); }

D
duke 已提交
773 774 775 776 777 778 779 780 781
class ParNewRefProcTaskProxy: public AbstractGangTask {
  typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
public:
  ParNewRefProcTaskProxy(ProcessTask& task, ParNewGeneration& gen,
                         Generation& next_gen,
                         HeapWord* young_old_boundary,
                         ParScanThreadStateSet& state_set);

private:
782
  virtual void work(uint worker_id);
783 784 785
  virtual void set_for_termination(int active_workers) {
    _state_set.terminator()->reset_for_reuse(active_workers);
  }
D
duke 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
private:
  ParNewGeneration&      _gen;
  ProcessTask&           _task;
  Generation&            _next_gen;
  HeapWord*              _young_old_boundary;
  ParScanThreadStateSet& _state_set;
};

ParNewRefProcTaskProxy::ParNewRefProcTaskProxy(
    ProcessTask& task, ParNewGeneration& gen,
    Generation& next_gen,
    HeapWord* young_old_boundary,
    ParScanThreadStateSet& state_set)
  : AbstractGangTask("ParNewGeneration parallel reference processing"),
    _gen(gen),
    _task(task),
    _next_gen(next_gen),
    _young_old_boundary(young_old_boundary),
    _state_set(state_set)
{
}

808
void ParNewRefProcTaskProxy::work(uint worker_id)
D
duke 已提交
809 810 811
{
  ResourceMark rm;
  HandleMark hm;
812
  ParScanThreadState& par_scan_state = _state_set.thread_state(worker_id);
D
duke 已提交
813
  par_scan_state.set_young_old_boundary(_young_old_boundary);
814
  _task.work(worker_id, par_scan_state.is_alive_closure(),
D
duke 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828
             par_scan_state.keep_alive_closure(),
             par_scan_state.evacuate_followers_closure());
}

class ParNewRefEnqueueTaskProxy: public AbstractGangTask {
  typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
  EnqueueTask& _task;

public:
  ParNewRefEnqueueTaskProxy(EnqueueTask& task)
    : AbstractGangTask("ParNewGeneration parallel reference enqueue"),
      _task(task)
  { }

829
  virtual void work(uint worker_id)
D
duke 已提交
830
  {
831
    _task.work(worker_id);
D
duke 已提交
832 833 834 835 836 837 838 839 840
  }
};


void ParNewRefProcTaskExecutor::execute(ProcessTask& task)
{
  GenCollectedHeap* gch = GenCollectedHeap::heap();
  assert(gch->kind() == CollectedHeap::GenCollectedHeap,
         "not a generational heap");
841
  FlexibleWorkGang* workers = gch->workers();
D
duke 已提交
842
  assert(workers != NULL, "Need parallel worker threads.");
843
  _state_set.reset(workers->active_workers(), _generation.promotion_failed());
D
duke 已提交
844 845 846
  ParNewRefProcTaskProxy rp_task(task, _generation, *_generation.next_gen(),
                                 _generation.reserved().end(), _state_set);
  workers->run_task(&rp_task);
847 848
  _state_set.reset(0 /* bad value in debug if not reset */,
                   _generation.promotion_failed());
D
duke 已提交
849 850 851 852 853
}

void ParNewRefProcTaskExecutor::execute(EnqueueTask& task)
{
  GenCollectedHeap* gch = GenCollectedHeap::heap();
854
  FlexibleWorkGang* workers = gch->workers();
D
duke 已提交
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
  assert(workers != NULL, "Need parallel worker threads.");
  ParNewRefEnqueueTaskProxy enq_task(task);
  workers->run_task(&enq_task);
}

void ParNewRefProcTaskExecutor::set_single_threaded_mode()
{
  _state_set.flush();
  GenCollectedHeap* gch = GenCollectedHeap::heap();
  gch->set_par_threads(0);  // 0 ==> non-parallel.
  gch->save_marks();
}

ScanClosureWithParBarrier::
ScanClosureWithParBarrier(ParNewGeneration* g, bool gc_barrier) :
  ScanClosure(g, gc_barrier) {}

EvacuateFollowersClosureGeneral::
EvacuateFollowersClosureGeneral(GenCollectedHeap* gch, int level,
                                OopsInGenClosure* cur,
                                OopsInGenClosure* older) :
  _gch(gch), _level(level),
  _scan_cur_or_nonheap(cur), _scan_older(older)
{}

void EvacuateFollowersClosureGeneral::do_void() {
  do {
    // Beware: this call will lead to closure applications via virtual
    // calls.
    _gch->oop_since_save_marks_iterate(_level,
                                       _scan_cur_or_nonheap,
                                       _scan_older);
  } while (!_gch->no_allocs_since_save_marks(_level));
}


S
sla 已提交
891 892
// A Generation that does parallel young-gen collection.

D
duke 已提交
893 894
bool ParNewGeneration::_avoid_promotion_undo = false;

S
sla 已提交
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
void ParNewGeneration::handle_promotion_failed(GenCollectedHeap* gch, ParScanThreadStateSet& thread_state_set, ParNewTracer& gc_tracer) {
  assert(_promo_failure_scan_stack.is_empty(), "post condition");
  _promo_failure_scan_stack.clear(true); // Clear cached segments.

  remove_forwarding_pointers();
  if (PrintGCDetails) {
    gclog_or_tty->print(" (promotion failed)");
  }
  // All the spaces are in play for mark-sweep.
  swap_spaces();  // Make life simpler for CMS || rescan; see 6483690.
  from()->set_next_compaction_space(to());
  gch->set_incremental_collection_failed();
  // Inform the next generation that a promotion failure occurred.
  _next_gen->promotion_failure_occurred();

  // Trace promotion failure in the parallel GC threads
  thread_state_set.trace_promotion_failed(gc_tracer);
  // Single threaded code may have reported promotion failure to the global state
  if (_promotion_failed_info.has_failed()) {
    gc_tracer.report_promotion_failed(_promotion_failed_info);
  }
  // Reset the PromotionFailureALot counters.
  NOT_PRODUCT(Universe::heap()->reset_promotion_should_fail();)
}
D
duke 已提交
919 920 921 922 923 924

void ParNewGeneration::collect(bool   full,
                               bool   clear_all_soft_refs,
                               size_t size,
                               bool   is_tlab) {
  assert(full || size > 0, "otherwise we don't want to collect");
S
sla 已提交
925

D
duke 已提交
926
  GenCollectedHeap* gch = GenCollectedHeap::heap();
S
sla 已提交
927

928
  GenGCPhaseTimes* phase_times = gch->gen_policy()->phase_times();
929
  _gc_timer->register_gc_start();
S
sla 已提交
930

D
duke 已提交
931 932 933
  assert(gch->kind() == CollectedHeap::GenCollectedHeap,
    "not a CMS generational heap");
  AdaptiveSizePolicy* size_policy = gch->gen_policy()->size_policy();
934 935 936 937 938 939 940
  FlexibleWorkGang* workers = gch->workers();
  assert(workers != NULL, "Need workgang for parallel work");
  int active_workers =
      AdaptiveSizePolicy::calc_active_workers(workers->total_workers(),
                                   workers->active_workers(),
                                   Threads::number_of_non_daemon_threads());
  workers->set_active_workers(active_workers);
941
  phase_times->note_gc_start(active_workers);
D
duke 已提交
942 943
  assert(gch->n_gens() == 2,
         "Par collection currently only works with single older gen.");
944
  _next_gen = gch->next_gen(this);
D
duke 已提交
945 946 947 948 949
  // Do we have to avoid promotion_undo?
  if (gch->collector_policy()->is_concurrent_mark_sweep_policy()) {
    set_avoid_promotion_undo(true);
  }

S
sla 已提交
950
  // If the next generation is too full to accommodate worst-case promotion
D
duke 已提交
951 952 953
  // from this generation, pass on collection; let the next generation
  // do it.
  if (!collection_attempt_is_safe()) {
954
    gch->set_incremental_collection_failed();  // slight lie, in that we did not even attempt one
D
duke 已提交
955 956 957 958
    return;
  }
  assert(to()->is_empty(), "Else not collection_attempt_is_safe");

S
sla 已提交
959 960 961 962
  ParNewTracer gc_tracer;
  gc_tracer.report_gc_start(gch->gc_cause(), _gc_timer->gc_start());
  gch->trace_heap_before_gc(&gc_tracer);

D
duke 已提交
963 964 965 966 967 968 969
  init_assuming_no_promotion_failure();

  if (UseAdaptiveSizePolicy) {
    set_survivor_overflow(false);
    size_policy->minor_collection_begin();
  }

970
  GCTraceTime t1(GCCauseString("GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL, gc_tracer.gc_id());
D
duke 已提交
971 972 973 974 975 976
  // Capture heap used before collection (for printing).
  size_t gch_prev_used = gch->used();

  SpecializationStats::clear();

  age_table()->clear();
977
  to()->clear(SpaceDecorator::Mangle);
D
duke 已提交
978 979 980

  gch->save_marks();
  assert(workers != NULL, "Need parallel worker threads.");
981 982 983 984 985 986 987 988 989
  int n_workers = active_workers;

  // Set the correct parallelism (number of queues) in the reference processor
  ref_processor()->set_active_mt_degree(n_workers);

  // Always set the terminator for the active number of workers
  // because only those workers go through the termination protocol.
  ParallelTaskTerminator _term(n_workers, task_queues());
  ParScanThreadStateSet thread_state_set(workers->active_workers(),
D
duke 已提交
990
                                         *to(), *this, *_next_gen, *task_queues(),
991
                                         _overflow_stacks, desired_plab_sz(), _term);
D
duke 已提交
992 993 994 995 996 997 998 999 1000

  ParNewGenTask tsk(this, _next_gen, reserved().end(), &thread_state_set);
  gch->set_par_threads(n_workers);
  gch->rem_set()->prepare_for_younger_refs_iterate(true);
  // It turns out that even when we're using 1 thread, doing the work in a
  // separate thread causes wide variance in run times.  We can't help this
  // in the multi-threaded case, but we special-case n=1 here to get
  // repeatable measurements of the 1-thread overhead of the parallel code.
  if (n_workers > 1) {
1001
    GenCollectedHeap::StrongRootsScope srs(gch);
D
duke 已提交
1002 1003
    workers->run_task(&tsk);
  } else {
1004
    GenCollectedHeap::StrongRootsScope srs(gch);
D
duke 已提交
1005 1006
    tsk.work(0);
  }
1007 1008
  thread_state_set.reset(0 /* Bad value in debug if not reset */,
                         promotion_failed());
D
duke 已提交
1009

1010 1011 1012 1013
  phase_times->note_gc_end();
  if (PrintGCRootsTraceTime && PrintGCDetails) {
    phase_times->log_gc_details();
  }
D
duke 已提交
1014
  // Process (weak) reference objects found during scavenge.
1015
  ReferenceProcessor* rp = ref_processor();
D
duke 已提交
1016 1017 1018 1019 1020 1021 1022 1023
  IsAliveClosure is_alive(this);
  ScanWeakRefClosure scan_weak_ref(this);
  KeepAliveClosure keep_alive(&scan_weak_ref);
  ScanClosure               scan_without_gc_barrier(this, false);
  ScanClosureWithParBarrier scan_with_gc_barrier(this, true);
  set_promo_failure_scan_stack_closure(&scan_without_gc_barrier);
  EvacuateFollowersClosureGeneral evacuate_followers(gch, _level,
    &scan_without_gc_barrier, &scan_with_gc_barrier);
1024
  rp->setup_policy(clear_all_soft_refs);
1025 1026
  // Can  the mt_degree be set later (at run_task() time would be best)?
  rp->set_active_mt_degree(active_workers);
S
sla 已提交
1027
  ReferenceProcessorStats stats;
1028
  if (rp->processing_is_mt()) {
D
duke 已提交
1029
    ParNewRefProcTaskExecutor task_executor(*this, thread_state_set);
S
sla 已提交
1030 1031
    stats = rp->process_discovered_references(&is_alive, &keep_alive,
                                              &evacuate_followers, &task_executor,
1032
                                              _gc_timer, gc_tracer.gc_id());
D
duke 已提交
1033 1034 1035 1036
  } else {
    thread_state_set.flush();
    gch->set_par_threads(0);  // 0 ==> non-parallel.
    gch->save_marks();
S
sla 已提交
1037 1038
    stats = rp->process_discovered_references(&is_alive, &keep_alive,
                                              &evacuate_followers, NULL,
1039
                                              _gc_timer, gc_tracer.gc_id());
D
duke 已提交
1040
  }
S
sla 已提交
1041
  gc_tracer.report_gc_reference_stats(stats);
D
duke 已提交
1042 1043
  if (!promotion_failed()) {
    // Swap the survivor spaces.
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    eden()->clear(SpaceDecorator::Mangle);
    from()->clear(SpaceDecorator::Mangle);
    if (ZapUnusedHeapArea) {
      // This is now done here because of the piece-meal mangling which
      // can check for valid mangling at intermediate points in the
      // collection(s).  When a minor collection fails to collect
      // sufficient space resizing of the young generation can occur
      // an redistribute the spaces in the young generation.  Mangle
      // here so that unzapped regions don't get distributed to
      // other spaces.
      to()->mangle_unused_area();
    }
D
duke 已提交
1056 1057
    swap_spaces();

1058 1059 1060 1061
    // A successful scavenge should restart the GC time limit count which is
    // for full GC's.
    size_policy->reset_gc_overhead_limit_count();

D
duke 已提交
1062
    assert(to()->is_empty(), "to space should be empty now");
1063 1064

    adjust_desired_tenuring_threshold();
D
duke 已提交
1065
  } else {
S
sla 已提交
1066
    handle_promotion_failed(gch, thread_state_set, gc_tracer);
D
duke 已提交
1067 1068 1069 1070 1071 1072
  }
  // set new iteration safe limit for the survivor spaces
  from()->set_concurrent_iteration_safe_limit(from()->top());
  to()->set_concurrent_iteration_safe_limit(to()->top());

  if (ResizePLAB) {
J
johnc 已提交
1073
    plab_stats()->adjust_desired_plab_sz(n_workers);
D
duke 已提交
1074 1075 1076 1077 1078 1079
  }

  if (PrintGC && !PrintGCDetails) {
    gch->print_heap_change(gch_prev_used);
  }

1080 1081 1082 1083
  if (PrintGCDetails && ParallelGCVerbose) {
    TASKQUEUE_STATS_ONLY(thread_state_set.print_termination_stats());
    TASKQUEUE_STATS_ONLY(thread_state_set.print_taskqueue_stats());
  }
1084

D
duke 已提交
1085 1086 1087 1088 1089
  if (UseAdaptiveSizePolicy) {
    size_policy->minor_collection_end(gch->gc_cause());
    size_policy->avg_survived()->sample(from()->used());
  }

1090 1091 1092 1093 1094
  // We need to use a monotonically non-deccreasing time in ms
  // or we will see time-warp warnings and os::javaTimeMillis()
  // does not guarantee monotonicity.
  jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  update_time_of_last_gc(now);
D
duke 已提交
1095 1096 1097

  SpecializationStats::print();

1098 1099
  rp->set_enqueuing_is_done(true);
  if (rp->processing_is_mt()) {
D
duke 已提交
1100
    ParNewRefProcTaskExecutor task_executor(*this, thread_state_set);
1101
    rp->enqueue_discovered_references(&task_executor);
D
duke 已提交
1102
  } else {
1103
    rp->enqueue_discovered_references(NULL);
D
duke 已提交
1104
  }
1105
  rp->verify_no_references_recorded();
S
sla 已提交
1106 1107 1108 1109

  gch->trace_heap_after_gc(&gc_tracer);
  gc_tracer.report_tenuring_threshold(tenuring_threshold());

1110
  _gc_timer->register_gc_end();
S
sla 已提交
1111

1112 1113 1114 1115 1116 1117 1118
  // print the young generation histo once after parnew gc then reset the PrintYoungGenHistoAfterParNewGC
  if (PrintYoungGenHistoAfterParNewGC) {
    HeapInspection inspect(false, false, false, NULL);
    inspect.heap_inspection(tty);
    PrintYoungGenHistoAfterParNewGC = false;
  }

S
sla 已提交
1119
  gc_tracer.report_gc_end(_gc_timer->gc_end(), _gc_timer->time_partitions());
D
duke 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128
}

static int sum;
void ParNewGeneration::waste_some_time() {
  for (int i = 0; i < 100; i++) {
    sum += i;
  }
}

1129
static const oop ClaimedForwardPtr = cast_to_oop<intptr_t>(0x4);
D
duke 已提交
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

// Because of concurrency, there are times where an object for which
// "is_forwarded()" is true contains an "interim" forwarding pointer
// value.  Such a value will soon be overwritten with a real value.
// This method requires "obj" to have a forwarding pointer, and waits, if
// necessary for a real one to be inserted, and returns it.

oop ParNewGeneration::real_forwardee(oop obj) {
  oop forward_ptr = obj->forwardee();
  if (forward_ptr != ClaimedForwardPtr) {
    return forward_ptr;
  } else {
    return real_forwardee_slow(obj);
  }
}

oop ParNewGeneration::real_forwardee_slow(oop obj) {
  // Spin-read if it is claimed but not yet written by another thread.
  oop forward_ptr = obj->forwardee();
  while (forward_ptr == ClaimedForwardPtr) {
    waste_some_time();
    assert(obj->is_forwarded(), "precondition");
    forward_ptr = obj->forwardee();
  }
  return forward_ptr;
}

#ifdef ASSERT
bool ParNewGeneration::is_legal_forward_ptr(oop p) {
  return
    (_avoid_promotion_undo && p == ClaimedForwardPtr)
    || Universe::heap()->is_in_reserved(p);
}
#endif

void ParNewGeneration::preserve_mark_if_necessary(oop obj, markOop m) {
1166 1167 1168
  if (m->must_be_preserved_for_promotion_failure(obj)) {
    // We should really have separate per-worker stacks, rather
    // than use locking of a common pair of stacks.
D
duke 已提交
1169
    MutexLocker ml(ParGCRareEvent_lock);
1170
    preserve_mark(obj, m);
D
duke 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
  }
}

// Multiple GC threads may try to promote an object.  If the object
// is successfully promoted, a forwarding pointer will be installed in
// the object in the young generation.  This method claims the right
// to install the forwarding pointer before it copies the object,
// thus avoiding the need to undo the copy as in
// copy_to_survivor_space_avoiding_with_undo.

oop ParNewGeneration::copy_to_survivor_space_avoiding_promotion_undo(
        ParScanThreadState* par_scan_state, oop old, size_t sz, markOop m) {
  // In the sequential version, this assert also says that the object is
  // not forwarded.  That might not be the case here.  It is the case that
  // the caller observed it to be not forwarded at some time in the past.
  assert(is_in_reserved(old), "shouldn't be scavenging this oop");

  // The sequential code read "old->age()" below.  That doesn't work here,
  // since the age is in the mark word, and that might be overwritten with
  // a forwarding pointer by a parallel thread.  So we must save the mark
  // word in a local and then analyze it.
  oopDesc dummyOld;
  dummyOld.set_mark(m);
  assert(!dummyOld.is_forwarded(),
         "should not be called with forwarding pointer mark word.");

  oop new_obj = NULL;
  oop forward_ptr;

  // Try allocating obj in to-space (unless too old)
  if (dummyOld.age() < tenuring_threshold()) {
    new_obj = (oop)par_scan_state->alloc_in_to_space(sz);
    if (new_obj == NULL) {
      set_survivor_overflow(true);
    }
  }

  if (new_obj == NULL) {
    // Either to-space is full or we decided to promote
    // try allocating obj tenured

    // Attempt to install a null forwarding pointer (atomically),
    // to claim the right to install the real forwarding pointer.
    forward_ptr = old->forward_to_atomic(ClaimedForwardPtr);
    if (forward_ptr != NULL) {
      // someone else beat us to it.
        return real_forwardee(old);
    }

1220 1221 1222 1223
    if (!_promotion_failed) {
      new_obj = _next_gen->par_promote(par_scan_state->thread_num(),
                                        old, m, sz);
    }
D
duke 已提交
1224 1225 1226 1227 1228 1229 1230

    if (new_obj == NULL) {
      // promotion failed, forward to self
      _promotion_failed = true;
      new_obj = old;

      preserve_mark_if_necessary(old, m);
S
sla 已提交
1231
      par_scan_state->register_promotion_failure(sz);
D
duke 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    }

    old->forward_to(new_obj);
    forward_ptr = NULL;
  } else {
    // Is in to-space; do copying ourselves.
    Copy::aligned_disjoint_words((HeapWord*)old, (HeapWord*)new_obj, sz);
    forward_ptr = old->forward_to_atomic(new_obj);
    // Restore the mark word copied above.
    new_obj->set_mark(m);
    // Increment age if obj still in new generation
    new_obj->incr_age();
    par_scan_state->age_table()->add(new_obj, sz);
  }
  assert(new_obj != NULL, "just checking");

1248 1249 1250 1251 1252 1253
#ifndef PRODUCT
  // This code must come after the CAS test, or it will print incorrect
  // information.
  if (TraceScavenge) {
    gclog_or_tty->print_cr("{%s %s " PTR_FORMAT " -> " PTR_FORMAT " (%d)}",
       is_in_reserved(new_obj) ? "copying" : "tenuring",
1254
       new_obj->klass()->internal_name(), (void *)old, (void *)new_obj, new_obj->size());
1255 1256 1257
  }
#endif

D
duke 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
  if (forward_ptr == NULL) {
    oop obj_to_push = new_obj;
    if (par_scan_state->should_be_partially_scanned(obj_to_push, old)) {
      // Length field used as index of next element to be scanned.
      // Real length can be obtained from real_forwardee()
      arrayOop(old)->set_length(0);
      obj_to_push = old;
      assert(obj_to_push->is_forwarded() && obj_to_push->forwardee() != obj_to_push,
             "push forwarded object");
    }
    // Push it on one of the queues of to-be-scanned objects.
1269 1270 1271 1272 1273 1274 1275 1276
    bool simulate_overflow = false;
    NOT_PRODUCT(
      if (ParGCWorkQueueOverflowALot && should_simulate_overflow()) {
        // simulate a stack overflow
        simulate_overflow = true;
      }
    )
    if (simulate_overflow || !par_scan_state->work_queue()->push(obj_to_push)) {
D
duke 已提交
1277 1278 1279 1280
      // Add stats for overflow pushes.
      if (Verbose && PrintGCDetails) {
        gclog_or_tty->print("queue overflow!\n");
      }
1281
      push_on_overflow_list(old, par_scan_state);
1282
      TASKQUEUE_STATS_ONLY(par_scan_state->taskqueue_stats().record_overflow(0));
D
duke 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    }

    return new_obj;
  }

  // Oops.  Someone beat us to it.  Undo the allocation.  Where did we
  // allocate it?
  if (is_in_reserved(new_obj)) {
    // Must be in to_space.
    assert(to()->is_in_reserved(new_obj), "Checking");
    if (forward_ptr == ClaimedForwardPtr) {
      // Wait to get the real forwarding pointer value.
      forward_ptr = real_forwardee(old);
    }
    par_scan_state->undo_alloc_in_to_space((HeapWord*)new_obj, sz);
  }

  return forward_ptr;
}


// Multiple GC threads may try to promote the same object.  If two
// or more GC threads copy the object, only one wins the race to install
// the forwarding pointer.  The other threads have to undo their copy.

oop ParNewGeneration::copy_to_survivor_space_with_undo(
        ParScanThreadState* par_scan_state, oop old, size_t sz, markOop m) {

  // In the sequential version, this assert also says that the object is
  // not forwarded.  That might not be the case here.  It is the case that
  // the caller observed it to be not forwarded at some time in the past.
  assert(is_in_reserved(old), "shouldn't be scavenging this oop");

  // The sequential code read "old->age()" below.  That doesn't work here,
  // since the age is in the mark word, and that might be overwritten with
  // a forwarding pointer by a parallel thread.  So we must save the mark
  // word here, install it in a local oopDesc, and then analyze it.
  oopDesc dummyOld;
  dummyOld.set_mark(m);
  assert(!dummyOld.is_forwarded(),
         "should not be called with forwarding pointer mark word.");

  bool failed_to_promote = false;
  oop new_obj = NULL;
  oop forward_ptr;

  // Try allocating obj in to-space (unless too old)
  if (dummyOld.age() < tenuring_threshold()) {
    new_obj = (oop)par_scan_state->alloc_in_to_space(sz);
    if (new_obj == NULL) {
      set_survivor_overflow(true);
    }
  }

  if (new_obj == NULL) {
    // Either to-space is full or we decided to promote
    // try allocating obj tenured
    new_obj = _next_gen->par_promote(par_scan_state->thread_num(),
                                       old, m, sz);

    if (new_obj == NULL) {
      // promotion failed, forward to self
      forward_ptr = old->forward_to_atomic(old);
      new_obj = old;

      if (forward_ptr != NULL) {
        return forward_ptr;   // someone else succeeded
      }

      _promotion_failed = true;
      failed_to_promote = true;

      preserve_mark_if_necessary(old, m);
S
sla 已提交
1356
      par_scan_state->register_promotion_failure(sz);
D
duke 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    }
  } else {
    // Is in to-space; do copying ourselves.
    Copy::aligned_disjoint_words((HeapWord*)old, (HeapWord*)new_obj, sz);
    // Restore the mark word copied above.
    new_obj->set_mark(m);
    // Increment age if new_obj still in new generation
    new_obj->incr_age();
    par_scan_state->age_table()->add(new_obj, sz);
  }
  assert(new_obj != NULL, "just checking");

1369 1370 1371 1372 1373 1374
#ifndef PRODUCT
  // This code must come after the CAS test, or it will print incorrect
  // information.
  if (TraceScavenge) {
    gclog_or_tty->print_cr("{%s %s " PTR_FORMAT " -> " PTR_FORMAT " (%d)}",
       is_in_reserved(new_obj) ? "copying" : "tenuring",
1375
       new_obj->klass()->internal_name(), (void *)old, (void *)new_obj, new_obj->size());
1376 1377 1378
  }
#endif

D
duke 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
  // Now attempt to install the forwarding pointer (atomically).
  // We have to copy the mark word before overwriting with forwarding
  // ptr, so we can restore it below in the copy.
  if (!failed_to_promote) {
    forward_ptr = old->forward_to_atomic(new_obj);
  }

  if (forward_ptr == NULL) {
    oop obj_to_push = new_obj;
    if (par_scan_state->should_be_partially_scanned(obj_to_push, old)) {
      // Length field used as index of next element to be scanned.
      // Real length can be obtained from real_forwardee()
      arrayOop(old)->set_length(0);
      obj_to_push = old;
      assert(obj_to_push->is_forwarded() && obj_to_push->forwardee() != obj_to_push,
             "push forwarded object");
    }
    // Push it on one of the queues of to-be-scanned objects.
1397 1398 1399 1400 1401 1402 1403 1404
    bool simulate_overflow = false;
    NOT_PRODUCT(
      if (ParGCWorkQueueOverflowALot && should_simulate_overflow()) {
        // simulate a stack overflow
        simulate_overflow = true;
      }
    )
    if (simulate_overflow || !par_scan_state->work_queue()->push(obj_to_push)) {
D
duke 已提交
1405
      // Add stats for overflow pushes.
1406
      push_on_overflow_list(old, par_scan_state);
1407
      TASKQUEUE_STATS_ONLY(par_scan_state->taskqueue_stats().record_overflow(0));
D
duke 已提交
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    }

    return new_obj;
  }

  // Oops.  Someone beat us to it.  Undo the allocation.  Where did we
  // allocate it?
  if (is_in_reserved(new_obj)) {
    // Must be in to_space.
    assert(to()->is_in_reserved(new_obj), "Checking");
    par_scan_state->undo_alloc_in_to_space((HeapWord*)new_obj, sz);
  } else {
    assert(!_avoid_promotion_undo, "Should not be here if avoiding.");
    _next_gen->par_promote_alloc_undo(par_scan_state->thread_num(),
                                      (HeapWord*)new_obj, sz);
  }

  return forward_ptr;
}

1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
#ifndef PRODUCT
// It's OK to call this multi-threaded;  the worst thing
// that can happen is that we'll get a bunch of closely
// spaced simulated oveflows, but that's OK, in fact
// probably good as it would exercise the overflow code
// under contention.
bool ParNewGeneration::should_simulate_overflow() {
  if (_overflow_counter-- <= 0) { // just being defensive
    _overflow_counter = ParGCWorkQueueOverflowInterval;
    return true;
  } else {
    return false;
  }
}
#endif

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
// In case we are using compressed oops, we need to be careful.
// If the object being pushed is an object array, then its length
// field keeps track of the "grey boundary" at which the next
// incremental scan will be done (see ParGCArrayScanChunk).
// When using compressed oops, this length field is kept in the
// lower 32 bits of the erstwhile klass word and cannot be used
// for the overflow chaining pointer (OCP below). As such the OCP
// would itself need to be compressed into the top 32-bits in this
// case. Unfortunately, see below, in the event that we have a
// promotion failure, the node to be pushed on the list can be
// outside of the Java heap, so the heap-based pointer compression
// would not work (we would have potential aliasing between C-heap
// and Java-heap pointers). For this reason, when using compressed
// oops, we simply use a worker-thread-local, non-shared overflow
// list in the form of a growable array, with a slightly different
// overflow stack draining strategy. If/when we start using fat
// stacks here, we can go back to using (fat) pointer chains
// (although some performance comparisons would be useful since
// single global lists have their own performance disadvantages
// as we were made painfully aware not long ago, see 6786503).
1464
#define BUSY (cast_to_oop<intptr_t>(0x1aff1aff))
1465
void ParNewGeneration::push_on_overflow_list(oop from_space_obj, ParScanThreadState* par_scan_state) {
1466
  assert(is_in_reserved(from_space_obj), "Should be from this generation");
1467
  if (ParGCUseLocalOverflow) {
1468 1469 1470 1471
    // In the case of compressed oops, we use a private, not-shared
    // overflow stack.
    par_scan_state->push_on_overflow_stack(from_space_obj);
  } else {
1472
    assert(!UseCompressedOops, "Error");
1473 1474 1475 1476 1477
    // if the object has been forwarded to itself, then we cannot
    // use the klass pointer for the linked list.  Instead we have
    // to allocate an oopDesc in the C-Heap and use that for the linked list.
    // XXX This is horribly inefficient when a promotion failure occurs
    // and should be fixed. XXX FIX ME !!!
1478
#ifndef PRODUCT
1479 1480
    Atomic::inc_ptr(&_num_par_pushes);
    assert(_num_par_pushes > 0, "Tautology");
1481
#endif
1482
    if (from_space_obj->forwardee() == from_space_obj) {
Z
zgu 已提交
1483
      oopDesc* listhead = NEW_C_HEAP_ARRAY(oopDesc, 1, mtGC);
1484 1485
      listhead->forward_to(from_space_obj);
      from_space_obj = listhead;
1486
    }
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    oop observed_overflow_list = _overflow_list;
    oop cur_overflow_list;
    do {
      cur_overflow_list = observed_overflow_list;
      if (cur_overflow_list != BUSY) {
        from_space_obj->set_klass_to_list_ptr(cur_overflow_list);
      } else {
        from_space_obj->set_klass_to_list_ptr(NULL);
      }
      observed_overflow_list =
        (oop)Atomic::cmpxchg_ptr(from_space_obj, &_overflow_list, cur_overflow_list);
    } while (cur_overflow_list != observed_overflow_list);
  }
D
duke 已提交
1500 1501
}

1502 1503 1504
bool ParNewGeneration::take_from_overflow_list(ParScanThreadState* par_scan_state) {
  bool res;

1505
  if (ParGCUseLocalOverflow) {
1506 1507
    res = par_scan_state->take_from_overflow_stack();
  } else {
1508
    assert(!UseCompressedOops, "Error");
1509 1510 1511 1512 1513 1514
    res = take_from_overflow_list_work(par_scan_state);
  }
  return res;
}


1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
// *NOTE*: The overflow list manipulation code here and
// in CMSCollector:: are very similar in shape,
// except that in the CMS case we thread the objects
// directly into the list via their mark word, and do
// not need to deal with special cases below related
// to chunking of object arrays and promotion failure
// handling.
// CR 6797058 has been filed to attempt consolidation of
// the common code.
// Because of the common code, if you make any changes in
// the code below, please check the CMS version to see if
// similar changes might be needed.
// See CMSCollector::par_take_from_overflow_list() for
// more extensive documentation comments.
1529
bool ParNewGeneration::take_from_overflow_list_work(ParScanThreadState* par_scan_state) {
D
duke 已提交
1530 1531
  ObjToScanQueue* work_q = par_scan_state->work_queue();
  // How many to take?
1532
  size_t objsFromOverflow = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
1533
                                 (size_t)ParGCDesiredObjsFromOverflowList);
D
duke 已提交
1534

1535
  assert(!UseCompressedOops, "Error");
1536
  assert(par_scan_state->overflow_stack() == NULL, "Error");
D
duke 已提交
1537 1538 1539
  if (_overflow_list == NULL) return false;

  // Otherwise, there was something there; try claiming the list.
1540
  oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
D
duke 已提交
1541
  // Trim off a prefix of at most objsFromOverflow items
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
  Thread* tid = Thread::current();
  size_t spin_count = (size_t)ParallelGCThreads;
  size_t sleep_time_millis = MAX2((size_t)1, objsFromOverflow/100);
  for (size_t spin = 0; prefix == BUSY && spin < spin_count; spin++) {
    // someone grabbed it before we did ...
    // ... we spin for a short while...
    os::sleep(tid, sleep_time_millis, false);
    if (_overflow_list == NULL) {
      // nothing left to take
      return false;
    } else if (_overflow_list != BUSY) {
     // try and grab the prefix
1554
     prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
    }
  }
  if (prefix == NULL || prefix == BUSY) {
     // Nothing to take or waited long enough
     if (prefix == NULL) {
       // Write back the NULL in case we overwrote it with BUSY above
       // and it is still the same value.
       (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
     }
     return false;
  }
  assert(prefix != NULL && prefix != BUSY, "Error");
  size_t i = 1;
D
duke 已提交
1568
  oop cur = prefix;
1569
  while (i < objsFromOverflow && cur->klass_or_null() != NULL) {
1570
    i++; cur = cur->list_ptr_from_klass();
D
duke 已提交
1571 1572 1573
  }

  // Reattach remaining (suffix) to overflow list
1574 1575 1576 1577 1578
  if (cur->klass_or_null() == NULL) {
    // Write back the NULL in lieu of the BUSY we wrote
    // above and it is still the same value.
    if (_overflow_list == BUSY) {
      (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
D
duke 已提交
1579
    }
1580
  } else {
1581 1582
    assert(cur->klass_or_null() != (Klass*)(address)BUSY, "Error");
    oop suffix = cur->list_ptr_from_klass();       // suffix will be put back on global list
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
    cur->set_klass_to_list_ptr(NULL);     // break off suffix
    // It's possible that the list is still in the empty(busy) state
    // we left it in a short while ago; in that case we may be
    // able to place back the suffix.
    oop observed_overflow_list = _overflow_list;
    oop cur_overflow_list = observed_overflow_list;
    bool attached = false;
    while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
      observed_overflow_list =
        (oop) Atomic::cmpxchg_ptr(suffix, &_overflow_list, cur_overflow_list);
      if (cur_overflow_list == observed_overflow_list) {
        attached = true;
        break;
      } else cur_overflow_list = observed_overflow_list;
    }
    if (!attached) {
      // Too bad, someone else got in in between; we'll need to do a splice.
      // Find the last item of suffix list
      oop last = suffix;
      while (last->klass_or_null() != NULL) {
1603
        last = last->list_ptr_from_klass();
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
      }
      // Atomically prepend suffix to current overflow list
      observed_overflow_list = _overflow_list;
      do {
        cur_overflow_list = observed_overflow_list;
        if (cur_overflow_list != BUSY) {
          // Do the splice ...
          last->set_klass_to_list_ptr(cur_overflow_list);
        } else { // cur_overflow_list == BUSY
          last->set_klass_to_list_ptr(NULL);
        }
        observed_overflow_list =
          (oop)Atomic::cmpxchg_ptr(suffix, &_overflow_list, cur_overflow_list);
      } while (cur_overflow_list != observed_overflow_list);
D
duke 已提交
1618 1619 1620 1621
    }
  }

  // Push objects on prefix list onto this thread's work queue
1622
  assert(prefix != NULL && prefix != BUSY, "program logic");
D
duke 已提交
1623
  cur = prefix;
1624
  ssize_t n = 0;
D
duke 已提交
1625 1626
  while (cur != NULL) {
    oop obj_to_push = cur->forwardee();
1627
    oop next        = cur->list_ptr_from_klass();
D
duke 已提交
1628
    cur->set_klass(obj_to_push->klass());
1629 1630 1631 1632 1633 1634
    // This may be an array object that is self-forwarded. In that case, the list pointer
    // space, cur, is not in the Java heap, but rather in the C-heap and should be freed.
    if (!is_in_reserved(cur)) {
      // This can become a scaling bottleneck when there is work queue overflow coincident
      // with promotion failure.
      oopDesc* f = cur;
Z
zgu 已提交
1635
      FREE_C_HEAP_ARRAY(oopDesc, f, mtGC);
1636
    } else if (par_scan_state->should_be_partially_scanned(obj_to_push, cur)) {
D
duke 已提交
1637
      assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");
1638
      obj_to_push = cur;
D
duke 已提交
1639
    }
1640 1641
    bool ok = work_q->push(obj_to_push);
    assert(ok, "Should have succeeded");
D
duke 已提交
1642 1643 1644
    cur = next;
    n++;
  }
1645
  TASKQUEUE_STATS_ONLY(par_scan_state->note_overflow_refill(n));
1646 1647 1648 1649
#ifndef PRODUCT
  assert(_num_par_pushes >= n, "Too many pops?");
  Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);
#endif
D
duke 已提交
1650 1651
  return true;
}
1652
#undef BUSY
D
duke 已提交
1653

S
sla 已提交
1654
void ParNewGeneration::ref_processor_init() {
D
duke 已提交
1655 1656
  if (_ref_processor == NULL) {
    // Allocate and initialize a reference processor
1657 1658 1659 1660 1661 1662 1663
    _ref_processor =
      new ReferenceProcessor(_reserved,                  // span
                             ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing
                             (int) ParallelGCThreads,    // mt processing degree
                             refs_discovery_is_mt(),     // mt discovery
                             (int) ParallelGCThreads,    // mt discovery degree
                             refs_discovery_is_atomic(), // atomic_discovery
1664
                             NULL);                      // is_alive_non_header
D
duke 已提交
1665 1666 1667 1668 1669 1670
  }
}

const char* ParNewGeneration::name() const {
  return "par new generation";
}