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