1 /*
   2  * Copyright (c) 2002, 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 #ifndef SHARE_VM_UTILITIES_WORKGROUP_HPP
  26 #define SHARE_VM_UTILITIES_WORKGROUP_HPP
  27 
  28 #include "utilities/taskqueue.hpp"
  29 #ifdef TARGET_OS_FAMILY_linux
  30 # include "thread_linux.inline.hpp"
  31 #endif
  32 #ifdef TARGET_OS_FAMILY_solaris
  33 # include "thread_solaris.inline.hpp"
  34 #endif
  35 #ifdef TARGET_OS_FAMILY_windows
  36 # include "thread_windows.inline.hpp"
  37 #endif
  38 
  39 // Forward declarations of classes defined here
  40 
  41 class WorkGang;
  42 class GangWorker;
  43 class YieldingFlexibleGangWorker;
  44 class YieldingFlexibleGangTask;
  45 class WorkData;
  46 class AbstractWorkGang;
  47 
  48 // An abstract task to be worked on by a gang.
  49 // You subclass this to supply your own work() method
  50 class AbstractGangTask VALUE_OBJ_CLASS_SPEC {
  51 public:
  52   // The abstract work method.
  53   // The argument tells you which member of the gang you are.
  54   virtual void work(int i) = 0;
  55 
  56   // This method configures the task for proper termination.
  57   // Some tasks do not have any requirements on termination
  58   // and may inherit this method that does nothing.  Some
  59   // tasks do some coordination on termination and override
  60   // this method to implement that coordination.
  61   virtual void set_for_termination(int active_workers) {};
  62 
  63   // Debugging accessor for the name.
  64   const char* name() const PRODUCT_RETURN_(return NULL;);
  65   int counter() { return _counter; }
  66   void set_counter(int value) { _counter = value; }
  67   int *address_of_counter() { return &_counter; }
  68 
  69   // RTTI
  70   NOT_PRODUCT(virtual bool is_YieldingFlexibleGang_task() const {
  71     return false;
  72   })
  73 
  74 private:
  75   NOT_PRODUCT(const char* _name;)
  76   // ??? Should a task have a priority associated with it?
  77   // ??? Or can the run method adjust priority as needed?
  78   int _counter;
  79 
  80 protected:
  81   // Constructor and desctructor: only construct subclasses.
  82   AbstractGangTask(const char* name) {
  83     NOT_PRODUCT(_name = name);
  84     _counter = 0;
  85   }
  86   virtual ~AbstractGangTask() { }
  87 };
  88 
  89 class AbstractGangTaskWOopQueues : public AbstractGangTask {
  90   OopTaskQueueSet*       _queues;
  91   ParallelTaskTerminator _terminator;
  92  public:
  93   AbstractGangTaskWOopQueues(const char* name, OopTaskQueueSet* queues) :
  94     AbstractGangTask(name), _queues(queues), _terminator(0, _queues) {}
  95   ParallelTaskTerminator* terminator() { return &_terminator; }
  96   virtual void set_for_termination(int active_workers) {
  97     terminator()->reset_for_reuse(active_workers);
  98   }
  99   OopTaskQueueSet* queues() { return _queues; }
 100 };
 101 
 102 // Class AbstractWorkGang:
 103 // An abstract class representing a gang of workers.
 104 // You subclass this to supply an implementation of run_task().
 105 class AbstractWorkGang: public CHeapObj {
 106   // Here's the public interface to this class.
 107 public:
 108   // Constructor and destructor.
 109   AbstractWorkGang(const char* name, bool are_GC_task_threads,
 110                    bool are_ConcurrentGC_threads);
 111   ~AbstractWorkGang();
 112   // Run a task, returns when the task is done (or terminated).
 113   virtual void run_task(AbstractGangTask* task) = 0;
 114   // Stop and terminate all workers.
 115   virtual void stop();
 116 public:
 117   // Debugging.
 118   const char* name() const;
 119 protected:
 120   // Initialize only instance data.
 121   const bool _are_GC_task_threads;
 122   const bool _are_ConcurrentGC_threads;
 123   // Printing support.
 124   const char* _name;
 125   // The monitor which protects these data,
 126   // and notifies of changes in it.
 127   Monitor*  _monitor;
 128   // The count of the number of workers in the gang.
 129   int _total_workers;
 130   // Whether the workers should terminate.
 131   bool _terminate;
 132   // The array of worker threads for this gang.
 133   // This is only needed for cleaning up.
 134   GangWorker** _gang_workers;
 135   // The task for this gang.
 136   AbstractGangTask* _task;
 137   // A sequence number for the current task.
 138   int _sequence_number;
 139   // The number of started workers.
 140   int _started_workers;
 141   // The number of finished workers.
 142   int _finished_workers;
 143 public:
 144   // Accessors for fields
 145   Monitor* monitor() const {
 146     return _monitor;
 147   }
 148   int total_workers() const {
 149     return _total_workers;
 150   }
 151   virtual int active_workers() const {
 152     return _total_workers;
 153   }
 154   bool terminate() const {
 155     return _terminate;
 156   }
 157   GangWorker** gang_workers() const {
 158     return _gang_workers;
 159   }
 160   AbstractGangTask* task() const {
 161     return _task;
 162   }
 163   int sequence_number() const {
 164     return _sequence_number;
 165   }
 166   int started_workers() const {
 167     return _started_workers;
 168   }
 169   int finished_workers() const {
 170     return _finished_workers;
 171   }
 172   bool are_GC_task_threads() const {
 173     return _are_GC_task_threads;
 174   }
 175   bool are_ConcurrentGC_threads() const {
 176     return _are_ConcurrentGC_threads;
 177   }
 178   // Predicates.
 179   bool is_idle() const {
 180     return (task() == NULL);
 181   }
 182   // Return the Ith gang worker.
 183   GangWorker* gang_worker(int i) const;
 184 
 185   void threads_do(ThreadClosure* tc) const;
 186 
 187   // Printing
 188   void print_worker_threads_on(outputStream *st) const;
 189   void print_worker_threads() const {
 190     print_worker_threads_on(tty);
 191   }
 192 
 193 protected:
 194   friend class GangWorker;
 195   friend class YieldingFlexibleGangWorker;
 196   // Note activation and deactivation of workers.
 197   // These methods should only be called with the mutex held.
 198   void internal_worker_poll(WorkData* data) const;
 199   void internal_note_start();
 200   void internal_note_finish();
 201 };
 202 
 203 class WorkData: public StackObj {
 204   // This would be a struct, but I want accessor methods.
 205 private:
 206   bool              _terminate;
 207   AbstractGangTask* _task;
 208   int               _sequence_number;
 209 public:
 210   // Constructor and destructor
 211   WorkData() {
 212     _terminate       = false;
 213     _task            = NULL;
 214     _sequence_number = 0;
 215   }
 216   ~WorkData() {
 217   }
 218   // Accessors and modifiers
 219   bool terminate()                       const { return _terminate;  }
 220   void set_terminate(bool value)               { _terminate = value; }
 221   AbstractGangTask* task()               const { return _task; }
 222   void set_task(AbstractGangTask* value)       { _task = value; }
 223   int sequence_number()                  const { return _sequence_number; }
 224   void set_sequence_number(int value)          { _sequence_number = value; }
 225 
 226   YieldingFlexibleGangTask* yf_task()    const {
 227     return (YieldingFlexibleGangTask*)_task;
 228   }
 229 };
 230 
 231 // Class WorkGang:
 232 class WorkGang: public AbstractWorkGang {
 233 public:
 234   // Constructor
 235   WorkGang(const char* name, int workers,
 236            bool are_GC_task_threads, bool are_ConcurrentGC_threads);
 237   // Run a task, returns when the task is done (or terminated).
 238   virtual void run_task(AbstractGangTask* task);
 239   void run_task(AbstractGangTask* task, uint no_of_parallel_workers);
 240   // Allocate a worker and return a pointer to it.
 241   virtual GangWorker* allocate_worker(int which);
 242   // Initialize workers in the gang.  Return true if initialization
 243   // succeeded. The type of the worker can be overridden in a derived
 244   // class with the appropriate implementation of allocate_worker().
 245   bool initialize_workers();
 246 };
 247 
 248 // Class GangWorker:
 249 //   Several instances of this class run in parallel as workers for a gang.
 250 class GangWorker: public WorkerThread {
 251 public:
 252   // Constructors and destructor.
 253   GangWorker(AbstractWorkGang* gang, uint id);
 254 
 255   // The only real method: run a task for the gang.
 256   virtual void run();
 257   // Predicate for Thread
 258   virtual bool is_GC_task_thread() const;
 259   virtual bool is_ConcurrentGC_thread() const;
 260   // Printing
 261   void print_on(outputStream* st) const;
 262   virtual void print() const { print_on(tty); }
 263 protected:
 264   AbstractWorkGang* _gang;
 265 
 266   virtual void initialize();
 267   virtual void loop();
 268 
 269 public:
 270   AbstractWorkGang* gang() const { return _gang; }
 271 };
 272 
 273 class FlexibleWorkGang: public WorkGang {
 274  protected:
 275   int _active_workers;
 276  public:
 277   // Constructor and destructor.
 278   FlexibleWorkGang(const char* name, int workers,
 279                    bool are_GC_task_threads,
 280                    bool  are_ConcurrentGC_threads) :
 281     WorkGang(name, workers, are_GC_task_threads, are_ConcurrentGC_threads) {
 282     _active_workers = ParallelGCThreads;
 283   };
 284   // Accessors for fields
 285   virtual int active_workers() const { return _active_workers; }
 286   void set_active_workers(int v) { _active_workers = v; }
 287 };
 288 
 289 // Work gangs in garbage collectors: 2009-06-10
 290 //
 291 // SharedHeap - work gang for stop-the-world parallel collection.
 292 //   Used by
 293 //     ParNewGeneration
 294 //     CMSParRemarkTask
 295 //     CMSRefProcTaskExecutor
 296 //     G1CollectedHeap
 297 //     G1ParFinalCountTask
 298 // ConcurrentMark
 299 // CMSCollector
 300 
 301 // A class that acts as a synchronisation barrier. Workers enter
 302 // the barrier and must wait until all other workers have entered
 303 // before any of them may leave.
 304 
 305 class WorkGangBarrierSync : public StackObj {
 306 protected:
 307   Monitor _monitor;
 308   int     _n_workers;
 309   int     _n_completed;
 310   bool    _should_reset;
 311 
 312   Monitor* monitor()        { return &_monitor; }
 313   int      n_workers()      { return _n_workers; }
 314   int      n_completed()    { return _n_completed; }
 315   bool     should_reset()   { return _should_reset; }
 316 
 317   void     zero_completed() { _n_completed = 0; }
 318   void     inc_completed()  { _n_completed++; }
 319 
 320   void     set_should_reset(bool v) { _should_reset = v; }
 321 
 322 public:
 323   WorkGangBarrierSync();
 324   WorkGangBarrierSync(int n_workers, const char* name);
 325 
 326   // Set the number of workers that will use the barrier.
 327   // Must be called before any of the workers start running.
 328   void set_n_workers(int n_workers);
 329 
 330   // Enter the barrier. A worker that enters the barrier will
 331   // not be allowed to leave until all other threads have
 332   // also entered the barrier.
 333   void enter();
 334 };
 335 
 336 // A class to manage claiming of subtasks within a group of tasks.  The
 337 // subtasks will be identified by integer indices, usually elements of an
 338 // enumeration type.
 339 
 340 class SubTasksDone: public CHeapObj {
 341   jint* _tasks;
 342   int _n_tasks;
 343   int _n_threads;
 344   jint _threads_completed;
 345 #ifdef ASSERT
 346   volatile jint _claimed;
 347 #endif
 348 
 349   // Set all tasks to unclaimed.
 350   void clear();
 351 
 352 public:
 353   // Initializes "this" to a state in which there are "n" tasks to be
 354   // processed, none of the which are originally claimed.  The number of
 355   // threads doing the tasks is initialized 1.
 356   SubTasksDone(int n);
 357 
 358   // True iff the object is in a valid state.
 359   bool valid();
 360 
 361   // Get/set the number of parallel threads doing the tasks to "t".  Can only
 362   // be called before tasks start or after they are complete.
 363   int n_threads() { return _n_threads; }
 364   void set_n_threads(int t);
 365 
 366   // Returns "false" if the task "t" is unclaimed, and ensures that task is
 367   // claimed.  The task "t" is required to be within the range of "this".
 368   bool is_task_claimed(int t);
 369 
 370   // The calling thread asserts that it has attempted to claim all the
 371   // tasks that it will try to claim.  Every thread in the parallel task
 372   // must execute this.  (When the last thread does so, the task array is
 373   // cleared.)
 374   void all_tasks_completed();
 375 
 376   // Destructor.
 377   ~SubTasksDone();
 378 };
 379 
 380 // As above, but for sequential tasks, i.e. instead of claiming
 381 // sub-tasks from a set (possibly an enumeration), claim sub-tasks
 382 // in sequential order. This is ideal for claiming dynamically
 383 // partitioned tasks (like striding in the parallel remembered
 384 // set scanning). Note that unlike the above class this is
 385 // a stack object - is there any reason for it not to be?
 386 
 387 class SequentialSubTasksDone : public StackObj {
 388 protected:
 389   jint _n_tasks;     // Total number of tasks available.
 390   jint _n_claimed;   // Number of tasks claimed.
 391   // _n_threads is used to determine when a sub task is done.
 392   // See comments on SubTasksDone::_n_threads
 393   jint _n_threads;   // Total number of parallel threads.
 394   jint _n_completed; // Number of completed threads.
 395 
 396   void clear();
 397 
 398 public:
 399   SequentialSubTasksDone() {
 400     clear();
 401   }
 402   ~SequentialSubTasksDone() {}
 403 
 404   // True iff the object is in a valid state.
 405   bool valid();
 406 
 407   // number of tasks
 408   jint n_tasks() const { return _n_tasks; }
 409 
 410   // Get/set the number of parallel threads doing the tasks to t.
 411   // Should be called before the task starts but it is safe
 412   // to call this once a task is running provided that all
 413   // threads agree on the number of threads.
 414   int n_threads() { return _n_threads; }
 415   void set_n_threads(int t) { _n_threads = t; }
 416 
 417   // Set the number of tasks to be claimed to t. As above,
 418   // should be called before the tasks start but it is safe
 419   // to call this once a task is running provided all threads
 420   // agree on the number of tasks.
 421   void set_n_tasks(int t) { _n_tasks = t; }
 422 
 423   // Returns false if the next task in the sequence is unclaimed,
 424   // and ensures that it is claimed. Will set t to be the index
 425   // of the claimed task in the sequence. Will return true if
 426   // the task cannot be claimed and there are none left to claim.
 427   bool is_task_claimed(int& t);
 428 
 429   // The calling thread asserts that it has attempted to claim
 430   // all the tasks it possibly can in the sequence. Every thread
 431   // claiming tasks must promise call this. Returns true if this
 432   // is the last thread to complete so that the thread can perform
 433   // cleanup if necessary.
 434   bool all_tasks_completed();
 435 };
 436 
 437 // Represents a set of free small integer ids.
 438 class FreeIdSet {
 439   enum {
 440     end_of_list = -1,
 441     claimed = -2
 442   };
 443 
 444   int _sz;
 445   Monitor* _mon;
 446 
 447   int* _ids;
 448   int _hd;
 449   int _waiters;
 450   int _claimed;
 451 
 452   static bool _safepoint;
 453   typedef FreeIdSet* FreeIdSetPtr;
 454   static const int NSets = 10;
 455   static FreeIdSetPtr _sets[NSets];
 456   static bool _stat_init;
 457   int _index;
 458 
 459 public:
 460   FreeIdSet(int sz, Monitor* mon);
 461   ~FreeIdSet();
 462 
 463   static void set_safepoint(bool b);
 464 
 465   // Attempt to claim the given id permanently.  Returns "true" iff
 466   // successful.
 467   bool claim_perm_id(int i);
 468 
 469   // Returns an unclaimed parallel id (waiting for one to be released if
 470   // necessary).  Returns "-1" if a GC wakes up a wait for an id.
 471   int claim_par_id();
 472 
 473   void release_par_id(int id);
 474 };
 475 
 476 #endif // SHARE_VM_UTILITIES_WORKGROUP_HPP