1 /*
   2  * Copyright (c) 2001, 2020, 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 "memory/iterator.hpp"
  32 #include "runtime/atomic.hpp"
  33 #include "runtime/os.hpp"
  34 #include "runtime/semaphore.hpp"
  35 #include "runtime/thread.inline.hpp"
  36 
  37 // Definitions of WorkGang methods.
  38 
  39 // The current implementation will exit if the allocation
  40 // of any worker fails.
  41 void  AbstractWorkGang::initialize_workers() {
  42   log_develop_trace(gc, workgang)("Constructing work gang %s with %u threads", name(), total_workers());
  43   _workers = NEW_C_HEAP_ARRAY(AbstractGangWorker*, total_workers(), mtInternal);
  44   add_workers(true);
  45 }
  46 
  47 
  48 AbstractGangWorker* AbstractWorkGang::install_worker(uint worker_id) {
  49   AbstractGangWorker* new_worker = allocate_worker(worker_id);
  50   set_thread(worker_id, new_worker);
  51   return new_worker;
  52 }
  53 
  54 void AbstractWorkGang::add_workers(bool initializing) {
  55   add_workers(_active_workers, initializing);
  56 }
  57 
  58 void AbstractWorkGang::add_workers(uint active_workers, bool initializing) {
  59 
  60   os::ThreadType worker_type;
  61   if (are_ConcurrentGC_threads()) {
  62     worker_type = os::cgc_thread;
  63   } else {
  64     worker_type = os::pgc_thread;
  65   }
  66   uint previous_created_workers = _created_workers;
  67 
  68   _created_workers = WorkerManager::add_workers(this,
  69                                                 active_workers,
  70                                                 _total_workers,
  71                                                 _created_workers,
  72                                                 worker_type,
  73                                                 initializing);
  74   _active_workers = MIN2(_created_workers, _active_workers);
  75 
  76   WorkerManager::log_worker_creation(this, previous_created_workers, _active_workers, _created_workers, initializing);
  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::threads_do(ThreadClosure* tc) const {
  90   assert(tc != NULL, "Null ThreadClosure");
  91   uint workers = created_workers();
  92   for (uint i = 0; i < workers; i++) {
  93     tc->do_thread(worker(i));
  94   }
  95 }
  96 
  97 static void run_foreground_task_if_needed(AbstractGangTask* task, uint num_workers,
  98                                           bool add_foreground_work) {
  99   if (add_foreground_work) {
 100     log_develop_trace(gc, workgang)("Running work gang: %s task: %s worker: foreground",
 101       Thread::current()->name(), task->name());
 102     task->work(num_workers);
 103     log_develop_trace(gc, workgang)("Finished work gang: %s task: %s worker: foreground "
 104       "thread: " PTR_FORMAT, Thread::current()->name(), task->name(), p2i(Thread::current()));
 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 GangTaskDispatcher : public CHeapObj<mtGC> {
 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   GangTaskDispatcher() :
 126       _task(NULL),
 127       _started(0),
 128       _not_finished(0),
 129       _start_semaphore(new Semaphore()),
 130       _end_semaphore(new Semaphore())
 131 { }
 132 
 133   ~GangTaskDispatcher() {
 134     delete _start_semaphore;
 135     delete _end_semaphore;
 136   }
 137 
 138   // Coordinator API.
 139 
 140   // Distributes the task out to num_workers workers.
 141   // Returns when the task has been completed by all workers.
 142   void coordinator_execute_on_workers(AbstractGangTask* task, uint num_workers, bool add_foreground_work) {
 143     // No workers are allowed to read the state variables until they have been signaled.
 144     _task         = task;
 145     _not_finished = num_workers;
 146 
 147     // Dispatch 'num_workers' number of tasks.
 148     _start_semaphore->signal(num_workers);
 149 
 150     run_foreground_task_if_needed(task, num_workers, add_foreground_work);
 151 
 152     // Wait for the last worker to signal the coordinator.
 153     _end_semaphore->wait();
 154 
 155     // No workers are allowed to read the state variables after the coordinator has been signaled.
 156     assert(_not_finished == 0, "%d not finished workers?", _not_finished);
 157     _task    = NULL;
 158     _started = 0;
 159 
 160   }
 161 
 162   // Worker API.
 163 
 164   // Waits for a task to become available to the worker.
 165   // Returns when the worker has been assigned a task.
 166   WorkData worker_wait_for_task() {
 167     // Wait for the coordinator to dispatch a task.
 168     _start_semaphore->wait();
 169 
 170     uint num_started = Atomic::add(&_started, 1u);
 171 
 172     // Subtract one to get a zero-indexed worker id.
 173     uint worker_id = num_started - 1;
 174 
 175     return WorkData(_task, worker_id);
 176   }
 177 
 178   // Signal to the coordinator that the worker is done with the assigned task.
 179   void worker_done_with_task() {
 180     // Mark that the worker is done with the task.
 181     // The worker is not allowed to read the state variables after this line.
 182     uint not_finished = Atomic::sub(&_not_finished, 1u);
 183 
 184     // The last worker signals to the coordinator that all work is completed.
 185     if (not_finished == 0) {
 186       _end_semaphore->signal();
 187     }
 188   }
 189 };
 190 
 191 WorkGang::WorkGang(const char* name,
 192                    uint  workers,
 193                    bool  are_GC_task_threads,
 194                    bool  are_ConcurrentGC_threads) :
 195     AbstractWorkGang(name, workers, are_GC_task_threads, are_ConcurrentGC_threads),
 196     _dispatcher(new GangTaskDispatcher())
 197 { }
 198 
 199 WorkGang::~WorkGang() {
 200   delete _dispatcher;
 201 }
 202 
 203 AbstractGangWorker* WorkGang::allocate_worker(uint worker_id) {
 204   return new GangWorker(this, worker_id);
 205 }
 206 
 207 void WorkGang::run_task(AbstractGangTask* task) {
 208   run_task(task, active_workers());
 209 }
 210 
 211 void WorkGang::run_task(AbstractGangTask* task, uint num_workers, bool add_foreground_work) {
 212   guarantee(num_workers <= total_workers(),
 213             "Trying to execute task %s with %u workers which is more than the amount of total workers %u.",
 214             task->name(), num_workers, total_workers());
 215   guarantee(num_workers > 0, "Trying to execute task %s with zero workers", task->name());
 216   uint old_num_workers = _active_workers;
 217   update_active_workers(num_workers);
 218   _dispatcher->coordinator_execute_on_workers(task, num_workers, add_foreground_work);
 219   update_active_workers(old_num_workers);
 220 }
 221 
 222 AbstractGangWorker::AbstractGangWorker(AbstractWorkGang* gang, uint id) {
 223   _gang = gang;
 224   set_id(id);
 225   set_name("%s#%d", gang->name(), id);
 226 }
 227 
 228 void AbstractGangWorker::run() {
 229   initialize();
 230   loop();
 231 }
 232 
 233 void AbstractGangWorker::initialize() {
 234   assert(_gang != NULL, "No gang to run in");
 235   os::set_priority(this, NearMaxPriority);
 236   log_develop_trace(gc, workgang)("Running gang worker for gang %s id %u", gang()->name(), id());
 237   assert(!Thread::current()->is_VM_thread(), "VM thread should not be part"
 238          " of a work gang");
 239 }
 240 
 241 bool AbstractGangWorker::is_GC_task_thread() const {
 242   return gang()->are_GC_task_threads();
 243 }
 244 
 245 bool AbstractGangWorker::is_ConcurrentGC_thread() const {
 246   return gang()->are_ConcurrentGC_threads();
 247 }
 248 
 249 void AbstractGangWorker::print_on(outputStream* st) const {
 250   st->print("\"%s\" ", name());
 251   Thread::print_on(st);
 252   st->cr();
 253 }
 254 
 255 void AbstractGangWorker::print() const { print_on(tty); }
 256 
 257 WorkData GangWorker::wait_for_task() {
 258   return gang()->dispatcher()->worker_wait_for_task();
 259 }
 260 
 261 void GangWorker::signal_task_done() {
 262   gang()->dispatcher()->worker_done_with_task();
 263 }
 264 
 265 void GangWorker::run_task(WorkData data) {
 266   GCIdMark gc_id_mark(data._task->gc_id());
 267   log_develop_trace(gc, workgang)("Running work gang: %s task: %s worker: %u", name(), data._task->name(), data._worker_id);
 268 
 269   data._task->work(data._worker_id);
 270 
 271   log_develop_trace(gc, workgang)("Finished work gang: %s task: %s worker: %u thread: " PTR_FORMAT,
 272                                   name(), data._task->name(), data._worker_id, p2i(Thread::current()));
 273 }
 274 
 275 void GangWorker::loop() {
 276   while (true) {
 277     WorkData data = wait_for_task();
 278 
 279     run_task(data);
 280 
 281     signal_task_done();
 282   }
 283 }
 284 
 285 // *** WorkGangBarrierSync
 286 
 287 WorkGangBarrierSync::WorkGangBarrierSync()
 288   : _monitor(Mutex::safepoint, "work gang barrier sync", true,
 289              Monitor::_safepoint_check_never),
 290     _n_workers(0), _n_completed(0), _should_reset(false), _aborted(false) {
 291 }
 292 
 293 WorkGangBarrierSync::WorkGangBarrierSync(uint n_workers, const char* name)
 294   : _monitor(Mutex::safepoint, name, true, Monitor::_safepoint_check_never),
 295     _n_workers(n_workers), _n_completed(0), _should_reset(false), _aborted(false) {
 296 }
 297 
 298 void WorkGangBarrierSync::set_n_workers(uint n_workers) {
 299   _n_workers    = n_workers;
 300   _n_completed  = 0;
 301   _should_reset = false;
 302   _aborted      = false;
 303 }
 304 
 305 bool WorkGangBarrierSync::enter() {
 306   MonitorLocker ml(monitor(), Mutex::_no_safepoint_check_flag);
 307   if (should_reset()) {
 308     // The should_reset() was set and we are the first worker to enter
 309     // the sync barrier. We will zero the n_completed() count which
 310     // effectively resets the barrier.
 311     zero_completed();
 312     set_should_reset(false);
 313   }
 314   inc_completed();
 315   if (n_completed() == n_workers()) {
 316     // At this point we would like to reset the barrier to be ready in
 317     // case it is used again. However, we cannot set n_completed() to
 318     // 0, even after the notify_all(), given that some other workers
 319     // might still be waiting for n_completed() to become ==
 320     // n_workers(). So, if we set n_completed() to 0, those workers
 321     // will get stuck (as they will wake up, see that n_completed() !=
 322     // n_workers() and go back to sleep). Instead, we raise the
 323     // should_reset() flag and the barrier will be reset the first
 324     // time a worker enters it again.
 325     set_should_reset(true);
 326     ml.notify_all();
 327   } else {
 328     while (n_completed() != n_workers() && !aborted()) {
 329       ml.wait();
 330     }
 331   }
 332   return !aborted();
 333 }
 334 
 335 void WorkGangBarrierSync::abort() {
 336   MutexLocker x(monitor(), Mutex::_no_safepoint_check_flag);
 337   set_aborted();
 338   monitor()->notify_all();
 339 }
 340 
 341 // SubTasksDone functions.
 342 
 343 SubTasksDone::SubTasksDone(uint n) :
 344   _tasks(NULL), _n_tasks(n), _threads_completed(0) {
 345   _tasks = NEW_C_HEAP_ARRAY(uint, n, mtInternal);
 346   clear();
 347 }
 348 
 349 bool SubTasksDone::valid() {
 350   return _tasks != NULL;
 351 }
 352 
 353 void SubTasksDone::clear() {
 354   for (uint i = 0; i < _n_tasks; i++) {
 355     _tasks[i] = 0;
 356   }
 357   _threads_completed = 0;
 358 #ifdef ASSERT
 359   _claimed = 0;
 360 #endif
 361 }
 362 
 363 bool SubTasksDone::try_claim_task(uint t) {
 364   assert(t < _n_tasks, "bad task id.");
 365   uint old = _tasks[t];
 366   if (old == 0) {
 367     old = Atomic::cmpxchg(&_tasks[t], 0u, 1u);
 368   }
 369   bool res = old == 0;
 370 #ifdef ASSERT
 371   if (res) {
 372     assert(_claimed < _n_tasks, "Too many tasks claimed; missing clear?");
 373     Atomic::inc(&_claimed);
 374   }
 375 #endif
 376   return res;
 377 }
 378 
 379 void SubTasksDone::all_tasks_completed(uint n_threads) {
 380   uint observed = _threads_completed;
 381   uint old;
 382   do {
 383     old = observed;
 384     observed = Atomic::cmpxchg(&_threads_completed, old, old+1);
 385   } while (observed != old);
 386   // If this was the last thread checking in, clear the tasks.
 387   uint adjusted_thread_count = (n_threads == 0 ? 1 : n_threads);
 388   if (observed + 1 == adjusted_thread_count) {
 389     clear();
 390   }
 391 }
 392 
 393 
 394 SubTasksDone::~SubTasksDone() {
 395   FREE_C_HEAP_ARRAY(uint, _tasks);
 396 }
 397 
 398 // *** SequentialSubTasksDone
 399 
 400 void SequentialSubTasksDone::clear() {
 401   _n_tasks   = _n_claimed   = 0;
 402   _n_threads = _n_completed = 0;
 403 }
 404 
 405 bool SequentialSubTasksDone::valid() {
 406   return _n_threads > 0;
 407 }
 408 
 409 bool SequentialSubTasksDone::try_claim_task(uint& t) {
 410   t = _n_claimed;
 411   while (t < _n_tasks) {
 412     uint res = Atomic::cmpxchg(&_n_claimed, t, t+1);
 413     if (res == t) {
 414       return true;
 415     }
 416     t = res;
 417   }
 418   return false;
 419 }
 420 
 421 bool SequentialSubTasksDone::all_tasks_completed() {
 422   uint complete = _n_completed;
 423   while (true) {
 424     uint res = Atomic::cmpxchg(&_n_completed, complete, complete+1);
 425     if (res == complete) {
 426       break;
 427     }
 428     complete = res;
 429   }
 430   if (complete+1 == _n_threads) {
 431     clear();
 432     return true;
 433   }
 434   return false;
 435 }