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/workgroup.hpp"
  27 #include "memory/allocation.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "runtime/atomic.inline.hpp"
  30 #include "runtime/os.hpp"
  31 
  32 // Definitions of WorkGang methods.
  33 
  34 // The current implementation will exit if the allocation
  35 // of any worker fails.  Still, return a boolean so that
  36 // a future implementation can possibly do a partial
  37 // initialization of the workers and report such to the
  38 // caller.
  39 bool AbstractWorkGang::initialize_workers() {
  40 
  41   if (TraceWorkGang) {
  42     tty->print_cr("Constructing work gang %s with %d threads",
  43                   name(),
  44                   total_workers());
  45   }
  46   _workers = NEW_C_HEAP_ARRAY(AbstractGangWorker*, total_workers(), mtInternal);
  47   if (_workers == NULL) {
  48     vm_exit_out_of_memory(0, OOM_MALLOC_ERROR, "Cannot create GangWorker array.");
  49     return false;
  50   }
  51   os::ThreadType worker_type;
  52   if (are_ConcurrentGC_threads()) {
  53     worker_type = os::cgc_thread;
  54   } else {
  55     worker_type = os::pgc_thread;
  56   }
  57   for (uint worker = 0; worker < total_workers(); worker += 1) {
  58     AbstractGangWorker* new_worker = allocate_worker(worker);
  59     assert(new_worker != NULL, "Failed to allocate GangWorker");
  60     _workers[worker] = new_worker;
  61     if (new_worker == NULL || !os::create_thread(new_worker, worker_type)) {
  62       vm_exit_out_of_memory(0, OOM_MALLOC_ERROR,
  63               "Cannot create worker GC thread. Out of system resources.");
  64       return false;
  65     }
  66     if (!DisableStartThread) {
  67       os::start_thread(new_worker);
  68     }
  69   }
  70   return true;
  71 }
  72 
  73 AbstractGangWorker* AbstractWorkGang::worker(uint i) const {
  74   // Array index bounds checking.
  75   AbstractGangWorker* result = NULL;
  76   assert(_workers != NULL, "No workers for indexing");
  77   assert(i < total_workers(), "Worker index out of bounds");
  78   result = _workers[i];
  79   assert(result != NULL, "Indexing to null worker");
  80   return result;
  81 }
  82 
  83 void AbstractWorkGang::print_worker_threads_on(outputStream* st) const {
  84   uint workers = total_workers();
  85   for (uint i = 0; i < workers; i++) {
  86     worker(i)->print_on(st);
  87     st->cr();
  88   }
  89 }
  90 
  91 void AbstractWorkGang::threads_do(ThreadClosure* tc) const {
  92   assert(tc != NULL, "Null ThreadClosure");
  93   uint workers = total_workers();
  94   for (uint i = 0; i < workers; i++) {
  95     tc->do_thread(worker(i));
  96   }
  97 }
  98 
  99 WorkGang::WorkGang(const char* name,
 100                    uint        workers,
 101                    bool        are_GC_task_threads,
 102                    bool        are_ConcurrentGC_threads) :
 103     AbstractWorkGang(name, workers, are_GC_task_threads, are_ConcurrentGC_threads),
 104     _started_workers(0),
 105     _finished_workers(0),
 106     _sequence_number(0),
 107     _task(NULL) {
 108 
 109   // Other initialization.
 110   _monitor = new Monitor(/* priority */       Mutex::leaf,
 111                          /* name */           "WorkGroup monitor",
 112                          /* allow_vm_block */ are_GC_task_threads,
 113                                               Monitor::_safepoint_check_sometimes);
 114 
 115   assert(monitor() != NULL, "Failed to allocate monitor");
 116 }
 117 
 118 AbstractGangWorker* WorkGang::allocate_worker(uint worker_id) {
 119   return new GangWorker(this, worker_id);
 120 }
 121 
 122 void WorkGang::run_task(AbstractGangTask* task) {
 123   run_task(task, (uint)active_workers());
 124 }
 125 
 126 void WorkGang::run_task(AbstractGangTask* task, uint no_of_parallel_workers) {
 127   // This thread is executed by the VM thread which does not block
 128   // on ordinary MutexLocker's.
 129   MutexLockerEx ml(monitor(), Mutex::_no_safepoint_check_flag);
 130   if (TraceWorkGang) {
 131     tty->print_cr("Running work gang %s task %s", name(), task->name());
 132   }
 133   // Tell all the workers to run a task.
 134   assert(task != NULL, "Running a null task");
 135   // Initialize.
 136   _task = task;
 137   _sequence_number += 1;
 138   _started_workers = 0;
 139   _finished_workers = 0;
 140   // Tell the workers to get to work.
 141   monitor()->notify_all();
 142   // Wait for them to be finished
 143   while (finished_workers() < no_of_parallel_workers) {
 144     if (TraceWorkGang) {
 145       tty->print_cr("Waiting in work gang %s: %u/%u finished sequence %d",
 146                     name(), finished_workers(), no_of_parallel_workers,
 147                     _sequence_number);
 148     }
 149     monitor()->wait(/* no_safepoint_check */ true);
 150   }
 151   _task = NULL;
 152   if (TraceWorkGang) {
 153     tty->print_cr("\nFinished work gang %s: %u/%u sequence %d",
 154                   name(), finished_workers(), no_of_parallel_workers,
 155                   _sequence_number);
 156     Thread* me = Thread::current();
 157     tty->print_cr("  T: " PTR_FORMAT "  VM_thread: %d", p2i(me), me->is_VM_thread());
 158   }
 159 }
 160 
 161 void WorkGang::internal_worker_poll(WorkData* data) const {
 162   assert(monitor()->owned_by_self(), "worker_poll is an internal method");
 163   assert(data != NULL, "worker data is null");
 164   data->set_task(task());
 165   data->set_sequence_number(sequence_number());
 166 }
 167 
 168 void WorkGang::internal_note_start() {
 169   assert(monitor()->owned_by_self(), "note_finish is an internal method");
 170   _started_workers += 1;
 171 }
 172 
 173 void WorkGang::internal_note_finish() {
 174   assert(monitor()->owned_by_self(), "note_finish is an internal method");
 175   _finished_workers += 1;
 176 }
 177 
 178 // GangWorker methods.
 179 
 180 AbstractGangWorker::AbstractGangWorker(AbstractWorkGang* gang, uint id) {
 181   _gang = gang;
 182   set_id(id);
 183   set_name("%s#%d", gang->name(), id);
 184 }
 185 
 186 void AbstractGangWorker::run() {
 187   initialize();
 188   loop();
 189 }
 190 
 191 void AbstractGangWorker::initialize() {
 192   this->initialize_thread_local_storage();
 193   this->record_stack_base_and_size();
 194   this->initialize_named_thread();
 195   assert(_gang != NULL, "No gang to run in");
 196   os::set_priority(this, NearMaxPriority);
 197   if (TraceWorkGang) {
 198     tty->print_cr("Running gang worker for gang %s id %u",
 199                   gang()->name(), id());
 200   }
 201   // The VM thread should not execute here because MutexLocker's are used
 202   // as (opposed to MutexLockerEx's).
 203   assert(!Thread::current()->is_VM_thread(), "VM thread should not be part"
 204          " of a work gang");
 205 }
 206 
 207 bool AbstractGangWorker::is_GC_task_thread() const {
 208   return gang()->are_GC_task_threads();
 209 }
 210 
 211 bool AbstractGangWorker::is_ConcurrentGC_thread() const {
 212   return gang()->are_ConcurrentGC_threads();
 213 }
 214 
 215 void AbstractGangWorker::print_on(outputStream* st) const {
 216   st->print("\"%s\" ", name());
 217   Thread::print_on(st);
 218   st->cr();
 219 }
 220 
 221 void GangWorker::loop() {
 222   int previous_sequence_number = 0;
 223   Monitor* gang_monitor = gang()->monitor();
 224   for ( ; ; ) {
 225     WorkData data;
 226     int part;  // Initialized below.
 227     {
 228       // Grab the gang mutex.
 229       MutexLocker ml(gang_monitor);
 230       // Wait for something to do.
 231       // Polling outside the while { wait } avoids missed notifies
 232       // in the outer loop.
 233       gang()->internal_worker_poll(&data);
 234       if (TraceWorkGang) {
 235         tty->print("Polled outside for work in gang %s worker %u",
 236                    gang()->name(), id());
 237         tty->print("  sequence: %d (prev: %d)",
 238                    data.sequence_number(), previous_sequence_number);
 239         if (data.task() != NULL) {
 240           tty->print("  task: %s", data.task()->name());
 241         } else {
 242           tty->print("  task: NULL");
 243         }
 244         tty->cr();
 245       }
 246       for ( ; /* break */; ) {
 247         // Check for new work.
 248         if ((data.task() != NULL) &&
 249             (data.sequence_number() != previous_sequence_number)) {
 250           if (gang()->needs_more_workers()) {
 251             gang()->internal_note_start();
 252             gang_monitor->notify_all();
 253             part = gang()->started_workers() - 1;
 254             break;
 255           }
 256         }
 257         // Nothing to do.
 258         gang_monitor->wait(/* no_safepoint_check */ true);
 259         gang()->internal_worker_poll(&data);
 260         if (TraceWorkGang) {
 261           tty->print("Polled inside for work in gang %s worker %u",
 262                      gang()->name(), id());
 263           tty->print("  sequence: %d (prev: %d)",
 264                      data.sequence_number(), previous_sequence_number);
 265           if (data.task() != NULL) {
 266             tty->print("  task: %s", data.task()->name());
 267           } else {
 268             tty->print("  task: NULL");
 269           }
 270           tty->cr();
 271         }
 272       }
 273       // Drop gang mutex.
 274     }
 275     if (TraceWorkGang) {
 276       tty->print("Work for work gang %s id %u task %s part %d",
 277                  gang()->name(), id(), data.task()->name(), part);
 278     }
 279     assert(data.task() != NULL, "Got null task");
 280     data.task()->work(part);
 281     {
 282       if (TraceWorkGang) {
 283         tty->print("Finish for work gang %s id %u task %s part %d",
 284                    gang()->name(), id(), data.task()->name(), part);
 285       }
 286       // Grab the gang mutex.
 287       MutexLocker ml(gang_monitor);
 288       gang()->internal_note_finish();
 289       // Tell the gang you are done.
 290       gang_monitor->notify_all();
 291       // Drop the gang mutex.
 292     }
 293     previous_sequence_number = data.sequence_number();
 294   }
 295 }
 296 
 297 // *** WorkGangBarrierSync
 298 
 299 WorkGangBarrierSync::WorkGangBarrierSync()
 300   : _monitor(Mutex::safepoint, "work gang barrier sync", true,
 301              Monitor::_safepoint_check_never),
 302     _n_workers(0), _n_completed(0), _should_reset(false), _aborted(false) {
 303 }
 304 
 305 WorkGangBarrierSync::WorkGangBarrierSync(uint n_workers, const char* name)
 306   : _monitor(Mutex::safepoint, name, true, Monitor::_safepoint_check_never),
 307     _n_workers(n_workers), _n_completed(0), _should_reset(false), _aborted(false) {
 308 }
 309 
 310 void WorkGangBarrierSync::set_n_workers(uint n_workers) {
 311   _n_workers    = n_workers;
 312   _n_completed  = 0;
 313   _should_reset = false;
 314   _aborted      = false;
 315 }
 316 
 317 bool WorkGangBarrierSync::enter() {
 318   MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag);
 319   if (should_reset()) {
 320     // The should_reset() was set and we are the first worker to enter
 321     // the sync barrier. We will zero the n_completed() count which
 322     // effectively resets the barrier.
 323     zero_completed();
 324     set_should_reset(false);
 325   }
 326   inc_completed();
 327   if (n_completed() == n_workers()) {
 328     // At this point we would like to reset the barrier to be ready in
 329     // case it is used again. However, we cannot set n_completed() to
 330     // 0, even after the notify_all(), given that some other workers
 331     // might still be waiting for n_completed() to become ==
 332     // n_workers(). So, if we set n_completed() to 0, those workers
 333     // will get stuck (as they will wake up, see that n_completed() !=
 334     // n_workers() and go back to sleep). Instead, we raise the
 335     // should_reset() flag and the barrier will be reset the first
 336     // time a worker enters it again.
 337     set_should_reset(true);
 338     monitor()->notify_all();
 339   } else {
 340     while (n_completed() != n_workers() && !aborted()) {
 341       monitor()->wait(/* no_safepoint_check */ true);
 342     }
 343   }
 344   return !aborted();
 345 }
 346 
 347 void WorkGangBarrierSync::abort() {
 348   MutexLockerEx x(monitor(), Mutex::_no_safepoint_check_flag);
 349   set_aborted();
 350   monitor()->notify_all();
 351 }
 352 
 353 // SubTasksDone functions.
 354 
 355 SubTasksDone::SubTasksDone(uint n) :
 356   _n_tasks(n), _tasks(NULL) {
 357   _tasks = NEW_C_HEAP_ARRAY(uint, n, mtInternal);
 358   guarantee(_tasks != NULL, "alloc failure");
 359   clear();
 360 }
 361 
 362 bool SubTasksDone::valid() {
 363   return _tasks != NULL;
 364 }
 365 
 366 void SubTasksDone::clear() {
 367   for (uint i = 0; i < _n_tasks; i++) {
 368     _tasks[i] = 0;
 369   }
 370   _threads_completed = 0;
 371 #ifdef ASSERT
 372   _claimed = 0;
 373 #endif
 374 }
 375 
 376 bool SubTasksDone::is_task_claimed(uint t) {
 377   assert(t < _n_tasks, "bad task id.");
 378   uint old = _tasks[t];
 379   if (old == 0) {
 380     old = Atomic::cmpxchg(1, &_tasks[t], 0);
 381   }
 382   assert(_tasks[t] == 1, "What else?");
 383   bool res = old != 0;
 384 #ifdef ASSERT
 385   if (!res) {
 386     assert(_claimed < _n_tasks, "Too many tasks claimed; missing clear?");
 387     Atomic::inc((volatile jint*) &_claimed);
 388   }
 389 #endif
 390   return res;
 391 }
 392 
 393 void SubTasksDone::all_tasks_completed(uint n_threads) {
 394   jint observed = _threads_completed;
 395   jint old;
 396   do {
 397     old = observed;
 398     observed = Atomic::cmpxchg(old+1, &_threads_completed, old);
 399   } while (observed != old);
 400   // If this was the last thread checking in, clear the tasks.
 401   uint adjusted_thread_count = (n_threads == 0 ? 1 : n_threads);
 402   if (observed + 1 == (jint)adjusted_thread_count) {
 403     clear();
 404   }
 405 }
 406 
 407 
 408 SubTasksDone::~SubTasksDone() {
 409   if (_tasks != NULL) FREE_C_HEAP_ARRAY(jint, _tasks);
 410 }
 411 
 412 // *** SequentialSubTasksDone
 413 
 414 void SequentialSubTasksDone::clear() {
 415   _n_tasks   = _n_claimed   = 0;
 416   _n_threads = _n_completed = 0;
 417 }
 418 
 419 bool SequentialSubTasksDone::valid() {
 420   return _n_threads > 0;
 421 }
 422 
 423 bool SequentialSubTasksDone::is_task_claimed(uint& t) {
 424   uint* n_claimed_ptr = &_n_claimed;
 425   t = *n_claimed_ptr;
 426   while (t < _n_tasks) {
 427     jint res = Atomic::cmpxchg(t+1, n_claimed_ptr, t);
 428     if (res == (jint)t) {
 429       return false;
 430     }
 431     t = *n_claimed_ptr;
 432   }
 433   return true;
 434 }
 435 
 436 bool SequentialSubTasksDone::all_tasks_completed() {
 437   uint* n_completed_ptr = &_n_completed;
 438   uint  complete        = *n_completed_ptr;
 439   while (true) {
 440     uint res = Atomic::cmpxchg(complete+1, n_completed_ptr, complete);
 441     if (res == complete) {
 442       break;
 443     }
 444     complete = res;
 445   }
 446   if (complete+1 == _n_threads) {
 447     clear();
 448     return true;
 449   }
 450   return false;
 451 }
 452 
 453 bool FreeIdSet::_stat_init = false;
 454 FreeIdSet* FreeIdSet::_sets[NSets];
 455 bool FreeIdSet::_safepoint;
 456 
 457 FreeIdSet::FreeIdSet(int sz, Monitor* mon) :
 458   _sz(sz), _mon(mon), _hd(0), _waiters(0), _index(-1), _claimed(0)
 459 {
 460   _ids = NEW_C_HEAP_ARRAY(int, sz, mtInternal);
 461   for (int i = 0; i < sz; i++) _ids[i] = i+1;
 462   _ids[sz-1] = end_of_list; // end of list.
 463   if (_stat_init) {
 464     for (int j = 0; j < NSets; j++) _sets[j] = NULL;
 465     _stat_init = true;
 466   }
 467   // Add to sets.  (This should happen while the system is still single-threaded.)
 468   for (int j = 0; j < NSets; j++) {
 469     if (_sets[j] == NULL) {
 470       _sets[j] = this;
 471       _index = j;
 472       break;
 473     }
 474   }
 475   guarantee(_index != -1, "Too many FreeIdSets in use!");
 476 }
 477 
 478 FreeIdSet::~FreeIdSet() {
 479   _sets[_index] = NULL;
 480   FREE_C_HEAP_ARRAY(int, _ids);
 481 }
 482 
 483 void FreeIdSet::set_safepoint(bool b) {
 484   _safepoint = b;
 485   if (b) {
 486     for (int j = 0; j < NSets; j++) {
 487       if (_sets[j] != NULL && _sets[j]->_waiters > 0) {
 488         Monitor* mon = _sets[j]->_mon;
 489         mon->lock_without_safepoint_check();
 490         mon->notify_all();
 491         mon->unlock();
 492       }
 493     }
 494   }
 495 }
 496 
 497 #define FID_STATS 0
 498 
 499 int FreeIdSet::claim_par_id() {
 500 #if FID_STATS
 501   thread_t tslf = thr_self();
 502   tty->print("claim_par_id[%d]: sz = %d, claimed = %d\n", tslf, _sz, _claimed);
 503 #endif
 504   MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag);
 505   while (!_safepoint && _hd == end_of_list) {
 506     _waiters++;
 507 #if FID_STATS
 508     if (_waiters > 5) {
 509       tty->print("claim_par_id waiting[%d]: %d waiters, %d claimed.\n",
 510                  tslf, _waiters, _claimed);
 511     }
 512 #endif
 513     _mon->wait(Mutex::_no_safepoint_check_flag);
 514     _waiters--;
 515   }
 516   if (_hd == end_of_list) {
 517 #if FID_STATS
 518     tty->print("claim_par_id[%d]: returning EOL.\n", tslf);
 519 #endif
 520     return -1;
 521   } else {
 522     int res = _hd;
 523     _hd = _ids[res];
 524     _ids[res] = claimed;  // For debugging.
 525     _claimed++;
 526 #if FID_STATS
 527     tty->print("claim_par_id[%d]: returning %d, claimed = %d.\n",
 528                tslf, res, _claimed);
 529 #endif
 530     return res;
 531   }
 532 }
 533 
 534 bool FreeIdSet::claim_perm_id(int i) {
 535   assert(0 <= i && i < _sz, "Out of range.");
 536   MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag);
 537   int prev = end_of_list;
 538   int cur = _hd;
 539   while (cur != end_of_list) {
 540     if (cur == i) {
 541       if (prev == end_of_list) {
 542         _hd = _ids[cur];
 543       } else {
 544         _ids[prev] = _ids[cur];
 545       }
 546       _ids[cur] = claimed;
 547       _claimed++;
 548       return true;
 549     } else {
 550       prev = cur;
 551       cur = _ids[cur];
 552     }
 553   }
 554   return false;
 555 
 556 }
 557 
 558 void FreeIdSet::release_par_id(int id) {
 559   MutexLockerEx x(_mon, Mutex::_no_safepoint_check_flag);
 560   assert(_ids[id] == claimed, "Precondition.");
 561   _ids[id] = _hd;
 562   _hd = id;
 563   _claimed--;
 564 #if FID_STATS
 565   tty->print("[%d] release_par_id(%d), waiters =%d,  claimed = %d.\n",
 566              thr_self(), id, _waiters, _claimed);
 567 #endif
 568   if (_waiters > 0)
 569     // Notify all would be safer, but this is OK, right?
 570     _mon->notify_all();
 571 }