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