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