1 /*
   2  * Copyright (c) 2001, 2016, 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/gcId.hpp"
  27 #include "gc/shared/workgroup.hpp"
  28 #include "gc/shared/workerManager.hpp"
  29 #include "memory/allocation.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "runtime/atomic.inline.hpp"
  32 #include "runtime/os.hpp"
  33 #include "runtime/semaphore.hpp"
  34 #include "runtime/thread.inline.hpp"
  35 
  36 // Definitions of WorkGang methods.
  37 
  38 // The current implementation will exit if the allocation
  39 // of any worker fails.
  40 void  AbstractWorkGang::initialize_workers() {
  41   log_develop_trace(gc, workgang)("Constructing work gang %s with %u threads", name(), total_workers());
  42   _workers = NEW_C_HEAP_ARRAY(AbstractGangWorker*, total_workers(), mtInternal);
  43   if (_workers == NULL) {
  44     vm_exit_out_of_memory(0, OOM_MALLOC_ERROR, "Cannot create GangWorker array.");
  45   }
  46 
  47   add_workers(true);
  48 }
  49 
  50 
  51 AbstractGangWorker* AbstractWorkGang::install_worker(uint worker_id) {
  52   AbstractGangWorker* new_worker = allocate_worker(worker_id);
  53   set_thread(worker_id, new_worker);
  54   return new_worker;
  55 }
  56 
  57 void AbstractWorkGang::add_workers(bool initializing) {
  58   add_workers(_active_workers, initializing);
  59 }
  60 
  61 void AbstractWorkGang::add_workers(uint active_workers, bool initializing) {
  62 
  63   os::ThreadType worker_type;
  64   if (are_ConcurrentGC_threads()) {
  65     worker_type = os::cgc_thread;
  66   } else {
  67     worker_type = os::pgc_thread;
  68   }
  69   uint previous_created_workers = _created_workers;
  70 
  71   _created_workers = WorkerManager::add_workers(this,
  72                                                 active_workers,
  73                                                 _total_workers,
  74                                                 _created_workers,
  75                                                 worker_type,
  76                                                 initializing);
  77   _active_workers = MIN2(_created_workers, _active_workers);
  78 
  79   WorkerManager::log_worker_creation(this, previous_created_workers, _active_workers, _created_workers, initializing);
  80 }
  81 
  82 char* AbstractWorkGang::worker_name(uint which) {
  83   if (worker(which) != NULL) {
  84     return worker(which)->name();
  85   } else {
  86     return NULL;
  87   }
  88 }
  89 
  90 AbstractGangWorker* AbstractWorkGang::worker(uint i) const {
  91   // Array index bounds checking.
  92   AbstractGangWorker* result = NULL;
  93   assert(_workers != NULL, "No workers for indexing");
  94   assert(i < total_workers(), "Worker index out of bounds");
  95   result = _workers[i];
  96   assert(result != NULL, "Indexing to null worker");
  97   return result;
  98 }
  99 
 100 void AbstractWorkGang::print_worker_threads_on(outputStream* st) const {
 101   uint workers = created_workers();
 102   for (uint i = 0; i < workers; i++) {
 103     worker(i)->print_on(st);
 104     st->cr();
 105   }
 106 }
 107 
 108 void AbstractWorkGang::threads_do(ThreadClosure* tc) const {
 109   assert(tc != NULL, "Null ThreadClosure");
 110   uint workers = created_workers();
 111   for (uint i = 0; i < workers; i++) {
 112     tc->do_thread(worker(i));
 113   }
 114 }
 115 
 116 // WorkGang dispatcher implemented with semaphores.
 117 //
 118 // Semaphores don't require the worker threads to re-claim the lock when they wake up.
 119 // This helps lowering the latency when starting and stopping the worker threads.
 120 class SemaphoreGangTaskDispatcher : public GangTaskDispatcher {
 121   // The task currently being dispatched to the GangWorkers.
 122   AbstractGangTask* _task;
 123 
 124   volatile uint _started;
 125   volatile uint _not_finished;
 126 
 127   // Semaphore used to start the GangWorkers.
 128   Semaphore* _start_semaphore;
 129   // Semaphore used to notify the coordinator that all workers are done.
 130   Semaphore* _end_semaphore;
 131 
 132 public:
 133   SemaphoreGangTaskDispatcher() :
 134       _task(NULL),
 135       _started(0),
 136       _not_finished(0),
 137       _start_semaphore(new Semaphore()),
 138       _end_semaphore(new Semaphore())
 139 { }
 140 
 141   ~SemaphoreGangTaskDispatcher() {
 142     delete _start_semaphore;
 143     delete _end_semaphore;
 144   }
 145 
 146   void coordinator_execute_on_workers(AbstractGangTask* task, uint num_workers) {
 147     // No workers are allowed to read the state variables until they have been signaled.
 148     _task         = task;
 149     _not_finished = num_workers;
 150 
 151     // Dispatch 'num_workers' number of tasks.
 152     _start_semaphore->signal(num_workers);
 153 
 154     // Wait for the last worker to signal the coordinator.
 155     _end_semaphore->wait();
 156 
 157     // No workers are allowed to read the state variables after the coordinator has been signaled.
 158     assert(_not_finished == 0, "%d not finished workers?", _not_finished);
 159     _task    = NULL;
 160     _started = 0;
 161 
 162   }
 163 
 164   WorkData worker_wait_for_task() {
 165     // Wait for the coordinator to dispatch a task.
 166     _start_semaphore->wait();
 167 
 168     uint num_started = (uint) Atomic::add(1, (volatile jint*)&_started);
 169 
 170     // Subtract one to get a zero-indexed worker id.
 171     uint worker_id = num_started - 1;
 172 
 173     return WorkData(_task, worker_id);
 174   }
 175 
 176   void worker_done_with_task() {
 177     // Mark that the worker is done with the task.
 178     // The worker is not allowed to read the state variables after this line.
 179     uint not_finished = (uint) Atomic::add(-1, (volatile jint*)&_not_finished);
 180 
 181     // The last worker signals to the coordinator that all work is completed.
 182     if (not_finished == 0) {
 183       _end_semaphore->signal();
 184     }
 185   }
 186 };
 187 
 188 class MutexGangTaskDispatcher : public GangTaskDispatcher {
 189   AbstractGangTask* _task;
 190 
 191   volatile uint _started;
 192   volatile uint _finished;
 193   volatile uint _num_workers;
 194 
 195   Monitor* _monitor;
 196 
 197  public:
 198   MutexGangTaskDispatcher()
 199       : _task(NULL),
 200         _monitor(new Monitor(Monitor::leaf, "WorkGang dispatcher lock", false, Monitor::_safepoint_check_never)),
 201         _started(0),
 202         _finished(0),
 203         _num_workers(0) {}
 204 
 205   ~MutexGangTaskDispatcher() {
 206     delete _monitor;
 207   }
 208 
 209   void coordinator_execute_on_workers(AbstractGangTask* task, uint num_workers) {
 210     MutexLockerEx ml(_monitor, Mutex::_no_safepoint_check_flag);
 211 
 212     _task        = task;
 213     _num_workers = num_workers;
 214 
 215     // Tell the workers to get to work.
 216     _monitor->notify_all();
 217 
 218     // Wait for them to finish.
 219     while (_finished < _num_workers) {
 220       _monitor->wait(/* no_safepoint_check */ true);
 221     }
 222 
 223     _task        = NULL;
 224     _num_workers = 0;
 225     _started     = 0;
 226     _finished    = 0;
 227   }
 228 
 229   WorkData worker_wait_for_task() {
 230     MonitorLockerEx ml(_monitor, Mutex::_no_safepoint_check_flag);
 231 
 232     while (_num_workers == 0 || _started == _num_workers) {
 233       _monitor->wait(/* no_safepoint_check */ true);
 234     }
 235 
 236     _started++;
 237 
 238     // Subtract one to get a zero-indexed worker id.
 239     uint worker_id = _started - 1;
 240 
 241     return WorkData(_task, worker_id);
 242   }
 243 
 244   void worker_done_with_task() {
 245     MonitorLockerEx ml(_monitor, Mutex::_no_safepoint_check_flag);
 246 
 247     _finished++;
 248 
 249     if (_finished == _num_workers) {
 250       // This will wake up all workers and not only the coordinator.
 251       _monitor->notify_all();
 252     }
 253   }
 254 };
 255 
 256 static GangTaskDispatcher* create_dispatcher() {
 257   if (UseSemaphoreGCThreadsSynchronization) {
 258     return new SemaphoreGangTaskDispatcher();
 259   }
 260 
 261   return new MutexGangTaskDispatcher();
 262 }
 263 
 264 WorkGang::WorkGang(const char* name,
 265                    uint  workers,
 266                    bool  are_GC_task_threads,
 267                    bool  are_ConcurrentGC_threads) :
 268     AbstractWorkGang(name, workers, are_GC_task_threads, are_ConcurrentGC_threads),
 269     _dispatcher(create_dispatcher())
 270 { }
 271 
 272 AbstractGangWorker* WorkGang::allocate_worker(uint worker_id) {
 273   return new GangWorker(this, worker_id);
 274 }
 275 
 276 void WorkGang::run_task(AbstractGangTask* task) {
 277   run_task(task, active_workers());
 278 }
 279 
 280 void WorkGang::run_task(AbstractGangTask* task, uint num_workers) {
 281   guarantee(num_workers <= total_workers(),
 282             "Trying to execute task %s with %u workers which is more than the amount of total workers %u.",
 283             task->name(), num_workers, total_workers());
 284   guarantee(num_workers > 0, "Trying to execute task %s with zero workers", task->name());
 285   add_workers(num_workers, false);
 286   _dispatcher->coordinator_execute_on_workers(task, num_workers);
 287 }
 288 
 289 AbstractGangWorker::AbstractGangWorker(AbstractWorkGang* gang, uint id) {
 290   _gang = gang;
 291   set_id(id);
 292   set_name("%s#%d", gang->name(), id);
 293 }
 294 
 295 void AbstractGangWorker::run() {
 296   initialize();
 297   loop();
 298 }
 299 
 300 void AbstractGangWorker::initialize() {
 301   this->record_stack_base_and_size();
 302   this->initialize_named_thread();
 303   assert(_gang != NULL, "No gang to run in");
 304   os::set_priority(this, NearMaxPriority);
 305   log_develop_trace(gc, workgang)("Running gang worker for gang %s id %u", gang()->name(), id());
 306   // The VM thread should not execute here because MutexLocker's are used
 307   // as (opposed to MutexLockerEx's).
 308   assert(!Thread::current()->is_VM_thread(), "VM thread should not be part"
 309          " of a work gang");
 310 }
 311 
 312 bool AbstractGangWorker::is_GC_task_thread() const {
 313   return gang()->are_GC_task_threads();
 314 }
 315 
 316 bool AbstractGangWorker::is_ConcurrentGC_thread() const {
 317   return gang()->are_ConcurrentGC_threads();
 318 }
 319 
 320 void AbstractGangWorker::print_on(outputStream* st) const {
 321   st->print("\"%s\" ", name());
 322   Thread::print_on(st);
 323   st->cr();
 324 }
 325 
 326 WorkData GangWorker::wait_for_task() {
 327   return gang()->dispatcher()->worker_wait_for_task();
 328 }
 329 
 330 void GangWorker::signal_task_done() {
 331   gang()->dispatcher()->worker_done_with_task();
 332 }
 333 
 334 void GangWorker::run_task(WorkData data) {
 335   GCIdMark gc_id_mark(data._task->gc_id());
 336   log_develop_trace(gc, workgang)("Running work gang: %s task: %s worker: %u", name(), data._task->name(), data._worker_id);
 337 
 338   data._task->work(data._worker_id);
 339 
 340   log_develop_trace(gc, workgang)("Finished work gang: %s task: %s worker: %u thread: " PTR_FORMAT,
 341                                   name(), data._task->name(), data._worker_id, p2i(Thread::current()));
 342 }
 343 
 344 void GangWorker::loop() {
 345   while (true) {
 346     WorkData data = wait_for_task();
 347 
 348     run_task(data);
 349 
 350     signal_task_done();
 351   }
 352 }
 353 
 354 // *** WorkGangBarrierSync
 355 
 356 WorkGangBarrierSync::WorkGangBarrierSync()
 357   : _monitor(Mutex::safepoint, "work gang barrier sync", true,
 358              Monitor::_safepoint_check_never),
 359     _n_workers(0), _n_completed(0), _should_reset(false), _aborted(false) {
 360 }
 361 
 362 WorkGangBarrierSync::WorkGangBarrierSync(uint n_workers, const char* name)
 363   : _monitor(Mutex::safepoint, name, true, Monitor::_safepoint_check_never),
 364     _n_workers(n_workers), _n_completed(0), _should_reset(false), _aborted(false) {
 365 }
 366 
 367 void WorkGangBarrierSync::set_n_workers(uint n_workers) {
 368   _n_workers    = n_workers;
 369   _n_completed  = 0;
 370   _should_reset = false;
 371   _aborted      = false;
 372 }
 373 
 374 bool WorkGangBarrierSync::enter() {
 375   MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag);
 376   if (should_reset()) {
 377     // The should_reset() was set and we are the first worker to enter
 378     // the sync barrier. We will zero the n_completed() count which
 379     // effectively resets the barrier.
 380     zero_completed();
 381     set_should_reset(false);
 382   }
 383   inc_completed();
 384   if (n_completed() == n_workers()) {
 385     // At this point we would like to reset the barrier to be ready in
 386     // case it is used again. However, we cannot set n_completed() to
 387     // 0, even after the notify_all(), given that some other workers
 388     // might still be waiting for n_completed() to become ==
 389     // n_workers(). So, if we set n_completed() to 0, those workers
 390     // will get stuck (as they will wake up, see that n_completed() !=
 391     // n_workers() and go back to sleep). Instead, we raise the
 392     // should_reset() flag and the barrier will be reset the first
 393     // time a worker enters it again.
 394     set_should_reset(true);
 395     monitor()->notify_all();
 396   } else {
 397     while (n_completed() != n_workers() && !aborted()) {
 398       monitor()->wait(/* no_safepoint_check */ true);
 399     }
 400   }
 401   return !aborted();
 402 }
 403 
 404 void WorkGangBarrierSync::abort() {
 405   MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag);
 406   set_aborted();
 407   monitor()->notify_all();
 408 }
 409 
 410 // SubTasksDone functions.
 411 
 412 SubTasksDone::SubTasksDone(uint n) :
 413   _n_tasks(n), _tasks(NULL) {
 414   _tasks = NEW_C_HEAP_ARRAY(uint, n, mtInternal);
 415   guarantee(_tasks != NULL, "alloc failure");
 416   clear();
 417 }
 418 
 419 bool SubTasksDone::valid() {
 420   return _tasks != NULL;
 421 }
 422 
 423 void SubTasksDone::clear() {
 424   for (uint i = 0; i < _n_tasks; i++) {
 425     _tasks[i] = 0;
 426   }
 427   _threads_completed = 0;
 428 #ifdef ASSERT
 429   _claimed = 0;
 430 #endif
 431 }
 432 
 433 bool SubTasksDone::is_task_claimed(uint t) {
 434   assert(t < _n_tasks, "bad task id.");
 435   uint old = _tasks[t];
 436   if (old == 0) {
 437     old = Atomic::cmpxchg(1, &_tasks[t], 0);
 438   }
 439   assert(_tasks[t] == 1, "What else?");
 440   bool res = old != 0;
 441 #ifdef ASSERT
 442   if (!res) {
 443     assert(_claimed < _n_tasks, "Too many tasks claimed; missing clear?");
 444     Atomic::inc((volatile jint*) &_claimed);
 445   }
 446 #endif
 447   return res;
 448 }
 449 
 450 void SubTasksDone::all_tasks_completed(uint n_threads) {
 451   jint observed = _threads_completed;
 452   jint old;
 453   do {
 454     old = observed;
 455     observed = Atomic::cmpxchg(old+1, &_threads_completed, old);
 456   } while (observed != old);
 457   // If this was the last thread checking in, clear the tasks.
 458   uint adjusted_thread_count = (n_threads == 0 ? 1 : n_threads);
 459   if (observed + 1 == (jint)adjusted_thread_count) {
 460     clear();
 461   }
 462 }
 463 
 464 
 465 SubTasksDone::~SubTasksDone() {
 466   if (_tasks != NULL) FREE_C_HEAP_ARRAY(jint, _tasks);
 467 }
 468 
 469 // *** SequentialSubTasksDone
 470 
 471 void SequentialSubTasksDone::clear() {
 472   _n_tasks   = _n_claimed   = 0;
 473   _n_threads = _n_completed = 0;
 474 }
 475 
 476 bool SequentialSubTasksDone::valid() {
 477   return _n_threads > 0;
 478 }
 479 
 480 bool SequentialSubTasksDone::is_task_claimed(uint& t) {
 481   uint* n_claimed_ptr = &_n_claimed;
 482   t = *n_claimed_ptr;
 483   while (t < _n_tasks) {
 484     jint res = Atomic::cmpxchg(t+1, n_claimed_ptr, t);
 485     if (res == (jint)t) {
 486       return false;
 487     }
 488     t = *n_claimed_ptr;
 489   }
 490   return true;
 491 }
 492 
 493 bool SequentialSubTasksDone::all_tasks_completed() {
 494   uint* n_completed_ptr = &_n_completed;
 495   uint  complete        = *n_completed_ptr;
 496   while (true) {
 497     uint res = Atomic::cmpxchg(complete+1, n_completed_ptr, complete);
 498     if (res == complete) {
 499       break;
 500     }
 501     complete = res;
 502   }
 503   if (complete+1 == _n_threads) {
 504     clear();
 505     return true;
 506   }
 507   return false;
 508 }