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