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 #ifndef SHARE_VM_MEMORY_REFERENCEPROCESSOR_HPP
  26 #define SHARE_VM_MEMORY_REFERENCEPROCESSOR_HPP
  27 
  28 #include "memory/referencePolicy.hpp"
  29 #include "oops/instanceRefKlass.hpp"
  30 
  31 // ReferenceProcessor class encapsulates the per-"collector" processing
  32 // of java.lang.Reference objects for GC. The interface is useful for supporting
  33 // a generational abstraction, in particular when there are multiple
  34 // generations that are being independently collected -- possibly
  35 // concurrently and/or incrementally.  Note, however, that the
  36 // ReferenceProcessor class abstracts away from a generational setting
  37 // by using only a heap interval (called "span" below), thus allowing
  38 // its use in a straightforward manner in a general, non-generational
  39 // setting.
  40 //
  41 // The basic idea is that each ReferenceProcessor object concerns
  42 // itself with ("weak") reference processing in a specific "span"
  43 // of the heap of interest to a specific collector. Currently,
  44 // the span is a convex interval of the heap, but, efficiency
  45 // apart, there seems to be no reason it couldn't be extended
  46 // (with appropriate modifications) to any "non-convex interval".
  47 
  48 // forward references
  49 class ReferencePolicy;
  50 class AbstractRefProcTaskExecutor;
  51 class DiscoveredList;
  52 
  53 class ReferenceProcessor : public CHeapObj {
  54  protected:
  55   // End of list marker
  56   static oop  _sentinelRef;
  57   MemRegion   _span; // (right-open) interval of heap
  58                      // subject to wkref discovery
  59   bool        _discovering_refs;      // true when discovery enabled
  60   bool        _discovery_is_atomic;   // if discovery is atomic wrt
  61                                       // other collectors in configuration
  62   bool        _discovery_is_mt;       // true if reference discovery is MT.
  63   // If true, setting "next" field of a discovered refs list requires
  64   // write barrier(s).  (Must be true if used in a collector in which
  65   // elements of a discovered list may be moved during discovery: for
  66   // example, a collector like Garbage-First that moves objects during a
  67   // long-term concurrent marking phase that does weak reference
  68   // discovery.)
  69   bool        _discovered_list_needs_barrier;
  70   BarrierSet* _bs;                    // Cached copy of BarrierSet.
  71   bool        _enqueuing_is_done;     // true if all weak references enqueued
  72   bool        _processing_is_mt;      // true during phases when
  73                                       // reference processing is MT.
  74   int         _next_id;               // round-robin counter in
  75                                       // support of work distribution
  76 
  77   // For collectors that do not keep GC marking information
  78   // in the object header, this field holds a closure that
  79   // helps the reference processor determine the reachability
  80   // of an oop (the field is currently initialized to NULL for
  81   // all collectors but the CMS collector).
  82   BoolObjectClosure* _is_alive_non_header;
  83 
  84   // Soft ref clearing policies
  85   // . the default policy
  86   static ReferencePolicy*   _default_soft_ref_policy;
  87   // . the "clear all" policy
  88   static ReferencePolicy*   _always_clear_soft_ref_policy;
  89   // . the current policy below is either one of the above
  90   ReferencePolicy*          _current_soft_ref_policy;
  91 
  92   // The discovered ref lists themselves
  93 
  94   // The active MT'ness degree of the queues below
  95   int             _num_q;
  96   // The maximum MT'ness degree of the queues below
  97   int             _max_num_q;
  98   // Arrays of lists of oops, one per thread
  99   DiscoveredList* _discoveredSoftRefs;
 100   DiscoveredList* _discoveredWeakRefs;
 101   DiscoveredList* _discoveredFinalRefs;
 102   DiscoveredList* _discoveredPhantomRefs;
 103 
 104  public:
 105   int num_q()                            { return _num_q; }
 106   void set_mt_degree(int v)              { _num_q = v; }
 107   DiscoveredList* discovered_soft_refs() { return _discoveredSoftRefs; }
 108   static oop  sentinel_ref()             { return _sentinelRef; }
 109   static oop* adr_sentinel_ref()         { return &_sentinelRef; }
 110   ReferencePolicy* setup_policy(bool always_clear) {
 111     _current_soft_ref_policy = always_clear ?
 112       _always_clear_soft_ref_policy : _default_soft_ref_policy;
 113     _current_soft_ref_policy->setup();   // snapshot the policy threshold
 114     return _current_soft_ref_policy;
 115   }
 116 
 117  public:
 118   // Process references with a certain reachability level.
 119   void process_discovered_reflist(DiscoveredList               refs_lists[],
 120                                   ReferencePolicy*             policy,
 121                                   bool                         clear_referent,
 122                                   BoolObjectClosure*           is_alive,
 123                                   OopClosure*                  keep_alive,
 124                                   VoidClosure*                 complete_gc,
 125                                   AbstractRefProcTaskExecutor* task_executor);
 126 
 127   void process_phaseJNI(BoolObjectClosure* is_alive,
 128                         OopClosure*        keep_alive,
 129                         VoidClosure*       complete_gc);
 130 
 131   // Work methods used by the method process_discovered_reflist
 132   // Phase1: keep alive all those referents that are otherwise
 133   // dead but which must be kept alive by policy (and their closure).
 134   void process_phase1(DiscoveredList&     refs_list,
 135                       ReferencePolicy*    policy,
 136                       BoolObjectClosure*  is_alive,
 137                       OopClosure*         keep_alive,
 138                       VoidClosure*        complete_gc);
 139   // Phase2: remove all those references whose referents are
 140   // reachable.
 141   inline void process_phase2(DiscoveredList&    refs_list,
 142                              BoolObjectClosure* is_alive,
 143                              OopClosure*        keep_alive,
 144                              VoidClosure*       complete_gc) {
 145     if (discovery_is_atomic()) {
 146       // complete_gc is ignored in this case for this phase
 147       pp2_work(refs_list, is_alive, keep_alive);
 148     } else {
 149       assert(complete_gc != NULL, "Error");
 150       pp2_work_concurrent_discovery(refs_list, is_alive,
 151                                     keep_alive, complete_gc);
 152     }
 153   }
 154   // Work methods in support of process_phase2
 155   void pp2_work(DiscoveredList&    refs_list,
 156                 BoolObjectClosure* is_alive,
 157                 OopClosure*        keep_alive);
 158   void pp2_work_concurrent_discovery(
 159                 DiscoveredList&    refs_list,
 160                 BoolObjectClosure* is_alive,
 161                 OopClosure*        keep_alive,
 162                 VoidClosure*       complete_gc);
 163   // Phase3: process the referents by either clearing them
 164   // or keeping them alive (and their closure)
 165   void process_phase3(DiscoveredList&    refs_list,
 166                       bool               clear_referent,
 167                       BoolObjectClosure* is_alive,
 168                       OopClosure*        keep_alive,
 169                       VoidClosure*       complete_gc);
 170 
 171   // Enqueue references with a certain reachability level
 172   void enqueue_discovered_reflist(DiscoveredList& refs_list, HeapWord* pending_list_addr);
 173 
 174   // "Preclean" all the discovered reference lists
 175   // by removing references with strongly reachable referents.
 176   // The first argument is a predicate on an oop that indicates
 177   // its (strong) reachability and the second is a closure that
 178   // may be used to incrementalize or abort the precleaning process.
 179   // The caller is responsible for taking care of potential
 180   // interference with concurrent operations on these lists
 181   // (or predicates involved) by other threads. Currently
 182   // only used by the CMS collector.  should_unload_classes is
 183   // used to aid assertion checking when classes are collected.
 184   void preclean_discovered_references(BoolObjectClosure* is_alive,
 185                                       OopClosure*        keep_alive,
 186                                       VoidClosure*       complete_gc,
 187                                       YieldClosure*      yield,
 188                                       bool               should_unload_classes);
 189 
 190   // Delete entries in the discovered lists that have
 191   // either a null referent or are not active. Such
 192   // Reference objects can result from the clearing
 193   // or enqueueing of Reference objects concurrent
 194   // with their discovery by a (concurrent) collector.
 195   // For a definition of "active" see java.lang.ref.Reference;
 196   // Refs are born active, become inactive when enqueued,
 197   // and never become active again. The state of being
 198   // active is encoded as follows: A Ref is active
 199   // if and only if its "next" field is NULL.
 200   void clean_up_discovered_references();
 201   void clean_up_discovered_reflist(DiscoveredList& refs_list);
 202 
 203   // Returns the name of the discovered reference list
 204   // occupying the i / _num_q slot.
 205   const char* list_name(int i);
 206 
 207   void enqueue_discovered_reflists(HeapWord* pending_list_addr, AbstractRefProcTaskExecutor* task_executor);
 208 
 209  protected:
 210   // "Preclean" the given discovered reference list
 211   // by removing references with strongly reachable referents.
 212   // Currently used in support of CMS only.
 213   void preclean_discovered_reflist(DiscoveredList&    refs_list,
 214                                    BoolObjectClosure* is_alive,
 215                                    OopClosure*        keep_alive,
 216                                    VoidClosure*       complete_gc,
 217                                    YieldClosure*      yield);
 218 
 219   int next_id() {
 220     int id = _next_id;
 221     if (++_next_id == _num_q) {
 222       _next_id = 0;
 223     }
 224     return id;
 225   }
 226   DiscoveredList* get_discovered_list(ReferenceType rt);
 227   inline void add_to_discovered_list_mt(DiscoveredList& refs_list, oop obj,
 228                                         HeapWord* discovered_addr);
 229   void verify_ok_to_handle_reflists() PRODUCT_RETURN;
 230 
 231   void abandon_partial_discovered_list(DiscoveredList& refs_list);
 232 
 233   // Calculate the number of jni handles.
 234   unsigned int count_jni_refs();
 235 
 236   // Balances reference queues.
 237   void balance_queues(DiscoveredList ref_lists[]);
 238 
 239   // Update (advance) the soft ref master clock field.
 240   void update_soft_ref_master_clock();
 241 
 242  public:
 243   // constructor
 244   ReferenceProcessor():
 245     _span((HeapWord*)NULL, (HeapWord*)NULL),
 246     _discoveredSoftRefs(NULL),  _discoveredWeakRefs(NULL),
 247     _discoveredFinalRefs(NULL), _discoveredPhantomRefs(NULL),
 248     _discovering_refs(false),
 249     _discovery_is_atomic(true),
 250     _enqueuing_is_done(false),
 251     _discovery_is_mt(false),
 252     _discovered_list_needs_barrier(false),
 253     _bs(NULL),
 254     _is_alive_non_header(NULL),
 255     _num_q(0),
 256     _max_num_q(0),
 257     _processing_is_mt(false),
 258     _next_id(0)
 259   { }
 260 
 261   // Default parameters give you a vanilla reference processor.
 262   ReferenceProcessor(MemRegion span,
 263                      bool mt_processing = false, int mt_processing_degree = 1,
 264                      bool mt_discovery  = false, int mt_discovery_degree  = 1,
 265                      bool atomic_discovery = true,
 266                      BoolObjectClosure* is_alive_non_header = NULL,
 267                      bool discovered_list_needs_barrier = false);
 268 
 269   // RefDiscoveryPolicy values
 270   enum DiscoveryPolicy {
 271     ReferenceBasedDiscovery = 0,
 272     ReferentBasedDiscovery  = 1,
 273     DiscoveryPolicyMin      = ReferenceBasedDiscovery,
 274     DiscoveryPolicyMax      = ReferentBasedDiscovery
 275   };
 276 
 277   static void init_statics();
 278 
 279  public:
 280   // get and set "is_alive_non_header" field
 281   BoolObjectClosure* is_alive_non_header() {
 282     return _is_alive_non_header;
 283   }
 284   void set_is_alive_non_header(BoolObjectClosure* is_alive_non_header) {
 285     _is_alive_non_header = is_alive_non_header;
 286   }
 287 
 288   // get and set span
 289   MemRegion span()                   { return _span; }
 290   void      set_span(MemRegion span) { _span = span; }
 291 
 292   // start and stop weak ref discovery
 293   void enable_discovery()   { _discovering_refs = true;  }
 294   void disable_discovery()  { _discovering_refs = false; }
 295   bool discovery_enabled()  { return _discovering_refs;  }
 296 
 297   // whether discovery is atomic wrt other collectors
 298   bool discovery_is_atomic() const { return _discovery_is_atomic; }
 299   void set_atomic_discovery(bool atomic) { _discovery_is_atomic = atomic; }
 300 
 301   // whether discovery is done by multiple threads same-old-timeously
 302   bool discovery_is_mt() const { return _discovery_is_mt; }
 303   void set_mt_discovery(bool mt) { _discovery_is_mt = mt; }
 304 
 305   // Whether we are in a phase when _processing_ is MT.
 306   bool processing_is_mt() const { return _processing_is_mt; }
 307   void set_mt_processing(bool mt) { _processing_is_mt = mt; }
 308 
 309   // whether all enqueuing of weak references is complete
 310   bool enqueuing_is_done()  { return _enqueuing_is_done; }
 311   void set_enqueuing_is_done(bool v) { _enqueuing_is_done = v; }
 312 
 313   // iterate over oops
 314   void weak_oops_do(OopClosure* f);       // weak roots
 315   static void oops_do(OopClosure* f);     // strong root(s)
 316 
 317   // Balance each of the discovered lists.
 318   void balance_all_queues();
 319 
 320   // Discover a Reference object, using appropriate discovery criteria
 321   bool discover_reference(oop obj, ReferenceType rt);
 322 
 323   // Process references found during GC (called by the garbage collector)
 324   void process_discovered_references(BoolObjectClosure*           is_alive,
 325                                      OopClosure*                  keep_alive,
 326                                      VoidClosure*                 complete_gc,
 327                                      AbstractRefProcTaskExecutor* task_executor);
 328 
 329  public:
 330   // Enqueue references at end of GC (called by the garbage collector)
 331   bool enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor = NULL);
 332 
 333   // If a discovery is in process that is being superceded, abandon it: all
 334   // the discovered lists will be empty, and all the objects on them will
 335   // have NULL discovered fields.  Must be called only at a safepoint.
 336   void abandon_partial_discovery();
 337 
 338   // debugging
 339   void verify_no_references_recorded() PRODUCT_RETURN;
 340   void verify_referent(oop obj)        PRODUCT_RETURN;
 341   static void verify();
 342 
 343   // clear the discovered lists (unlinking each entry).
 344   void clear_discovered_references() PRODUCT_RETURN;
 345 };
 346 
 347 // A utility class to disable reference discovery in
 348 // the scope which contains it, for given ReferenceProcessor.
 349 class NoRefDiscovery: StackObj {
 350  private:
 351   ReferenceProcessor* _rp;
 352   bool _was_discovering_refs;
 353  public:
 354   NoRefDiscovery(ReferenceProcessor* rp) : _rp(rp) {
 355     _was_discovering_refs = _rp->discovery_enabled();
 356     if (_was_discovering_refs) {
 357       _rp->disable_discovery();
 358     }
 359   }
 360 
 361   ~NoRefDiscovery() {
 362     if (_was_discovering_refs) {
 363       _rp->enable_discovery();
 364     }
 365   }
 366 };
 367 
 368 
 369 // A utility class to temporarily mutate the span of the
 370 // given ReferenceProcessor in the scope that contains it.
 371 class ReferenceProcessorSpanMutator: StackObj {
 372  private:
 373   ReferenceProcessor* _rp;
 374   MemRegion           _saved_span;
 375 
 376  public:
 377   ReferenceProcessorSpanMutator(ReferenceProcessor* rp,
 378                                 MemRegion span):
 379     _rp(rp) {
 380     _saved_span = _rp->span();
 381     _rp->set_span(span);
 382   }
 383 
 384   ~ReferenceProcessorSpanMutator() {
 385     _rp->set_span(_saved_span);
 386   }
 387 };
 388 
 389 // A utility class to temporarily change the MT'ness of
 390 // reference discovery for the given ReferenceProcessor
 391 // in the scope that contains it.
 392 class ReferenceProcessorMTMutator: StackObj {
 393  private:
 394   ReferenceProcessor* _rp;
 395   bool                _saved_mt;
 396 
 397  public:
 398   ReferenceProcessorMTMutator(ReferenceProcessor* rp,
 399                               bool mt):
 400     _rp(rp) {
 401     _saved_mt = _rp->discovery_is_mt();
 402     _rp->set_mt_discovery(mt);
 403   }
 404 
 405   ~ReferenceProcessorMTMutator() {
 406     _rp->set_mt_discovery(_saved_mt);
 407   }
 408 };
 409 
 410 
 411 // A utility class to temporarily change the disposition
 412 // of the "is_alive_non_header" closure field of the
 413 // given ReferenceProcessor in the scope that contains it.
 414 class ReferenceProcessorIsAliveMutator: StackObj {
 415  private:
 416   ReferenceProcessor* _rp;
 417   BoolObjectClosure*  _saved_cl;
 418 
 419  public:
 420   ReferenceProcessorIsAliveMutator(ReferenceProcessor* rp,
 421                                    BoolObjectClosure*  cl):
 422     _rp(rp) {
 423     _saved_cl = _rp->is_alive_non_header();
 424     _rp->set_is_alive_non_header(cl);
 425   }
 426 
 427   ~ReferenceProcessorIsAliveMutator() {
 428     _rp->set_is_alive_non_header(_saved_cl);
 429   }
 430 };
 431 
 432 // A utility class to temporarily change the disposition
 433 // of the "discovery_is_atomic" field of the
 434 // given ReferenceProcessor in the scope that contains it.
 435 class ReferenceProcessorAtomicMutator: StackObj {
 436  private:
 437   ReferenceProcessor* _rp;
 438   bool                _saved_atomic_discovery;
 439 
 440  public:
 441   ReferenceProcessorAtomicMutator(ReferenceProcessor* rp,
 442                                   bool atomic):
 443     _rp(rp) {
 444     _saved_atomic_discovery = _rp->discovery_is_atomic();
 445     _rp->set_atomic_discovery(atomic);
 446   }
 447 
 448   ~ReferenceProcessorAtomicMutator() {
 449     _rp->set_atomic_discovery(_saved_atomic_discovery);
 450   }
 451 };
 452 
 453 
 454 // A utility class to temporarily change the MT processing
 455 // disposition of the given ReferenceProcessor instance
 456 // in the scope that contains it.
 457 class ReferenceProcessorMTProcMutator: StackObj {
 458  private:
 459   ReferenceProcessor* _rp;
 460   bool  _saved_mt;
 461 
 462  public:
 463   ReferenceProcessorMTProcMutator(ReferenceProcessor* rp,
 464                                   bool mt):
 465     _rp(rp) {
 466     _saved_mt = _rp->processing_is_mt();
 467     _rp->set_mt_processing(mt);
 468   }
 469 
 470   ~ReferenceProcessorMTProcMutator() {
 471     _rp->set_mt_processing(_saved_mt);
 472   }
 473 };
 474 
 475 
 476 // This class is an interface used to implement task execution for the
 477 // reference processing.
 478 class AbstractRefProcTaskExecutor {
 479 public:
 480 
 481   // Abstract tasks to execute.
 482   class ProcessTask;
 483   class EnqueueTask;
 484 
 485   // Executes a task using worker threads.
 486   virtual void execute(ProcessTask& task) = 0;
 487   virtual void execute(EnqueueTask& task) = 0;
 488 
 489   // Switch to single threaded mode.
 490   virtual void set_single_threaded_mode() { };
 491 };
 492 
 493 // Abstract reference processing task to execute.
 494 class AbstractRefProcTaskExecutor::ProcessTask {
 495 protected:
 496   ProcessTask(ReferenceProcessor& ref_processor,
 497               DiscoveredList      refs_lists[],
 498               bool                marks_oops_alive)
 499     : _ref_processor(ref_processor),
 500       _refs_lists(refs_lists),
 501       _marks_oops_alive(marks_oops_alive)
 502   { }
 503 
 504 public:
 505   virtual void work(unsigned int work_id, BoolObjectClosure& is_alive,
 506                     OopClosure& keep_alive,
 507                     VoidClosure& complete_gc) = 0;
 508 
 509   // Returns true if a task marks some oops as alive.
 510   bool marks_oops_alive() const
 511   { return _marks_oops_alive; }
 512 
 513 protected:
 514   ReferenceProcessor& _ref_processor;
 515   DiscoveredList*     _refs_lists;
 516   const bool          _marks_oops_alive;
 517 };
 518 
 519 // Abstract reference processing task to execute.
 520 class AbstractRefProcTaskExecutor::EnqueueTask {
 521 protected:
 522   EnqueueTask(ReferenceProcessor& ref_processor,
 523               DiscoveredList      refs_lists[],
 524               HeapWord*           pending_list_addr,
 525               oop                 sentinel_ref,
 526               int                 n_queues)
 527     : _ref_processor(ref_processor),
 528       _refs_lists(refs_lists),
 529       _pending_list_addr(pending_list_addr),
 530       _sentinel_ref(sentinel_ref),
 531       _n_queues(n_queues)
 532   { }
 533 
 534 public:
 535   virtual void work(unsigned int work_id) = 0;
 536 
 537 protected:
 538   ReferenceProcessor& _ref_processor;
 539   DiscoveredList*     _refs_lists;
 540   HeapWord*           _pending_list_addr;
 541   oop                 _sentinel_ref;
 542   int                 _n_queues;
 543 };
 544 
 545 #endif // SHARE_VM_MEMORY_REFERENCEPROCESSOR_HPP