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 "memory/allocation.hpp" 27 #include "memory/allocation.inline.hpp" 28 #include "runtime/atomic.inline.hpp" 29 #include "runtime/os.hpp" 30 #include "utilities/workgroup.hpp" 31 32 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 33 34 // Definitions of WorkGang methods. 35 36 AbstractWorkGang::AbstractWorkGang(const char* name, 37 bool are_GC_task_threads, 38 bool are_ConcurrentGC_threads) : 39 _name(name), 40 _are_GC_task_threads(are_GC_task_threads), 41 _are_ConcurrentGC_threads(are_ConcurrentGC_threads) { 42 43 assert(!(are_GC_task_threads && are_ConcurrentGC_threads), 44 "They cannot both be STW GC and Concurrent threads" ); 45 46 // Other initialization. 47 _monitor = new Monitor(/* priority */ Mutex::leaf, 48 /* name */ "WorkGroup monitor", 49 /* allow_vm_block */ are_GC_task_threads, 50 Monitor::_safepoint_check_sometimes); 51 assert(monitor() != NULL, "Failed to allocate monitor"); 52 _terminate = false; 53 _task = NULL; 54 _sequence_number = 0; 55 _started_workers = 0; 56 _finished_workers = 0; 57 } 58 59 WorkGang::WorkGang(const char* name, 60 uint workers, 61 bool are_GC_task_threads, 62 bool are_ConcurrentGC_threads) : 63 AbstractWorkGang(name, are_GC_task_threads, are_ConcurrentGC_threads) { 64 _total_workers = workers; 65 } 66 67 GangWorker* WorkGang::allocate_worker(uint which) { 68 GangWorker* new_worker = new GangWorker(this, which); 69 return new_worker; 70 } 71 72 // The current implementation will exit if the allocation 73 // of any worker fails. Still, return a boolean so that 74 // a future implementation can possibly do a partial 75 // initialization of the workers and report such to the 76 // caller. 77 bool WorkGang::initialize_workers() { 78 79 if (TraceWorkGang) { 80 tty->print_cr("Constructing work gang %s with %d threads", 81 name(), 82 total_workers()); 83 } 84 _gang_workers = NEW_C_HEAP_ARRAY(GangWorker*, total_workers(), mtInternal); 85 if (gang_workers() == NULL) { 86 vm_exit_out_of_memory(0, OOM_MALLOC_ERROR, "Cannot create GangWorker array."); 87 return false; 88 } 89 os::ThreadType worker_type; 90 if (are_ConcurrentGC_threads()) { 91 worker_type = os::cgc_thread; 92 } else { 93 worker_type = os::pgc_thread; 94 } 95 for (uint worker = 0; worker < total_workers(); worker += 1) { 96 GangWorker* new_worker = allocate_worker(worker); 97 assert(new_worker != NULL, "Failed to allocate GangWorker"); 98 _gang_workers[worker] = new_worker; 99 if (new_worker == NULL || !os::create_thread(new_worker, worker_type)) { 100 vm_exit_out_of_memory(0, OOM_MALLOC_ERROR, 101 "Cannot create worker GC thread. Out of system resources."); 102 return false; 103 } 104 if (!DisableStartThread) { 105 os::start_thread(new_worker); 106 } 107 } 108 return true; 109 } 110 111 AbstractWorkGang::~AbstractWorkGang() { 112 if (TraceWorkGang) { 113 tty->print_cr("Destructing work gang %s", name()); 114 } 115 stop(); // stop all the workers 116 for (uint worker = 0; worker < total_workers(); worker += 1) { 117 delete gang_worker(worker); 118 } 119 delete gang_workers(); 120 delete monitor(); 121 } 122 123 GangWorker* AbstractWorkGang::gang_worker(uint i) const { 124 // Array index bounds checking. 125 GangWorker* result = NULL; 126 assert(gang_workers() != NULL, "No workers for indexing"); 127 assert(((i >= 0) && (i < total_workers())), "Worker index out of bounds"); 128 result = _gang_workers[i]; 129 assert(result != NULL, "Indexing to null worker"); 130 return result; 131 } 132 133 void WorkGang::run_task(AbstractGangTask* task) { 134 run_task(task, total_workers()); 135 } 136 137 void WorkGang::run_task(AbstractGangTask* task, uint no_of_parallel_workers) { 138 task->set_for_termination(no_of_parallel_workers); 139 140 // This thread is executed by the VM thread which does not block 141 // on ordinary MutexLocker's. 142 MutexLockerEx ml(monitor(), Mutex::_no_safepoint_check_flag); 143 if (TraceWorkGang) { 144 tty->print_cr("Running work gang %s task %s", name(), task->name()); 145 } 146 // Tell all the workers to run a task. 147 assert(task != NULL, "Running a null task"); 148 // Initialize. 149 _task = task; 150 _sequence_number += 1; 151 _started_workers = 0; 152 _finished_workers = 0; 153 // Tell the workers to get to work. 154 monitor()->notify_all(); 155 // Wait for them to be finished 156 while (finished_workers() < no_of_parallel_workers) { 157 if (TraceWorkGang) { 158 tty->print_cr("Waiting in work gang %s: %d/%d finished sequence %d", 159 name(), finished_workers(), no_of_parallel_workers, 160 _sequence_number); 161 } 162 monitor()->wait(/* no_safepoint_check */ true); 163 } 164 _task = NULL; 165 if (TraceWorkGang) { 166 tty->print_cr("\nFinished work gang %s: %d/%d sequence %d", 167 name(), finished_workers(), no_of_parallel_workers, 168 _sequence_number); 169 Thread* me = Thread::current(); 170 tty->print_cr(" T: 0x%x VM_thread: %d", me, me->is_VM_thread()); 171 } 172 } 173 174 void FlexibleWorkGang::run_task(AbstractGangTask* task) { 175 // If active_workers() is passed, _finished_workers 176 // must only be incremented for workers that find non_null 177 // work (as opposed to all those that just check that the 178 // task is not null). 179 WorkGang::run_task(task, (uint) active_workers()); 180 } 181 182 void AbstractWorkGang::stop() { 183 // Tell all workers to terminate, then wait for them to become inactive. 184 MutexLockerEx ml(monitor(), Mutex::_no_safepoint_check_flag); 185 if (TraceWorkGang) { 186 tty->print_cr("Stopping work gang %s task %s", name(), task()->name()); 187 } 188 _task = NULL; 189 _terminate = true; 190 monitor()->notify_all(); 191 while (finished_workers() < active_workers()) { 192 if (TraceWorkGang) { 193 tty->print_cr("Waiting in work gang %s: %d/%d finished", 194 name(), finished_workers(), active_workers()); 195 } 196 monitor()->wait(/* no_safepoint_check */ true); 197 } 198 } 199 200 void AbstractWorkGang::internal_worker_poll(WorkData* data) const { 201 assert(monitor()->owned_by_self(), "worker_poll is an internal method"); 202 assert(data != NULL, "worker data is null"); 203 data->set_terminate(terminate()); 204 data->set_task(task()); 205 data->set_sequence_number(sequence_number()); 206 } 207 208 void AbstractWorkGang::internal_note_start() { 209 assert(monitor()->owned_by_self(), "note_finish is an internal method"); 210 _started_workers += 1; 211 } 212 213 void AbstractWorkGang::internal_note_finish() { 214 assert(monitor()->owned_by_self(), "note_finish is an internal method"); 215 _finished_workers += 1; 216 } 217 218 void AbstractWorkGang::print_worker_threads_on(outputStream* st) const { 219 uint num_thr = total_workers(); 220 for (uint i = 0; i < num_thr; i++) { 221 gang_worker(i)->print_on(st); 222 st->cr(); 223 } 224 } 225 226 void AbstractWorkGang::threads_do(ThreadClosure* tc) const { 227 assert(tc != NULL, "Null ThreadClosure"); 228 uint num_thr = total_workers(); 229 for (uint i = 0; i < num_thr; i++) { 230 tc->do_thread(gang_worker(i)); 231 } 232 } 233 234 // GangWorker methods. 235 236 GangWorker::GangWorker(AbstractWorkGang* gang, uint id) { 237 _gang = gang; 238 set_id(id); 239 set_name("Gang worker#%d (%s)", id, gang->name()); 240 } 241 242 void GangWorker::run() { 243 initialize(); 244 loop(); 245 } 246 247 void GangWorker::initialize() { 248 this->initialize_thread_local_storage(); 249 this->record_stack_base_and_size(); 250 assert(_gang != NULL, "No gang to run in"); 251 os::set_priority(this, NearMaxPriority); 252 if (TraceWorkGang) { 253 tty->print_cr("Running gang worker for gang %s id %d", 254 gang()->name(), id()); 255 } 256 // The VM thread should not execute here because MutexLocker's are used 257 // as (opposed to MutexLockerEx's). 258 assert(!Thread::current()->is_VM_thread(), "VM thread should not be part" 259 " of a work gang"); 260 } 261 262 void GangWorker::loop() { 263 int previous_sequence_number = 0; 264 Monitor* gang_monitor = gang()->monitor(); 265 for ( ; /* !terminate() */; ) { 266 WorkData data; 267 int part; // Initialized below. 268 { 269 // Grab the gang mutex. 270 MutexLocker ml(gang_monitor); 271 // Wait for something to do. 272 // Polling outside the while { wait } avoids missed notifies 273 // in the outer loop. 274 gang()->internal_worker_poll(&data); 275 if (TraceWorkGang) { 276 tty->print("Polled outside for work in gang %s worker %d", 277 gang()->name(), id()); 278 tty->print(" terminate: %s", 279 data.terminate() ? "true" : "false"); 280 tty->print(" sequence: %d (prev: %d)", 281 data.sequence_number(), previous_sequence_number); 282 if (data.task() != NULL) { 283 tty->print(" task: %s", data.task()->name()); 284 } else { 285 tty->print(" task: NULL"); 286 } 287 tty->cr(); 288 } 289 for ( ; /* break or return */; ) { 290 // Terminate if requested. 291 if (data.terminate()) { 292 gang()->internal_note_finish(); 293 gang_monitor->notify_all(); 294 return; 295 } 296 // Check for new work. 297 if ((data.task() != NULL) && 298 (data.sequence_number() != previous_sequence_number)) { 299 if (gang()->needs_more_workers()) { 300 gang()->internal_note_start(); 301 gang_monitor->notify_all(); 302 part = gang()->started_workers() - 1; 303 break; 304 } 305 } 306 // Nothing to do. 307 gang_monitor->wait(/* no_safepoint_check */ true); 308 gang()->internal_worker_poll(&data); 309 if (TraceWorkGang) { 310 tty->print("Polled inside for work in gang %s worker %d", 311 gang()->name(), id()); 312 tty->print(" terminate: %s", 313 data.terminate() ? "true" : "false"); 314 tty->print(" sequence: %d (prev: %d)", 315 data.sequence_number(), previous_sequence_number); 316 if (data.task() != NULL) { 317 tty->print(" task: %s", data.task()->name()); 318 } else { 319 tty->print(" task: NULL"); 320 } 321 tty->cr(); 322 } 323 } 324 // Drop gang mutex. 325 } 326 if (TraceWorkGang) { 327 tty->print("Work for work gang %s id %d task %s part %d", 328 gang()->name(), id(), data.task()->name(), part); 329 } 330 assert(data.task() != NULL, "Got null task"); 331 data.task()->work(part); 332 { 333 if (TraceWorkGang) { 334 tty->print("Finish for work gang %s id %d task %s part %d", 335 gang()->name(), id(), data.task()->name(), part); 336 } 337 // Grab the gang mutex. 338 MutexLocker ml(gang_monitor); 339 gang()->internal_note_finish(); 340 // Tell the gang you are done. 341 gang_monitor->notify_all(); 342 // Drop the gang mutex. 343 } 344 previous_sequence_number = data.sequence_number(); 345 } 346 } 347 348 bool GangWorker::is_GC_task_thread() const { 349 return gang()->are_GC_task_threads(); 350 } 351 352 bool GangWorker::is_ConcurrentGC_thread() const { 353 return gang()->are_ConcurrentGC_threads(); 354 } 355 356 void GangWorker::print_on(outputStream* st) const { 357 st->print("\"%s\" ", name()); 358 Thread::print_on(st); 359 st->cr(); 360 } 361 362 // Printing methods 363 364 const char* AbstractWorkGang::name() const { 365 return _name; 366 } 367 368 #ifndef PRODUCT 369 370 const char* AbstractGangTask::name() const { 371 return _name; 372 } 373 374 #endif /* PRODUCT */ 375 376 // FlexibleWorkGang 377 378 379 // *** WorkGangBarrierSync 380 381 WorkGangBarrierSync::WorkGangBarrierSync() 382 : _monitor(Mutex::safepoint, "work gang barrier sync", true, 383 Monitor::_safepoint_check_never), 384 _n_workers(0), _n_completed(0), _should_reset(false), _aborted(false) { 385 } 386 387 WorkGangBarrierSync::WorkGangBarrierSync(uint n_workers, const char* name) 388 : _monitor(Mutex::safepoint, name, true, Monitor::_safepoint_check_never), 389 _n_workers(n_workers), _n_completed(0), _should_reset(false), _aborted(false) { 390 } 391 392 void WorkGangBarrierSync::set_n_workers(uint n_workers) { 393 _n_workers = n_workers; 394 _n_completed = 0; 395 _should_reset = false; 396 _aborted = false; 397 } 398 399 bool WorkGangBarrierSync::enter() { 400 MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag); 401 if (should_reset()) { 402 // The should_reset() was set and we are the first worker to enter 403 // the sync barrier. We will zero the n_completed() count which 404 // effectively resets the barrier. 405 zero_completed(); 406 set_should_reset(false); 407 } 408 inc_completed(); 409 if (n_completed() == n_workers()) { 410 // At this point we would like to reset the barrier to be ready in 411 // case it is used again. However, we cannot set n_completed() to 412 // 0, even after the notify_all(), given that some other workers 413 // might still be waiting for n_completed() to become == 414 // n_workers(). So, if we set n_completed() to 0, those workers 415 // will get stuck (as they will wake up, see that n_completed() != 416 // n_workers() and go back to sleep). Instead, we raise the 417 // should_reset() flag and the barrier will be reset the first 418 // time a worker enters it again. 419 set_should_reset(true); 420 monitor()->notify_all(); 421 } else { 422 while (n_completed() != n_workers() && !aborted()) { 423 monitor()->wait(/* no_safepoint_check */ true); 424 } 425 } 426 return !aborted(); 427 } 428 429 void WorkGangBarrierSync::abort() { 430 MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag); 431 set_aborted(); 432 monitor()->notify_all(); 433 } 434 435 // SubTasksDone functions. 436 437 SubTasksDone::SubTasksDone(uint n) : 438 _n_tasks(n), _n_threads(1), _tasks(NULL) { 439 _tasks = NEW_C_HEAP_ARRAY(uint, n, mtInternal); 440 guarantee(_tasks != NULL, "alloc failure"); 441 clear(); 442 } 443 444 bool SubTasksDone::valid() { 445 return _tasks != NULL; 446 } 447 448 void SubTasksDone::set_n_threads(uint t) { 449 assert(_claimed == 0 || _threads_completed == _n_threads, 450 "should not be called while tasks are being processed!"); 451 _n_threads = (t == 0 ? 1 : t); 452 } 453 454 void SubTasksDone::clear() { 455 for (uint i = 0; i < _n_tasks; i++) { 456 _tasks[i] = 0; 457 } 458 _threads_completed = 0; 459 #ifdef ASSERT 460 _claimed = 0; 461 #endif 462 } 463 464 bool SubTasksDone::is_task_claimed(uint t) { 465 assert(0 <= t && t < _n_tasks, "bad task id."); 466 uint old = _tasks[t]; 467 if (old == 0) { 468 old = Atomic::cmpxchg(1, &_tasks[t], 0); 469 } 470 assert(_tasks[t] == 1, "What else?"); 471 bool res = old != 0; 472 #ifdef ASSERT 473 if (!res) { 474 assert(_claimed < _n_tasks, "Too many tasks claimed; missing clear?"); 475 Atomic::inc((volatile jint*) &_claimed); 476 } 477 #endif 478 return res; 479 } 480 481 void SubTasksDone::all_tasks_completed() { 482 jint observed = _threads_completed; 483 jint old; 484 do { 485 old = observed; 486 observed = Atomic::cmpxchg(old+1, &_threads_completed, old); 487 } while (observed != old); 488 // If this was the last thread checking in, clear the tasks. 489 if (observed+1 == (jint)_n_threads) clear(); 490 } 491 492 493 SubTasksDone::~SubTasksDone() { 494 if (_tasks != NULL) FREE_C_HEAP_ARRAY(jint, _tasks); 495 } 496 497 // *** SequentialSubTasksDone 498 499 void SequentialSubTasksDone::clear() { 500 _n_tasks = _n_claimed = 0; 501 _n_threads = _n_completed = 0; 502 } 503 504 bool SequentialSubTasksDone::valid() { 505 return _n_threads > 0; 506 } 507 508 bool SequentialSubTasksDone::is_task_claimed(uint& t) { 509 uint* n_claimed_ptr = &_n_claimed; 510 t = *n_claimed_ptr; 511 while (t < _n_tasks) { 512 jint res = Atomic::cmpxchg(t+1, n_claimed_ptr, t); 513 if (res == (jint)t) { 514 return false; 515 } 516 t = *n_claimed_ptr; 517 } 518 return true; 519 } 520 521 bool SequentialSubTasksDone::all_tasks_completed() { 522 uint* n_completed_ptr = &_n_completed; 523 uint complete = *n_completed_ptr; 524 while (true) { 525 uint res = Atomic::cmpxchg(complete+1, n_completed_ptr, complete); 526 if (res == complete) { 527 break; 528 } 529 complete = res; 530 } 531 if (complete+1 == _n_threads) { 532 clear(); 533 return true; 534 } 535 return false; 536 } 537 538 bool FreeIdSet::_stat_init = false; 539 FreeIdSet* FreeIdSet::_sets[NSets]; 540 bool FreeIdSet::_safepoint; 541 542 FreeIdSet::FreeIdSet(int sz, Monitor* mon) : 543 _sz(sz), _mon(mon), _hd(0), _waiters(0), _index(-1), _claimed(0) 544 { 545 _ids = NEW_C_HEAP_ARRAY(int, sz, mtInternal); 546 for (int i = 0; i < sz; i++) _ids[i] = i+1; 547 _ids[sz-1] = end_of_list; // end of list. 548 if (_stat_init) { 549 for (int j = 0; j < NSets; j++) _sets[j] = NULL; 550 _stat_init = true; 551 } 552 // Add to sets. (This should happen while the system is still single-threaded.) 553 for (int j = 0; j < NSets; j++) { 554 if (_sets[j] == NULL) { 555 _sets[j] = this; 556 _index = j; 557 break; 558 } 559 } 560 guarantee(_index != -1, "Too many FreeIdSets in use!"); 561 } 562 563 FreeIdSet::~FreeIdSet() { 564 _sets[_index] = NULL; 565 FREE_C_HEAP_ARRAY(int, _ids); 566 } 567 568 void FreeIdSet::set_safepoint(bool b) { 569 _safepoint = b; 570 if (b) { 571 for (int j = 0; j < NSets; j++) { 572 if (_sets[j] != NULL && _sets[j]->_waiters > 0) { 573 Monitor* mon = _sets[j]->_mon; 574 mon->lock_without_safepoint_check(); 575 mon->notify_all(); 576 mon->unlock(); 577 } 578 } 579 } 580 } 581 582 #define FID_STATS 0 583 584 int FreeIdSet::claim_par_id() { 585 #if FID_STATS 586 thread_t tslf = thr_self(); 587 tty->print("claim_par_id[%d]: sz = %d, claimed = %d\n", tslf, _sz, _claimed); 588 #endif 589 MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag); 590 while (!_safepoint && _hd == end_of_list) { 591 _waiters++; 592 #if FID_STATS 593 if (_waiters > 5) { 594 tty->print("claim_par_id waiting[%d]: %d waiters, %d claimed.\n", 595 tslf, _waiters, _claimed); 596 } 597 #endif 598 _mon->wait(Mutex::_no_safepoint_check_flag); 599 _waiters--; 600 } 601 if (_hd == end_of_list) { 602 #if FID_STATS 603 tty->print("claim_par_id[%d]: returning EOL.\n", tslf); 604 #endif 605 return -1; 606 } else { 607 int res = _hd; 608 _hd = _ids[res]; 609 _ids[res] = claimed; // For debugging. 610 _claimed++; 611 #if FID_STATS 612 tty->print("claim_par_id[%d]: returning %d, claimed = %d.\n", 613 tslf, res, _claimed); 614 #endif 615 return res; 616 } 617 } 618 619 bool FreeIdSet::claim_perm_id(int i) { 620 assert(0 <= i && i < _sz, "Out of range."); 621 MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag); 622 int prev = end_of_list; 623 int cur = _hd; 624 while (cur != end_of_list) { 625 if (cur == i) { 626 if (prev == end_of_list) { 627 _hd = _ids[cur]; 628 } else { 629 _ids[prev] = _ids[cur]; 630 } 631 _ids[cur] = claimed; 632 _claimed++; 633 return true; 634 } else { 635 prev = cur; 636 cur = _ids[cur]; 637 } 638 } 639 return false; 640 641 } 642 643 void FreeIdSet::release_par_id(int id) { 644 MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag); 645 assert(_ids[id] == claimed, "Precondition."); 646 _ids[id] = _hd; 647 _hd = id; 648 _claimed--; 649 #if FID_STATS 650 tty->print("[%d] release_par_id(%d), waiters =%d, claimed = %d.\n", 651 thr_self(), id, _waiters, _claimed); 652 #endif 653 if (_waiters > 0) 654 // Notify all would be safer, but this is OK, right? 655 _mon->notify_all(); 656 }