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