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