1 /* 2 * Copyright (c) 2001, 2015, 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/shared/workgroup.hpp" 27 #include "memory/allocation.hpp" 28 #include "memory/allocation.inline.hpp" 29 #include "runtime/atomic.inline.hpp" 30 #include "runtime/os.hpp" 31 #include "runtime/thread.inline.hpp" 32 #include "utilities/semaphore.hpp" 33 34 // Definitions of WorkGang methods. 35 36 // The current implementation will exit if the allocation 37 // of any worker fails. Still, return a boolean so that 38 // a future implementation can possibly do a partial 39 // initialization of the workers and report such to the 40 // caller. 41 bool AbstractWorkGang::initialize_workers() { 42 43 if (TraceWorkGang) { 44 tty->print_cr("Constructing work gang %s with %d threads", 45 name(), 46 total_workers()); 47 } 48 _workers = NEW_C_HEAP_ARRAY(AbstractGangWorker*, total_workers(), mtInternal); 49 if (_workers == NULL) { 50 vm_exit_out_of_memory(0, OOM_MALLOC_ERROR, "Cannot create GangWorker array."); 51 return false; 52 } 53 os::ThreadType worker_type; 54 if (are_ConcurrentGC_threads()) { 55 worker_type = os::cgc_thread; 56 } else { 57 worker_type = os::pgc_thread; 58 } 59 for (uint worker = 0; worker < total_workers(); worker += 1) { 60 AbstractGangWorker* new_worker = allocate_worker(worker); 61 assert(new_worker != NULL, "Failed to allocate GangWorker"); 62 _workers[worker] = new_worker; 63 if (new_worker == NULL || !os::create_thread(new_worker, worker_type)) { 64 vm_exit_out_of_memory(0, OOM_MALLOC_ERROR, 65 "Cannot create worker GC thread. Out of system resources."); 66 return false; 67 } 68 if (!DisableStartThread) { 69 os::start_thread(new_worker); 70 } 71 } 72 return true; 73 } 74 75 AbstractGangWorker* AbstractWorkGang::worker(uint i) const { 76 // Array index bounds checking. 77 AbstractGangWorker* result = NULL; 78 assert(_workers != NULL, "No workers for indexing"); 79 assert(i < total_workers(), "Worker index out of bounds"); 80 result = _workers[i]; 81 assert(result != NULL, "Indexing to null worker"); 82 return result; 83 } 84 85 void AbstractWorkGang::print_worker_threads_on(outputStream* st) const { 86 uint workers = total_workers(); 87 for (uint i = 0; i < workers; i++) { 88 worker(i)->print_on(st); 89 st->cr(); 90 } 91 } 92 93 void AbstractWorkGang::threads_do(ThreadClosure* tc) const { 94 assert(tc != NULL, "Null ThreadClosure"); 95 uint workers = total_workers(); 96 for (uint i = 0; i < workers; i++) { 97 tc->do_thread(worker(i)); 98 } 99 } 100 101 #if IMPLEMENTS_SEMAPHORE_CLASS 102 103 // WorkGang dispatcher implemented with semaphores. 104 // 105 // Semaphores don't require the worker threads to re-claim the lock when they wake up. 106 // This helps lowering the latency when starting and stopping the worker threads. 107 class SemaphoreGangTaskDispatcher : public GangTaskDispatcher { 108 // The task currently being dispatched to the GangWorkers. 109 AbstractGangTask* _task; 110 111 volatile uint _started; 112 volatile uint _not_finished; 113 114 // Semaphore used to start the GangWorkers. 115 Semaphore* _start_semaphore; 116 // Semaphore used to notify the coordinator that all workers are done. 117 Semaphore* _end_semaphore; 118 119 public: 120 SemaphoreGangTaskDispatcher(uint workers) : 121 _task(NULL), 122 _started(0), 123 _not_finished(0), 124 // Limit the semaphore value to the number of workers. 125 _start_semaphore(new Semaphore(0, workers)), 126 _end_semaphore(new Semaphore(0, workers)) 127 { } 128 129 ~SemaphoreGangTaskDispatcher() { 130 delete _start_semaphore; 131 delete _end_semaphore; 132 } 133 134 void coordinator_execute_on_workers(AbstractGangTask* task, uint num_workers) { 135 // No workers are allowed to read the state variables until they have been signaled. 136 _task = task; 137 _not_finished = num_workers; 138 139 // Dispatch 'num_workers' number of tasks. 140 _start_semaphore->signal(num_workers); 141 142 // Wait for the last worker to signal the coordinator. 143 _end_semaphore->wait(); 144 145 // No workers are allowed to read the state variables after the coordinator has been signaled. 146 _task = NULL; 147 _started = 0; 148 _not_finished = 0; 149 } 150 151 WorkData worker_wait_for_task() { 152 // Wait for the coordinator to dispatch a task. 153 _start_semaphore->wait(); 154 155 uint num_started = (uint) Atomic::add(1, (volatile jint*)&_started); 156 157 // Subtract one to get a zero-indexed worker id. 158 uint worker_id = num_started - 1; 159 160 return WorkData(_task, worker_id); 161 } 162 163 void worker_done_with_task() { 164 // Mark that the worker is done with the task. 165 // The worker is not allowed to read the state variables after this line. 166 uint not_finished = (uint) Atomic::add(-1, (volatile jint*)&_not_finished); 167 168 // The last worker signals to the coordinator that all work is completed. 169 if (not_finished == 0) { 170 _end_semaphore->signal(); 171 } 172 } 173 }; 174 #endif // IMPLEMENTS_SEMAPHORE_CLASS 175 176 class MutexGangTaskDispatcher : public GangTaskDispatcher { 177 AbstractGangTask* _task; 178 179 volatile uint _started; 180 volatile uint _finished; 181 volatile uint _num_workers; 182 183 Monitor* _monitor; 184 185 public: 186 MutexGangTaskDispatcher() 187 : _task(NULL), 188 _monitor(new Monitor(Monitor::leaf, "WorkGang dispatcher lock", false, Monitor::_safepoint_check_never)), 189 _started(0), 190 _finished(0), 191 _num_workers(0) {} 192 193 ~MutexGangTaskDispatcher() { 194 delete _monitor; 195 } 196 197 void coordinator_execute_on_workers(AbstractGangTask* task, uint num_workers) { 198 MutexLockerEx ml(_monitor, Mutex::_no_safepoint_check_flag); 199 200 _task = task; 201 _num_workers = num_workers; 202 203 // Tell the workers to get to work. 204 _monitor->notify_all(); 205 206 // Wait for them to finish. 207 while (_finished < _num_workers) { 208 _monitor->wait(/* no_safepoint_check */ true); 209 } 210 211 _task = NULL; 212 _num_workers = 0; 213 _started = 0; 214 _finished = 0; 215 } 216 217 WorkData worker_wait_for_task() { 218 MonitorLockerEx ml(_monitor, Mutex::_no_safepoint_check_flag); 219 220 while (_num_workers == 0 || _started == _num_workers) { 221 _monitor->wait(/* no_safepoint_check */ true); 222 } 223 224 _started++; 225 226 // Subtract one to get a zero-indexed worker id. 227 uint worker_id = _started - 1; 228 229 return WorkData(_task, worker_id); 230 } 231 232 void worker_done_with_task() { 233 MonitorLockerEx ml(_monitor, Mutex::_no_safepoint_check_flag); 234 235 _finished++; 236 237 if (_finished == _num_workers) { 238 // This will wake up all workers and not only the coordinator. 239 _monitor->notify_all(); 240 } 241 } 242 }; 243 244 static GangTaskDispatcher* create_dispatcher(uint workers) { 245 #if IMPLEMENTS_SEMAPHORE_CLASS 246 if (UseSemaphoreGCThreadsSynchronization) { 247 return new SemaphoreGangTaskDispatcher(workers); 248 } 249 #endif 250 251 return new MutexGangTaskDispatcher(); 252 } 253 254 WorkGang::WorkGang(const char* name, 255 uint workers, 256 bool are_GC_task_threads, 257 bool are_ConcurrentGC_threads, 258 GangTaskDispatcher* dispatcher) : 259 AbstractWorkGang(name, workers, are_GC_task_threads, are_ConcurrentGC_threads), 260 _dispatcher(dispatcher != NULL ? dispatcher: create_dispatcher(workers)) 261 { } 262 263 AbstractGangWorker* WorkGang::allocate_worker(uint worker_id) { 264 return new GangWorker(this, worker_id); 265 } 266 267 void WorkGang::run_task(AbstractGangTask* task) { 268 _dispatcher->coordinator_execute_on_workers(task, active_workers()); 269 } 270 271 AbstractGangWorker::AbstractGangWorker(AbstractWorkGang* gang, uint id) { 272 _gang = gang; 273 set_id(id); 274 set_name("%s#%d", gang->name(), id); 275 } 276 277 void AbstractGangWorker::run() { 278 initialize(); 279 loop(); 280 } 281 282 void AbstractGangWorker::initialize() { 283 this->initialize_thread_local_storage(); 284 this->record_stack_base_and_size(); 285 this->initialize_named_thread(); 286 assert(_gang != NULL, "No gang to run in"); 287 os::set_priority(this, NearMaxPriority); 288 if (TraceWorkGang) { 289 tty->print_cr("Running gang worker for gang %s id %u", 290 gang()->name(), id()); 291 } 292 // The VM thread should not execute here because MutexLocker's are used 293 // as (opposed to MutexLockerEx's). 294 assert(!Thread::current()->is_VM_thread(), "VM thread should not be part" 295 " of a work gang"); 296 } 297 298 bool AbstractGangWorker::is_GC_task_thread() const { 299 return gang()->are_GC_task_threads(); 300 } 301 302 bool AbstractGangWorker::is_ConcurrentGC_thread() const { 303 return gang()->are_ConcurrentGC_threads(); 304 } 305 306 void AbstractGangWorker::print_on(outputStream* st) const { 307 st->print("\"%s\" ", name()); 308 Thread::print_on(st); 309 st->cr(); 310 } 311 312 WorkData GangWorker::wait_for_task() { 313 return gang()->dispatcher()->worker_wait_for_task(); 314 } 315 316 void GangWorker::signal_task_done() { 317 gang()->dispatcher()->worker_done_with_task(); 318 } 319 320 void GangWorker::print_task_started(WorkData data) { 321 if (TraceWorkGang) { 322 tty->print_cr("Running work gang %s task %s worker %u", name(), data._task->name(), data._worker_id); 323 } 324 } 325 326 void GangWorker::print_task_done(WorkData data) { 327 if (TraceWorkGang) { 328 tty->print_cr("\nFinished work gang %s task %s worker %u", name(), data._task->name(), data._worker_id); 329 Thread* me = Thread::current(); 330 tty->print_cr(" T: " PTR_FORMAT " VM_thread: %d", p2i(me), me->is_VM_thread()); 331 } 332 } 333 334 void GangWorker::run_task(WorkData data) { 335 print_task_started(data); 336 337 data._task->work(data._worker_id); 338 339 print_task_done(data); 340 } 341 342 void GangWorker::loop() { 343 while (true) { 344 WorkData data = wait_for_task(); 345 346 run_task(data); 347 348 signal_task_done(); 349 } 350 } 351 352 // *** WorkGangBarrierSync 353 354 WorkGangBarrierSync::WorkGangBarrierSync() 355 : _monitor(Mutex::safepoint, "work gang barrier sync", true, 356 Monitor::_safepoint_check_never), 357 _n_workers(0), _n_completed(0), _should_reset(false), _aborted(false) { 358 } 359 360 WorkGangBarrierSync::WorkGangBarrierSync(uint n_workers, const char* name) 361 : _monitor(Mutex::safepoint, name, true, Monitor::_safepoint_check_never), 362 _n_workers(n_workers), _n_completed(0), _should_reset(false), _aborted(false) { 363 } 364 365 void WorkGangBarrierSync::set_n_workers(uint n_workers) { 366 _n_workers = n_workers; 367 _n_completed = 0; 368 _should_reset = false; 369 _aborted = false; 370 } 371 372 bool WorkGangBarrierSync::enter() { 373 MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag); 374 if (should_reset()) { 375 // The should_reset() was set and we are the first worker to enter 376 // the sync barrier. We will zero the n_completed() count which 377 // effectively resets the barrier. 378 zero_completed(); 379 set_should_reset(false); 380 } 381 inc_completed(); 382 if (n_completed() == n_workers()) { 383 // At this point we would like to reset the barrier to be ready in 384 // case it is used again. However, we cannot set n_completed() to 385 // 0, even after the notify_all(), given that some other workers 386 // might still be waiting for n_completed() to become == 387 // n_workers(). So, if we set n_completed() to 0, those workers 388 // will get stuck (as they will wake up, see that n_completed() != 389 // n_workers() and go back to sleep). Instead, we raise the 390 // should_reset() flag and the barrier will be reset the first 391 // time a worker enters it again. 392 set_should_reset(true); 393 monitor()->notify_all(); 394 } else { 395 while (n_completed() != n_workers() && !aborted()) { 396 monitor()->wait(/* no_safepoint_check */ true); 397 } 398 } 399 return !aborted(); 400 } 401 402 void WorkGangBarrierSync::abort() { 403 MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag); 404 set_aborted(); 405 monitor()->notify_all(); 406 } 407 408 // SubTasksDone functions. 409 410 SubTasksDone::SubTasksDone(uint n) : 411 _n_tasks(n), _tasks(NULL) { 412 _tasks = NEW_C_HEAP_ARRAY(uint, n, mtInternal); 413 guarantee(_tasks != NULL, "alloc failure"); 414 clear(); 415 } 416 417 bool SubTasksDone::valid() { 418 return _tasks != NULL; 419 } 420 421 void SubTasksDone::clear() { 422 for (uint i = 0; i < _n_tasks; i++) { 423 _tasks[i] = 0; 424 } 425 _threads_completed = 0; 426 #ifdef ASSERT 427 _claimed = 0; 428 #endif 429 } 430 431 bool SubTasksDone::is_task_claimed(uint t) { 432 assert(t < _n_tasks, "bad task id."); 433 uint old = _tasks[t]; 434 if (old == 0) { 435 old = Atomic::cmpxchg(1, &_tasks[t], 0); 436 } 437 assert(_tasks[t] == 1, "What else?"); 438 bool res = old != 0; 439 #ifdef ASSERT 440 if (!res) { 441 assert(_claimed < _n_tasks, "Too many tasks claimed; missing clear?"); 442 Atomic::inc((volatile jint*) &_claimed); 443 } 444 #endif 445 return res; 446 } 447 448 void SubTasksDone::all_tasks_completed(uint n_threads) { 449 jint observed = _threads_completed; 450 jint old; 451 do { 452 old = observed; 453 observed = Atomic::cmpxchg(old+1, &_threads_completed, old); 454 } while (observed != old); 455 // If this was the last thread checking in, clear the tasks. 456 uint adjusted_thread_count = (n_threads == 0 ? 1 : n_threads); 457 if (observed + 1 == (jint)adjusted_thread_count) { 458 clear(); 459 } 460 } 461 462 463 SubTasksDone::~SubTasksDone() { 464 if (_tasks != NULL) FREE_C_HEAP_ARRAY(jint, _tasks); 465 } 466 467 // *** SequentialSubTasksDone 468 469 void SequentialSubTasksDone::clear() { 470 _n_tasks = _n_claimed = 0; 471 _n_threads = _n_completed = 0; 472 } 473 474 bool SequentialSubTasksDone::valid() { 475 return _n_threads > 0; 476 } 477 478 bool SequentialSubTasksDone::is_task_claimed(uint& t) { 479 uint* n_claimed_ptr = &_n_claimed; 480 t = *n_claimed_ptr; 481 while (t < _n_tasks) { 482 jint res = Atomic::cmpxchg(t+1, n_claimed_ptr, t); 483 if (res == (jint)t) { 484 return false; 485 } 486 t = *n_claimed_ptr; 487 } 488 return true; 489 } 490 491 bool SequentialSubTasksDone::all_tasks_completed() { 492 uint* n_completed_ptr = &_n_completed; 493 uint complete = *n_completed_ptr; 494 while (true) { 495 uint res = Atomic::cmpxchg(complete+1, n_completed_ptr, complete); 496 if (res == complete) { 497 break; 498 } 499 complete = res; 500 } 501 if (complete+1 == _n_threads) { 502 clear(); 503 return true; 504 } 505 return false; 506 } 507 508 bool FreeIdSet::_stat_init = false; 509 FreeIdSet* FreeIdSet::_sets[NSets]; 510 bool FreeIdSet::_safepoint; 511 512 FreeIdSet::FreeIdSet(int sz, Monitor* mon) : 513 _sz(sz), _mon(mon), _hd(0), _waiters(0), _index(-1), _claimed(0) 514 { 515 _ids = NEW_C_HEAP_ARRAY(int, sz, mtInternal); 516 for (int i = 0; i < sz; i++) _ids[i] = i+1; 517 _ids[sz-1] = end_of_list; // end of list. 518 if (_stat_init) { 519 for (int j = 0; j < NSets; j++) _sets[j] = NULL; 520 _stat_init = true; 521 } 522 // Add to sets. (This should happen while the system is still single-threaded.) 523 for (int j = 0; j < NSets; j++) { 524 if (_sets[j] == NULL) { 525 _sets[j] = this; 526 _index = j; 527 break; 528 } 529 } 530 guarantee(_index != -1, "Too many FreeIdSets in use!"); 531 } 532 533 FreeIdSet::~FreeIdSet() { 534 _sets[_index] = NULL; 535 FREE_C_HEAP_ARRAY(int, _ids); 536 } 537 538 void FreeIdSet::set_safepoint(bool b) { 539 _safepoint = b; 540 if (b) { 541 for (int j = 0; j < NSets; j++) { 542 if (_sets[j] != NULL && _sets[j]->_waiters > 0) { 543 Monitor* mon = _sets[j]->_mon; 544 mon->lock_without_safepoint_check(); 545 mon->notify_all(); 546 mon->unlock(); 547 } 548 } 549 } 550 } 551 552 #define FID_STATS 0 553 554 int FreeIdSet::claim_par_id() { 555 #if FID_STATS 556 thread_t tslf = thr_self(); 557 tty->print("claim_par_id[%d]: sz = %d, claimed = %d\n", tslf, _sz, _claimed); 558 #endif 559 MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag); 560 while (!_safepoint && _hd == end_of_list) { 561 _waiters++; 562 #if FID_STATS 563 if (_waiters > 5) { 564 tty->print("claim_par_id waiting[%d]: %d waiters, %d claimed.\n", 565 tslf, _waiters, _claimed); 566 } 567 #endif 568 _mon->wait(Mutex::_no_safepoint_check_flag); 569 _waiters--; 570 } 571 if (_hd == end_of_list) { 572 #if FID_STATS 573 tty->print("claim_par_id[%d]: returning EOL.\n", tslf); 574 #endif 575 return -1; 576 } else { 577 int res = _hd; 578 _hd = _ids[res]; 579 _ids[res] = claimed; // For debugging. 580 _claimed++; 581 #if FID_STATS 582 tty->print("claim_par_id[%d]: returning %d, claimed = %d.\n", 583 tslf, res, _claimed); 584 #endif 585 return res; 586 } 587 } 588 589 bool FreeIdSet::claim_perm_id(int i) { 590 assert(0 <= i && i < _sz, "Out of range."); 591 MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag); 592 int prev = end_of_list; 593 int cur = _hd; 594 while (cur != end_of_list) { 595 if (cur == i) { 596 if (prev == end_of_list) { 597 _hd = _ids[cur]; 598 } else { 599 _ids[prev] = _ids[cur]; 600 } 601 _ids[cur] = claimed; 602 _claimed++; 603 return true; 604 } else { 605 prev = cur; 606 cur = _ids[cur]; 607 } 608 } 609 return false; 610 611 } 612 613 void FreeIdSet::release_par_id(int id) { 614 MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag); 615 assert(_ids[id] == claimed, "Precondition."); 616 _ids[id] = _hd; 617 _hd = id; 618 _claimed--; 619 #if FID_STATS 620 tty->print("[%d] release_par_id(%d), waiters =%d, claimed = %d.\n", 621 thr_self(), id, _waiters, _claimed); 622 #endif 623 if (_waiters > 0) 624 // Notify all would be safer, but this is OK, right? 625 _mon->notify_all(); 626 } 627 628 /////////////// Unit tests /////////////// 629 630 #ifndef PRODUCT 631 632 class CountTask : public AbstractGangTask { 633 volatile jint _count; 634 bool _sleep; 635 public: 636 CountTask(bool sleep) : AbstractGangTask("CountTask"), _sleep(sleep), _count(0) {} 637 virtual void work(uint worker_id) { 638 if (_sleep) { 639 // Sleep a while, to delay the task to allow the coordinator to run. 640 os::sleep(Thread::current(), 100, false); 641 } 642 643 // Count number of times executed. 644 Atomic::inc(&_count); 645 } 646 uint count() { return _count; } 647 }; 648 649 650 static void test_workgang_dispatch(bool use_semaphore, 651 uint total_workers, 652 uint active_workers, 653 bool sleep) { 654 655 GangTaskDispatcher* dispatcher = use_semaphore 656 ? (GangTaskDispatcher*) new SemGangTaskDispatcher(total_workers) 657 : (GangTaskDispatcher*) new MutexGangTaskDispatcher(); 658 659 // Intentionally leaking WorkGang, since there's no support to delete WorkGangs. 660 WorkGang* gang = new WorkGang("Test WorkGang", total_workers, false, false, dispatcher); 661 gang->initialize_workers(); 662 663 gang->set_active_workers(active_workers); 664 665 CountTask task(sleep); 666 667 gang->run_task(&task); 668 669 uint task_count = task.count(); 670 671 assert(task_count == active_workers, err_msg("Expected count: %u got: %u", active_workers, task_count)); 672 } 673 674 static void test_workgang_dispatch(bool use_semaphore) { 675 const bool sleep = true; 676 const uint total_workers = 8; 677 for (uint active_workers = 1; active_workers <= 4; active_workers++) { 678 test_workgang_dispatch(use_semaphore, total_workers, active_workers, sleep); 679 test_workgang_dispatch(use_semaphore, total_workers, active_workers, !sleep); 680 } 681 } 682 683 static void test_workgang_dispatch_mutex() { 684 test_workgang_dispatch(false); 685 } 686 687 static void test_workgang_dispatch_semaphore() { 688 test_workgang_dispatch(true); 689 } 690 691 void test_workgang() { 692 // Needed to use dynamic number of active workers. 693 FlagSetting fs(UseDynamicNumberOfGCThreads, true); 694 695 test_workgang_dispatch_semaphore(); 696 test_workgang_dispatch_mutex(); 697 } 698 699 #endif // PRODUCT