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