1 /*
   2  * Copyright (c) 2001, 2010, 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 "incls/_precompiled.incl"
  26 # include "incls/_taskqueue.cpp.incl"
  27 
  28 #ifdef TRACESPINNING
  29 uint ParallelTaskTerminator::_total_yields = 0;
  30 uint ParallelTaskTerminator::_total_spins = 0;
  31 uint ParallelTaskTerminator::_total_peeks = 0;
  32 #endif
  33 
  34 #if TASKQUEUE_STATS
  35 const char * const TaskQueueStats::_names[last_stat_id] = {
  36   "qpush", "qpop", "qpop-s", "qattempt", "qsteal", "opush", "omax"
  37 };
  38 
  39 TaskQueueStats & TaskQueueStats::operator +=(const TaskQueueStats & addend)
  40 {
  41   for (unsigned int i = 0; i < last_stat_id; ++i) {
  42     _stats[i] += addend._stats[i];
  43   }
  44   return *this;
  45 }
  46 
  47 void TaskQueueStats::print_header(unsigned int line, outputStream* const stream,
  48                                   unsigned int width)
  49 {
  50   // Use a width w: 1 <= w <= max_width
  51   const unsigned int max_width = 40;
  52   const unsigned int w = MAX2(MIN2(width, max_width), 1U);
  53 
  54   if (line == 0) { // spaces equal in width to the header
  55     const unsigned int hdr_width = w * last_stat_id + last_stat_id - 1;
  56     stream->print("%*s", hdr_width, " ");
  57   } else if (line == 1) { // labels
  58     stream->print("%*s", w, _names[0]);
  59     for (unsigned int i = 1; i < last_stat_id; ++i) {
  60       stream->print(" %*s", w, _names[i]);
  61     }
  62   } else if (line == 2) { // dashed lines
  63     char dashes[max_width + 1];
  64     memset(dashes, '-', w);
  65     dashes[w] = '\0';
  66     stream->print("%s", dashes);
  67     for (unsigned int i = 1; i < last_stat_id; ++i) {
  68       stream->print(" %s", dashes);
  69     }
  70   }
  71 }
  72 
  73 void TaskQueueStats::print(outputStream* stream, unsigned int width) const
  74 {
  75   #define FMT SIZE_FORMAT_W(*)
  76   stream->print(FMT, width, _stats[0]);
  77   for (unsigned int i = 1; i < last_stat_id; ++i) {
  78     stream->print(" " FMT, width, _stats[i]);
  79   }
  80   #undef FMT
  81 }
  82 
  83 #ifdef ASSERT
  84 // Invariants which should hold after a TaskQueue has been emptied and is
  85 // quiescent; they do not hold at arbitrary times.
  86 void TaskQueueStats::verify() const
  87 {
  88   assert(get(push) == get(pop) + get(steal),
  89          err_msg("push=" SIZE_FORMAT " pop=" SIZE_FORMAT " steal=" SIZE_FORMAT,
  90                  get(push), get(pop), get(steal)));
  91   assert(get(pop_slow) <= get(pop),
  92          err_msg("pop_slow=" SIZE_FORMAT " pop=" SIZE_FORMAT,
  93                  get(pop_slow), get(pop)));
  94   assert(get(steal) <= get(steal_attempt),
  95          err_msg("steal=" SIZE_FORMAT " steal_attempt=" SIZE_FORMAT,
  96                  get(steal), get(steal_attempt)));
  97   assert(get(overflow) == 0 || get(push) != 0,
  98          err_msg("overflow=" SIZE_FORMAT " push=" SIZE_FORMAT,
  99                  get(overflow), get(push)));
 100   assert(get(overflow_max_len) == 0 || get(overflow) != 0,
 101          err_msg("overflow_max_len=" SIZE_FORMAT " overflow=" SIZE_FORMAT,
 102                  get(overflow_max_len), get(overflow)));
 103 }
 104 #endif // ASSERT
 105 #endif // TASKQUEUE_STATS
 106 
 107 int TaskQueueSetSuper::randomParkAndMiller(int *seed0) {
 108   const int a =      16807;
 109   const int m = 2147483647;
 110   const int q =     127773;  /* m div a */
 111   const int r =       2836;  /* m mod a */
 112   assert(sizeof(int) == 4, "I think this relies on that");
 113   int seed = *seed0;
 114   int hi   = seed / q;
 115   int lo   = seed % q;
 116   int test = a * lo - r * hi;
 117   if (test > 0)
 118     seed = test;
 119   else
 120     seed = test + m;
 121   *seed0 = seed;
 122   return seed;
 123 }
 124 
 125 ParallelTaskTerminator::
 126 ParallelTaskTerminator(int n_threads, TaskQueueSetSuper* queue_set) :
 127   _n_threads(n_threads),
 128   _queue_set(queue_set),
 129   _offered_termination(0) {}
 130 
 131 bool ParallelTaskTerminator::peek_in_queue_set() {
 132   return _queue_set->peek();
 133 }
 134 
 135 void ParallelTaskTerminator::yield() {
 136   assert(_offered_termination <= _n_threads, "Invariant");
 137   os::yield();
 138 }
 139 
 140 void ParallelTaskTerminator::sleep(uint millis) {
 141   assert(_offered_termination <= _n_threads, "Invariant");
 142   os::sleep(Thread::current(), millis, false);
 143 }
 144 
 145 bool
 146 ParallelTaskTerminator::offer_termination(TerminatorTerminator* terminator) {
 147   assert(_n_threads > 0, "Initialization is incorrect");
 148   assert(_offered_termination < _n_threads, "Invariant");
 149   Atomic::inc(&_offered_termination);
 150 
 151   uint yield_count = 0;
 152   // Number of hard spin loops done since last yield
 153   uint hard_spin_count = 0;
 154   // Number of iterations in the hard spin loop.
 155   uint hard_spin_limit = WorkStealingHardSpins;
 156 
 157   // If WorkStealingSpinToYieldRatio is 0, no hard spinning is done.
 158   // If it is greater than 0, then start with a small number
 159   // of spins and increase number with each turn at spinning until
 160   // the count of hard spins exceeds WorkStealingSpinToYieldRatio.
 161   // Then do a yield() call and start spinning afresh.
 162   if (WorkStealingSpinToYieldRatio > 0) {
 163     hard_spin_limit = WorkStealingHardSpins >> WorkStealingSpinToYieldRatio;
 164     hard_spin_limit = MAX2(hard_spin_limit, 1U);
 165   }
 166   // Remember the initial spin limit.
 167   uint hard_spin_start = hard_spin_limit;
 168 
 169   // Loop waiting for all threads to offer termination or
 170   // more work.
 171   while (true) {
 172     assert(_offered_termination <= _n_threads, "Invariant");
 173     // Are all threads offering termination?
 174     if (_offered_termination == _n_threads) {
 175       return true;
 176     } else {
 177       // Look for more work.
 178       // Periodically sleep() instead of yield() to give threads
 179       // waiting on the cores the chance to grab this code
 180       if (yield_count <= WorkStealingYieldsBeforeSleep) {
 181         // Do a yield or hardspin.  For purposes of deciding whether
 182         // to sleep, count this as a yield.
 183         yield_count++;
 184 
 185         // Periodically call yield() instead spinning
 186         // After WorkStealingSpinToYieldRatio spins, do a yield() call
 187         // and reset the counts and starting limit.
 188         if (hard_spin_count > WorkStealingSpinToYieldRatio) {
 189           yield();
 190           hard_spin_count = 0;
 191           hard_spin_limit = hard_spin_start;
 192 #ifdef TRACESPINNING
 193           _total_yields++;
 194 #endif
 195         } else {
 196           // Hard spin this time
 197           // Increase the hard spinning period but only up to a limit.
 198           hard_spin_limit = MIN2(2*hard_spin_limit,
 199                                  (uint) WorkStealingHardSpins);
 200           for (uint j = 0; j < hard_spin_limit; j++) {
 201             SpinPause();
 202           }
 203           hard_spin_count++;
 204 #ifdef TRACESPINNING
 205           _total_spins++;
 206 #endif
 207         }
 208       } else {
 209         if (PrintGCDetails && Verbose) {
 210          gclog_or_tty->print_cr("ParallelTaskTerminator::offer_termination() "
 211            "thread %d sleeps after %d yields",
 212            Thread::current(), yield_count);
 213         }
 214         yield_count = 0;
 215         // A sleep will cause this processor to seek work on another processor's
 216         // runqueue, if it has nothing else to run (as opposed to the yield
 217         // which may only move the thread to the end of the this processor's
 218         // runqueue).
 219         sleep(WorkStealingSleepMillis);
 220       }
 221 
 222 #ifdef TRACESPINNING
 223       _total_peeks++;
 224 #endif
 225       if (peek_in_queue_set() ||
 226           (terminator != NULL && terminator->should_exit_termination())) {
 227         Atomic::dec(&_offered_termination);
 228         assert(_offered_termination < _n_threads, "Invariant");
 229         return false;
 230       }
 231     }
 232   }
 233 }
 234 
 235 #ifdef TRACESPINNING
 236 void ParallelTaskTerminator::print_termination_counts() {
 237   gclog_or_tty->print_cr("ParallelTaskTerminator Total yields: %lld  "
 238     "Total spins: %lld  Total peeks: %lld",
 239     total_yields(),
 240     total_spins(),
 241     total_peeks());
 242 }
 243 #endif
 244 
 245 void ParallelTaskTerminator::reset_for_reuse() {
 246   if (_offered_termination != 0) {
 247     assert(_offered_termination == _n_threads,
 248            "Terminator may still be in use");
 249     _offered_termination = 0;
 250   }
 251 }
 252 
 253 #ifdef ASSERT
 254 bool ObjArrayTask::is_valid() const {
 255   return _obj != NULL && _obj->is_objArray() && _index > 0 &&
 256     _index < objArrayOop(_obj)->length();
 257 }
 258 #endif // ASSERT
 259 
 260 void ParallelTaskTerminator::reset_for_reuse(int n_threads) {
 261   reset_for_reuse();
 262   _n_threads = n_threads;
 263 }
 264