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