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