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