src/share/vm/memory/referenceProcessor.cpp

Thu, 05 Sep 2019 18:52:27 +0800

author
aoqi
date
Thu, 05 Sep 2019 18:52:27 +0800
changeset 9703
2fdf635bcf28
parent 7994
04ff2f6cd0eb
parent 9665
a8441ccaff15
child 9931
fd44df5e3bc3
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 2001, 2014, 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  */
    25 #include "precompiled.hpp"
    26 #include "classfile/javaClasses.hpp"
    27 #include "classfile/systemDictionary.hpp"
    28 #include "gc_implementation/shared/gcTimer.hpp"
    29 #include "gc_implementation/shared/gcTraceTime.hpp"
    30 #include "gc_interface/collectedHeap.hpp"
    31 #include "gc_interface/collectedHeap.inline.hpp"
    32 #include "memory/referencePolicy.hpp"
    33 #include "memory/referenceProcessor.hpp"
    34 #include "oops/oop.inline.hpp"
    35 #include "runtime/java.hpp"
    36 #include "runtime/jniHandles.hpp"
    38 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    40 ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL;
    41 ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy      = NULL;
    42 bool             ReferenceProcessor::_pending_list_uses_discovered_field = false;
    43 jlong            ReferenceProcessor::_soft_ref_timestamp_clock = 0;
    45 void referenceProcessor_init() {
    46   ReferenceProcessor::init_statics();
    47 }
    49 void ReferenceProcessor::init_statics() {
    50   // We need a monotonically non-deccreasing time in ms but
    51   // os::javaTimeMillis() does not guarantee monotonicity.
    52   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
    54   // Initialize the soft ref timestamp clock.
    55   _soft_ref_timestamp_clock = now;
    56   // Also update the soft ref clock in j.l.r.SoftReference
    57   java_lang_ref_SoftReference::set_clock(_soft_ref_timestamp_clock);
    59   _always_clear_soft_ref_policy = new AlwaysClearPolicy();
    60   _default_soft_ref_policy      = new COMPILER2_PRESENT(LRUMaxHeapPolicy())
    61                                       NOT_COMPILER2(LRUCurrentHeapPolicy());
    62   if (_always_clear_soft_ref_policy == NULL || _default_soft_ref_policy == NULL) {
    63     vm_exit_during_initialization("Could not allocate reference policy object");
    64   }
    65   guarantee(RefDiscoveryPolicy == ReferenceBasedDiscovery ||
    66             RefDiscoveryPolicy == ReferentBasedDiscovery,
    67             "Unrecongnized RefDiscoveryPolicy");
    68   _pending_list_uses_discovered_field = JDK_Version::current().pending_list_uses_discovered_field();
    69 }
    71 void ReferenceProcessor::enable_discovery(bool verify_disabled, bool check_no_refs) {
    72 #ifdef ASSERT
    73   // Verify that we're not currently discovering refs
    74   assert(!verify_disabled || !_discovering_refs, "nested call?");
    76   if (check_no_refs) {
    77     // Verify that the discovered lists are empty
    78     verify_no_references_recorded();
    79   }
    80 #endif // ASSERT
    82   // Someone could have modified the value of the static
    83   // field in the j.l.r.SoftReference class that holds the
    84   // soft reference timestamp clock using reflection or
    85   // Unsafe between GCs. Unconditionally update the static
    86   // field in ReferenceProcessor here so that we use the new
    87   // value during reference discovery.
    89   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
    90   _discovering_refs = true;
    91 }
    93 ReferenceProcessor::ReferenceProcessor(MemRegion span,
    94                                        bool      mt_processing,
    95                                        uint      mt_processing_degree,
    96                                        bool      mt_discovery,
    97                                        uint      mt_discovery_degree,
    98                                        bool      atomic_discovery,
    99                                        BoolObjectClosure* is_alive_non_header)  :
   100   _discovering_refs(false),
   101   _enqueuing_is_done(false),
   102   _is_alive_non_header(is_alive_non_header),
   103   _processing_is_mt(mt_processing),
   104   _next_id(0)
   105 {
   106   _span = span;
   107   _discovery_is_atomic = atomic_discovery;
   108   _discovery_is_mt     = mt_discovery;
   109   _num_q               = MAX2(1U, mt_processing_degree);
   110   _max_num_q           = MAX2(_num_q, mt_discovery_degree);
   111   _discovered_refs     = NEW_C_HEAP_ARRAY(DiscoveredList,
   112             _max_num_q * number_of_subclasses_of_ref(), mtGC);
   114   if (_discovered_refs == NULL) {
   115     vm_exit_during_initialization("Could not allocated RefProc Array");
   116   }
   117   _discoveredSoftRefs    = &_discovered_refs[0];
   118   _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_q];
   119   _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_q];
   120   _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_q];
   121   _discoveredCleanerRefs = &_discoveredPhantomRefs[_max_num_q];
   123   // Initialize all entries to NULL
   124   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
   125     _discovered_refs[i].set_head(NULL);
   126     _discovered_refs[i].set_length(0);
   127   }
   129   setup_policy(false /* default soft ref policy */);
   130 }
   132 #ifndef PRODUCT
   133 void ReferenceProcessor::verify_no_references_recorded() {
   134   guarantee(!_discovering_refs, "Discovering refs?");
   135   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
   136     guarantee(_discovered_refs[i].is_empty(),
   137               "Found non-empty discovered list");
   138   }
   139 }
   140 #endif
   142 void ReferenceProcessor::weak_oops_do(OopClosure* f) {
   143   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
   144     if (UseCompressedOops) {
   145       f->do_oop((narrowOop*)_discovered_refs[i].adr_head());
   146     } else {
   147       f->do_oop((oop*)_discovered_refs[i].adr_head());
   148     }
   149   }
   150 }
   152 void ReferenceProcessor::update_soft_ref_master_clock() {
   153   // Update (advance) the soft ref master clock field. This must be done
   154   // after processing the soft ref list.
   156   // We need a monotonically non-deccreasing time in ms but
   157   // os::javaTimeMillis() does not guarantee monotonicity.
   158   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
   159   jlong soft_ref_clock = java_lang_ref_SoftReference::clock();
   160   assert(soft_ref_clock == _soft_ref_timestamp_clock, "soft ref clocks out of sync");
   162   NOT_PRODUCT(
   163   if (now < _soft_ref_timestamp_clock) {
   164     warning("time warp: "INT64_FORMAT" to "INT64_FORMAT,
   165             _soft_ref_timestamp_clock, now);
   166   }
   167   )
   168   // The values of now and _soft_ref_timestamp_clock are set using
   169   // javaTimeNanos(), which is guaranteed to be monotonically
   170   // non-decreasing provided the underlying platform provides such
   171   // a time source (and it is bug free).
   172   // In product mode, however, protect ourselves from non-monotonicty.
   173   if (now > _soft_ref_timestamp_clock) {
   174     _soft_ref_timestamp_clock = now;
   175     java_lang_ref_SoftReference::set_clock(now);
   176   }
   177   // Else leave clock stalled at its old value until time progresses
   178   // past clock value.
   179 }
   181 size_t ReferenceProcessor::total_count(DiscoveredList lists[]) {
   182   size_t total = 0;
   183   for (uint i = 0; i < _max_num_q; ++i) {
   184     total += lists[i].length();
   185   }
   186   return total;
   187 }
   189 ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
   190   BoolObjectClosure*           is_alive,
   191   OopClosure*                  keep_alive,
   192   VoidClosure*                 complete_gc,
   193   AbstractRefProcTaskExecutor* task_executor,
   194   GCTimer*                     gc_timer,
   195   GCId                         gc_id) {
   196   NOT_PRODUCT(verify_ok_to_handle_reflists());
   198   assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
   199   // Stop treating discovered references specially.
   200   disable_discovery();
   202   // If discovery was concurrent, someone could have modified
   203   // the value of the static field in the j.l.r.SoftReference
   204   // class that holds the soft reference timestamp clock using
   205   // reflection or Unsafe between when discovery was enabled and
   206   // now. Unconditionally update the static field in ReferenceProcessor
   207   // here so that we use the new value during processing of the
   208   // discovered soft refs.
   210   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
   212   bool trace_time = PrintGCDetails && PrintReferenceGC;
   214   // Soft references
   215   size_t soft_count = 0;
   216   {
   217     GCTraceTime tt("SoftReference", trace_time, false, gc_timer, gc_id);
   218     soft_count =
   219       process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
   220                                  is_alive, keep_alive, complete_gc, task_executor);
   221   }
   223   update_soft_ref_master_clock();
   225   // Weak references
   226   size_t weak_count = 0;
   227   {
   228     GCTraceTime tt("WeakReference", trace_time, false, gc_timer, gc_id);
   229     weak_count =
   230       process_discovered_reflist(_discoveredWeakRefs, NULL, true,
   231                                  is_alive, keep_alive, complete_gc, task_executor);
   232   }
   234   // Final references
   235   size_t final_count = 0;
   236   {
   237     GCTraceTime tt("FinalReference", trace_time, false, gc_timer, gc_id);
   238     final_count =
   239       process_discovered_reflist(_discoveredFinalRefs, NULL, false,
   240                                  is_alive, keep_alive, complete_gc, task_executor);
   241   }
   243   // Phantom references
   244   size_t phantom_count = 0;
   245   {
   246     GCTraceTime tt("PhantomReference", trace_time, false, gc_timer, gc_id);
   247     phantom_count =
   248       process_discovered_reflist(_discoveredPhantomRefs, NULL, false,
   249                                  is_alive, keep_alive, complete_gc, task_executor);
   251     // Process cleaners, but include them in phantom statistics.  We expect
   252     // Cleaner references to be temporary, and don't want to deal with
   253     // possible incompatibilities arising from making it more visible.
   254     phantom_count +=
   255       process_discovered_reflist(_discoveredCleanerRefs, NULL, true,
   256                                  is_alive, keep_alive, complete_gc, task_executor);
   257   }
   259   // Weak global JNI references. It would make more sense (semantically) to
   260   // traverse these simultaneously with the regular weak references above, but
   261   // that is not how the JDK1.2 specification is. See #4126360. Native code can
   262   // thus use JNI weak references to circumvent the phantom references and
   263   // resurrect a "post-mortem" object.
   264   {
   265     GCTraceTime tt("JNI Weak Reference", trace_time, false, gc_timer, gc_id);
   266     if (task_executor != NULL) {
   267       task_executor->set_single_threaded_mode();
   268     }
   269     process_phaseJNI(is_alive, keep_alive, complete_gc);
   270   }
   272   return ReferenceProcessorStats(soft_count, weak_count, final_count, phantom_count);
   273 }
   275 #ifndef PRODUCT
   276 // Calculate the number of jni handles.
   277 uint ReferenceProcessor::count_jni_refs() {
   278   class CountHandleClosure: public OopClosure {
   279   private:
   280     int _count;
   281   public:
   282     CountHandleClosure(): _count(0) {}
   283     void do_oop(oop* unused)       { _count++; }
   284     void do_oop(narrowOop* unused) { ShouldNotReachHere(); }
   285     int count() { return _count; }
   286   };
   287   CountHandleClosure global_handle_count;
   288   JNIHandles::weak_oops_do(&global_handle_count);
   289   return global_handle_count.count();
   290 }
   291 #endif
   293 void ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive,
   294                                           OopClosure*        keep_alive,
   295                                           VoidClosure*       complete_gc) {
   296 #ifndef PRODUCT
   297   if (PrintGCDetails && PrintReferenceGC) {
   298     unsigned int count = count_jni_refs();
   299     gclog_or_tty->print(", %u refs", count);
   300   }
   301 #endif
   302   JNIHandles::weak_oops_do(is_alive, keep_alive);
   303   complete_gc->do_void();
   304 }
   307 template <class T>
   308 bool enqueue_discovered_ref_helper(ReferenceProcessor* ref,
   309                                    AbstractRefProcTaskExecutor* task_executor) {
   311   // Remember old value of pending references list
   312   T* pending_list_addr = (T*)java_lang_ref_Reference::pending_list_addr();
   313   T old_pending_list_value = *pending_list_addr;
   315   // Enqueue references that are not made active again, and
   316   // clear the decks for the next collection (cycle).
   317   ref->enqueue_discovered_reflists((HeapWord*)pending_list_addr, task_executor);
   318   // Do the post-barrier on pending_list_addr missed in
   319   // enqueue_discovered_reflist.
   320   oopDesc::bs()->write_ref_field(pending_list_addr, oopDesc::load_decode_heap_oop(pending_list_addr));
   322   // Stop treating discovered references specially.
   323   ref->disable_discovery();
   325   // Return true if new pending references were added
   326   return old_pending_list_value != *pending_list_addr;
   327 }
   329 bool ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor) {
   330   NOT_PRODUCT(verify_ok_to_handle_reflists());
   331   if (UseCompressedOops) {
   332     return enqueue_discovered_ref_helper<narrowOop>(this, task_executor);
   333   } else {
   334     return enqueue_discovered_ref_helper<oop>(this, task_executor);
   335   }
   336 }
   338 void ReferenceProcessor::enqueue_discovered_reflist(DiscoveredList& refs_list,
   339                                                     HeapWord* pending_list_addr) {
   340   // Given a list of refs linked through the "discovered" field
   341   // (java.lang.ref.Reference.discovered), self-loop their "next" field
   342   // thus distinguishing them from active References, then
   343   // prepend them to the pending list.
   344   //
   345   // The Java threads will see the Reference objects linked together through
   346   // the discovered field. Instead of trying to do the write barrier updates
   347   // in all places in the reference processor where we manipulate the discovered
   348   // field we make sure to do the barrier here where we anyway iterate through
   349   // all linked Reference objects. Note that it is important to not dirty any
   350   // cards during reference processing since this will cause card table
   351   // verification to fail for G1.
   352   //
   353   // BKWRD COMPATIBILITY NOTE: For older JDKs (prior to the fix for 4956777),
   354   // the "next" field is used to chain the pending list, not the discovered
   355   // field.
   356   if (TraceReferenceGC && PrintGCDetails) {
   357     gclog_or_tty->print_cr("ReferenceProcessor::enqueue_discovered_reflist list "
   358                            INTPTR_FORMAT, (address)refs_list.head());
   359   }
   361   oop obj = NULL;
   362   oop next_d = refs_list.head();
   363   if (pending_list_uses_discovered_field()) { // New behavior
   364     // Walk down the list, self-looping the next field
   365     // so that the References are not considered active.
   366     while (obj != next_d) {
   367       obj = next_d;
   368       assert(obj->is_instanceRef(), "should be reference object");
   369       next_d = java_lang_ref_Reference::discovered(obj);
   370       if (TraceReferenceGC && PrintGCDetails) {
   371         gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT,
   372                                (void *)obj, (void *)next_d);
   373       }
   374       assert(java_lang_ref_Reference::next(obj) == NULL,
   375              "Reference not active; should not be discovered");
   376       // Self-loop next, so as to make Ref not active.
   377       java_lang_ref_Reference::set_next_raw(obj, obj);
   378       if (next_d != obj) {
   379         oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), next_d);
   380       } else {
   381         // This is the last object.
   382         // Swap refs_list into pending_list_addr and
   383         // set obj's discovered to what we read from pending_list_addr.
   384         oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
   385         // Need post-barrier on pending_list_addr. See enqueue_discovered_ref_helper() above.
   386         java_lang_ref_Reference::set_discovered_raw(obj, old); // old may be NULL
   387         oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), old);
   388       }
   389     }
   390   } else { // Old behaviour
   391     // Walk down the list, copying the discovered field into
   392     // the next field and clearing the discovered field.
   393     while (obj != next_d) {
   394       obj = next_d;
   395       assert(obj->is_instanceRef(), "should be reference object");
   396       next_d = java_lang_ref_Reference::discovered(obj);
   397       if (TraceReferenceGC && PrintGCDetails) {
   398         gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT,
   399                                (void *)obj, (void *)next_d);
   400       }
   401       assert(java_lang_ref_Reference::next(obj) == NULL,
   402              "The reference should not be enqueued");
   403       if (next_d == obj) {  // obj is last
   404         // Swap refs_list into pendling_list_addr and
   405         // set obj's next to what we read from pending_list_addr.
   406         oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
   407         // Need oop_check on pending_list_addr above;
   408         // see special oop-check code at the end of
   409         // enqueue_discovered_reflists() further below.
   410         if (old == NULL) {
   411           // obj should be made to point to itself, since
   412           // pending list was empty.
   413           java_lang_ref_Reference::set_next(obj, obj);
   414         } else {
   415           java_lang_ref_Reference::set_next(obj, old);
   416         }
   417       } else {
   418         java_lang_ref_Reference::set_next(obj, next_d);
   419       }
   420       java_lang_ref_Reference::set_discovered(obj, (oop) NULL);
   421     }
   422   }
   423 }
   425 // Parallel enqueue task
   426 class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask {
   427 public:
   428   RefProcEnqueueTask(ReferenceProcessor& ref_processor,
   429                      DiscoveredList      discovered_refs[],
   430                      HeapWord*           pending_list_addr,
   431                      int                 n_queues)
   432     : EnqueueTask(ref_processor, discovered_refs,
   433                   pending_list_addr, n_queues)
   434   { }
   436   virtual void work(unsigned int work_id) {
   437     assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds");
   438     // Simplest first cut: static partitioning.
   439     int index = work_id;
   440     // The increment on "index" must correspond to the maximum number of queues
   441     // (n_queues) with which that ReferenceProcessor was created.  That
   442     // is because of the "clever" way the discovered references lists were
   443     // allocated and are indexed into.
   444     assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected");
   445     for (int j = 0;
   446          j < ReferenceProcessor::number_of_subclasses_of_ref();
   447          j++, index += _n_queues) {
   448       _ref_processor.enqueue_discovered_reflist(
   449         _refs_lists[index], _pending_list_addr);
   450       _refs_lists[index].set_head(NULL);
   451       _refs_lists[index].set_length(0);
   452     }
   453   }
   454 };
   456 // Enqueue references that are not made active again
   457 void ReferenceProcessor::enqueue_discovered_reflists(HeapWord* pending_list_addr,
   458   AbstractRefProcTaskExecutor* task_executor) {
   459   if (_processing_is_mt && task_executor != NULL) {
   460     // Parallel code
   461     RefProcEnqueueTask tsk(*this, _discovered_refs,
   462                            pending_list_addr, _max_num_q);
   463     task_executor->execute(tsk);
   464   } else {
   465     // Serial code: call the parent class's implementation
   466     for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
   467       enqueue_discovered_reflist(_discovered_refs[i], pending_list_addr);
   468       _discovered_refs[i].set_head(NULL);
   469       _discovered_refs[i].set_length(0);
   470     }
   471   }
   472 }
   474 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
   475   _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref);
   476   oop discovered = java_lang_ref_Reference::discovered(_ref);
   477   assert(_discovered_addr && discovered->is_oop_or_null(),
   478          "discovered field is bad");
   479   _next = discovered;
   480   _referent_addr = java_lang_ref_Reference::referent_addr(_ref);
   481   _referent = java_lang_ref_Reference::referent(_ref);
   482   assert(Universe::heap()->is_in_reserved_or_null(_referent),
   483          "Wrong oop found in java.lang.Reference object");
   484   assert(allow_null_referent ?
   485              _referent->is_oop_or_null()
   486            : _referent->is_oop(),
   487          "bad referent");
   488 }
   490 void DiscoveredListIterator::remove() {
   491   assert(_ref->is_oop(), "Dropping a bad reference");
   492   oop_store_raw(_discovered_addr, NULL);
   494   // First _prev_next ref actually points into DiscoveredList (gross).
   495   oop new_next;
   496   if (_next == _ref) {
   497     // At the end of the list, we should make _prev point to itself.
   498     // If _ref is the first ref, then _prev_next will be in the DiscoveredList,
   499     // and _prev will be NULL.
   500     new_next = _prev;
   501   } else {
   502     new_next = _next;
   503   }
   504   // Remove Reference object from discovered list. Note that G1 does not need a
   505   // pre-barrier here because we know the Reference has already been found/marked,
   506   // that's how it ended up in the discovered list in the first place.
   507   oop_store_raw(_prev_next, new_next);
   508   NOT_PRODUCT(_removed++);
   509   _refs_list.dec_length(1);
   510 }
   512 // Make the Reference object active again.
   513 void DiscoveredListIterator::make_active() {
   514   // The pre barrier for G1 is probably just needed for the old
   515   // reference processing behavior. Should we guard this with
   516   // ReferenceProcessor::pending_list_uses_discovered_field() ?
   517   if (UseG1GC) {
   518     HeapWord* next_addr = java_lang_ref_Reference::next_addr(_ref);
   519     if (UseCompressedOops) {
   520       oopDesc::bs()->write_ref_field_pre((narrowOop*)next_addr, NULL);
   521     } else {
   522       oopDesc::bs()->write_ref_field_pre((oop*)next_addr, NULL);
   523     }
   524   }
   525   java_lang_ref_Reference::set_next_raw(_ref, NULL);
   526 }
   528 void DiscoveredListIterator::clear_referent() {
   529   oop_store_raw(_referent_addr, NULL);
   530 }
   532 // NOTE: process_phase*() are largely similar, and at a high level
   533 // merely iterate over the extant list applying a predicate to
   534 // each of its elements and possibly removing that element from the
   535 // list and applying some further closures to that element.
   536 // We should consider the possibility of replacing these
   537 // process_phase*() methods by abstracting them into
   538 // a single general iterator invocation that receives appropriate
   539 // closures that accomplish this work.
   541 // (SoftReferences only) Traverse the list and remove any SoftReferences whose
   542 // referents are not alive, but that should be kept alive for policy reasons.
   543 // Keep alive the transitive closure of all such referents.
   544 void
   545 ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
   546                                    ReferencePolicy*   policy,
   547                                    BoolObjectClosure* is_alive,
   548                                    OopClosure*        keep_alive,
   549                                    VoidClosure*       complete_gc) {
   550   assert(policy != NULL, "Must have a non-NULL policy");
   551   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
   552   // Decide which softly reachable refs should be kept alive.
   553   while (iter.has_next()) {
   554     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
   555     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
   556     if (referent_is_dead &&
   557         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
   558       if (TraceReferenceGC) {
   559         gclog_or_tty->print_cr("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
   560                                (void *)iter.obj(), iter.obj()->klass()->internal_name());
   561       }
   562       // Remove Reference object from list
   563       iter.remove();
   564       // Make the Reference object active again
   565       iter.make_active();
   566       // keep the referent around
   567       iter.make_referent_alive();
   568       iter.move_to_next();
   569     } else {
   570       iter.next();
   571     }
   572   }
   573   // Close the reachable set
   574   complete_gc->do_void();
   575   NOT_PRODUCT(
   576     if (PrintGCDetails && TraceReferenceGC) {
   577       gclog_or_tty->print_cr(" Dropped %d dead Refs out of %d "
   578         "discovered Refs by policy, from list " INTPTR_FORMAT,
   579         iter.removed(), iter.processed(), (address)refs_list.head());
   580     }
   581   )
   582 }
   584 // Traverse the list and remove any Refs that are not active, or
   585 // whose referents are either alive or NULL.
   586 void
   587 ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
   588                              BoolObjectClosure* is_alive,
   589                              OopClosure*        keep_alive) {
   590   assert(discovery_is_atomic(), "Error");
   591   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
   592   while (iter.has_next()) {
   593     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
   594     DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
   595     assert(next == NULL, "Should not discover inactive Reference");
   596     if (iter.is_referent_alive()) {
   597       if (TraceReferenceGC) {
   598         gclog_or_tty->print_cr("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
   599                                (void *)iter.obj(), iter.obj()->klass()->internal_name());
   600       }
   601       // The referent is reachable after all.
   602       // Remove Reference object from list.
   603       iter.remove();
   604       // Update the referent pointer as necessary: Note that this
   605       // should not entail any recursive marking because the
   606       // referent must already have been traversed.
   607       iter.make_referent_alive();
   608       iter.move_to_next();
   609     } else {
   610       iter.next();
   611     }
   612   }
   613   NOT_PRODUCT(
   614     if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
   615       gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
   616         "Refs in discovered list " INTPTR_FORMAT,
   617         iter.removed(), iter.processed(), (address)refs_list.head());
   618     }
   619   )
   620 }
   622 void
   623 ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList&    refs_list,
   624                                                   BoolObjectClosure* is_alive,
   625                                                   OopClosure*        keep_alive,
   626                                                   VoidClosure*       complete_gc) {
   627   assert(!discovery_is_atomic(), "Error");
   628   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
   629   while (iter.has_next()) {
   630     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
   631     HeapWord* next_addr = java_lang_ref_Reference::next_addr(iter.obj());
   632     oop next = java_lang_ref_Reference::next(iter.obj());
   633     if ((iter.referent() == NULL || iter.is_referent_alive() ||
   634          next != NULL)) {
   635       assert(next->is_oop_or_null(), "bad next field");
   636       // Remove Reference object from list
   637       iter.remove();
   638       // Trace the cohorts
   639       iter.make_referent_alive();
   640       if (UseCompressedOops) {
   641         keep_alive->do_oop((narrowOop*)next_addr);
   642       } else {
   643         keep_alive->do_oop((oop*)next_addr);
   644       }
   645       iter.move_to_next();
   646     } else {
   647       iter.next();
   648     }
   649   }
   650   // Now close the newly reachable set
   651   complete_gc->do_void();
   652   NOT_PRODUCT(
   653     if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
   654       gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
   655         "Refs in discovered list " INTPTR_FORMAT,
   656         iter.removed(), iter.processed(), (address)refs_list.head());
   657     }
   658   )
   659 }
   661 // Traverse the list and process the referents, by either
   662 // clearing them or keeping them (and their reachable
   663 // closure) alive.
   664 void
   665 ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
   666                                    bool               clear_referent,
   667                                    BoolObjectClosure* is_alive,
   668                                    OopClosure*        keep_alive,
   669                                    VoidClosure*       complete_gc) {
   670   ResourceMark rm;
   671   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
   672   while (iter.has_next()) {
   673     iter.update_discovered();
   674     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
   675     if (clear_referent) {
   676       // NULL out referent pointer
   677       iter.clear_referent();
   678     } else {
   679       // keep the referent around
   680       iter.make_referent_alive();
   681     }
   682     if (TraceReferenceGC) {
   683       gclog_or_tty->print_cr("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
   684                              clear_referent ? "cleared " : "",
   685                              (void *)iter.obj(), iter.obj()->klass()->internal_name());
   686     }
   687     assert(iter.obj()->is_oop(UseConcMarkSweepGC), "Adding a bad reference");
   688     iter.next();
   689   }
   690   // Remember to update the next pointer of the last ref.
   691   iter.update_discovered();
   692   // Close the reachable set
   693   complete_gc->do_void();
   694 }
   696 void
   697 ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) {
   698   oop obj = NULL;
   699   oop next = refs_list.head();
   700   while (next != obj) {
   701     obj = next;
   702     next = java_lang_ref_Reference::discovered(obj);
   703     java_lang_ref_Reference::set_discovered_raw(obj, NULL);
   704   }
   705   refs_list.set_head(NULL);
   706   refs_list.set_length(0);
   707 }
   709 void
   710 ReferenceProcessor::abandon_partial_discovered_list(DiscoveredList& refs_list) {
   711   clear_discovered_references(refs_list);
   712 }
   714 void ReferenceProcessor::abandon_partial_discovery() {
   715   // loop over the lists
   716   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
   717     if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
   718       gclog_or_tty->print_cr("\nAbandoning %s discovered list", list_name(i));
   719     }
   720     abandon_partial_discovered_list(_discovered_refs[i]);
   721   }
   722 }
   724 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
   725 public:
   726   RefProcPhase1Task(ReferenceProcessor& ref_processor,
   727                     DiscoveredList      refs_lists[],
   728                     ReferencePolicy*    policy,
   729                     bool                marks_oops_alive)
   730     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
   731       _policy(policy)
   732   { }
   733   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
   734                     OopClosure& keep_alive,
   735                     VoidClosure& complete_gc)
   736   {
   737     Thread* thr = Thread::current();
   738     int refs_list_index = ((WorkerThread*)thr)->id();
   739     _ref_processor.process_phase1(_refs_lists[refs_list_index], _policy,
   740                                   &is_alive, &keep_alive, &complete_gc);
   741   }
   742 private:
   743   ReferencePolicy* _policy;
   744 };
   746 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
   747 public:
   748   RefProcPhase2Task(ReferenceProcessor& ref_processor,
   749                     DiscoveredList      refs_lists[],
   750                     bool                marks_oops_alive)
   751     : ProcessTask(ref_processor, refs_lists, marks_oops_alive)
   752   { }
   753   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
   754                     OopClosure& keep_alive,
   755                     VoidClosure& complete_gc)
   756   {
   757     _ref_processor.process_phase2(_refs_lists[i],
   758                                   &is_alive, &keep_alive, &complete_gc);
   759   }
   760 };
   762 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
   763 public:
   764   RefProcPhase3Task(ReferenceProcessor& ref_processor,
   765                     DiscoveredList      refs_lists[],
   766                     bool                clear_referent,
   767                     bool                marks_oops_alive)
   768     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
   769       _clear_referent(clear_referent)
   770   { }
   771   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
   772                     OopClosure& keep_alive,
   773                     VoidClosure& complete_gc)
   774   {
   775     // Don't use "refs_list_index" calculated in this way because
   776     // balance_queues() has moved the Ref's into the first n queues.
   777     // Thread* thr = Thread::current();
   778     // int refs_list_index = ((WorkerThread*)thr)->id();
   779     // _ref_processor.process_phase3(_refs_lists[refs_list_index], _clear_referent,
   780     _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
   781                                   &is_alive, &keep_alive, &complete_gc);
   782   }
   783 private:
   784   bool _clear_referent;
   785 };
   787 // Balances reference queues.
   788 // Move entries from all queues[0, 1, ..., _max_num_q-1] to
   789 // queues[0, 1, ..., _num_q-1] because only the first _num_q
   790 // corresponding to the active workers will be processed.
   791 void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
   792 {
   793   // calculate total length
   794   size_t total_refs = 0;
   795   if (TraceReferenceGC && PrintGCDetails) {
   796     gclog_or_tty->print_cr("\nBalance ref_lists ");
   797   }
   799   for (uint i = 0; i < _max_num_q; ++i) {
   800     total_refs += ref_lists[i].length();
   801     if (TraceReferenceGC && PrintGCDetails) {
   802       gclog_or_tty->print("%d ", ref_lists[i].length());
   803     }
   804   }
   805   if (TraceReferenceGC && PrintGCDetails) {
   806     gclog_or_tty->print_cr(" = %d", total_refs);
   807   }
   808   size_t avg_refs = total_refs / _num_q + 1;
   809   uint to_idx = 0;
   810   for (uint from_idx = 0; from_idx < _max_num_q; from_idx++) {
   811     bool move_all = false;
   812     if (from_idx >= _num_q) {
   813       move_all = ref_lists[from_idx].length() > 0;
   814     }
   815     while ((ref_lists[from_idx].length() > avg_refs) ||
   816            move_all) {
   817       assert(to_idx < _num_q, "Sanity Check!");
   818       if (ref_lists[to_idx].length() < avg_refs) {
   819         // move superfluous refs
   820         size_t refs_to_move;
   821         // Move all the Ref's if the from queue will not be processed.
   822         if (move_all) {
   823           refs_to_move = MIN2(ref_lists[from_idx].length(),
   824                               avg_refs - ref_lists[to_idx].length());
   825         } else {
   826           refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
   827                               avg_refs - ref_lists[to_idx].length());
   828         }
   830         assert(refs_to_move > 0, "otherwise the code below will fail");
   832         oop move_head = ref_lists[from_idx].head();
   833         oop move_tail = move_head;
   834         oop new_head  = move_head;
   835         // find an element to split the list on
   836         for (size_t j = 0; j < refs_to_move; ++j) {
   837           move_tail = new_head;
   838           new_head = java_lang_ref_Reference::discovered(new_head);
   839         }
   841         // Add the chain to the to list.
   842         if (ref_lists[to_idx].head() == NULL) {
   843           // to list is empty. Make a loop at the end.
   844           java_lang_ref_Reference::set_discovered_raw(move_tail, move_tail);
   845         } else {
   846           java_lang_ref_Reference::set_discovered_raw(move_tail, ref_lists[to_idx].head());
   847         }
   848         ref_lists[to_idx].set_head(move_head);
   849         ref_lists[to_idx].inc_length(refs_to_move);
   851         // Remove the chain from the from list.
   852         if (move_tail == new_head) {
   853           // We found the end of the from list.
   854           ref_lists[from_idx].set_head(NULL);
   855         } else {
   856           ref_lists[from_idx].set_head(new_head);
   857         }
   858         ref_lists[from_idx].dec_length(refs_to_move);
   859         if (ref_lists[from_idx].length() == 0) {
   860           break;
   861         }
   862       } else {
   863         to_idx = (to_idx + 1) % _num_q;
   864       }
   865     }
   866   }
   867 #ifdef ASSERT
   868   size_t balanced_total_refs = 0;
   869   for (uint i = 0; i < _max_num_q; ++i) {
   870     balanced_total_refs += ref_lists[i].length();
   871     if (TraceReferenceGC && PrintGCDetails) {
   872       gclog_or_tty->print("%d ", ref_lists[i].length());
   873     }
   874   }
   875   if (TraceReferenceGC && PrintGCDetails) {
   876     gclog_or_tty->print_cr(" = %d", balanced_total_refs);
   877     gclog_or_tty->flush();
   878   }
   879   assert(total_refs == balanced_total_refs, "Balancing was incomplete");
   880 #endif
   881 }
   883 void ReferenceProcessor::balance_all_queues() {
   884   balance_queues(_discoveredSoftRefs);
   885   balance_queues(_discoveredWeakRefs);
   886   balance_queues(_discoveredFinalRefs);
   887   balance_queues(_discoveredPhantomRefs);
   888   balance_queues(_discoveredCleanerRefs);
   889 }
   891 size_t
   892 ReferenceProcessor::process_discovered_reflist(
   893   DiscoveredList               refs_lists[],
   894   ReferencePolicy*             policy,
   895   bool                         clear_referent,
   896   BoolObjectClosure*           is_alive,
   897   OopClosure*                  keep_alive,
   898   VoidClosure*                 complete_gc,
   899   AbstractRefProcTaskExecutor* task_executor)
   900 {
   901   bool mt_processing = task_executor != NULL && _processing_is_mt;
   902   // If discovery used MT and a dynamic number of GC threads, then
   903   // the queues must be balanced for correctness if fewer than the
   904   // maximum number of queues were used.  The number of queue used
   905   // during discovery may be different than the number to be used
   906   // for processing so don't depend of _num_q < _max_num_q as part
   907   // of the test.
   908   bool must_balance = _discovery_is_mt;
   910   if ((mt_processing && ParallelRefProcBalancingEnabled) ||
   911       must_balance) {
   912     balance_queues(refs_lists);
   913   }
   915   size_t total_list_count = total_count(refs_lists);
   917   if (PrintReferenceGC && PrintGCDetails) {
   918     gclog_or_tty->print(", %u refs", total_list_count);
   919   }
   921   // Phase 1 (soft refs only):
   922   // . Traverse the list and remove any SoftReferences whose
   923   //   referents are not alive, but that should be kept alive for
   924   //   policy reasons. Keep alive the transitive closure of all
   925   //   such referents.
   926   if (policy != NULL) {
   927     if (mt_processing) {
   928       RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/);
   929       task_executor->execute(phase1);
   930     } else {
   931       for (uint i = 0; i < _max_num_q; i++) {
   932         process_phase1(refs_lists[i], policy,
   933                        is_alive, keep_alive, complete_gc);
   934       }
   935     }
   936   } else { // policy == NULL
   937     assert(refs_lists != _discoveredSoftRefs,
   938            "Policy must be specified for soft references.");
   939   }
   941   // Phase 2:
   942   // . Traverse the list and remove any refs whose referents are alive.
   943   if (mt_processing) {
   944     RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/);
   945     task_executor->execute(phase2);
   946   } else {
   947     for (uint i = 0; i < _max_num_q; i++) {
   948       process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
   949     }
   950   }
   952   // Phase 3:
   953   // . Traverse the list and process referents as appropriate.
   954   if (mt_processing) {
   955     RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/);
   956     task_executor->execute(phase3);
   957   } else {
   958     for (uint i = 0; i < _max_num_q; i++) {
   959       process_phase3(refs_lists[i], clear_referent,
   960                      is_alive, keep_alive, complete_gc);
   961     }
   962   }
   964   return total_list_count;
   965 }
   967 void ReferenceProcessor::clean_up_discovered_references() {
   968   // loop over the lists
   969   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
   970     if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
   971       gclog_or_tty->print_cr(
   972         "\nScrubbing %s discovered list of Null referents",
   973         list_name(i));
   974     }
   975     clean_up_discovered_reflist(_discovered_refs[i]);
   976   }
   977 }
   979 void ReferenceProcessor::clean_up_discovered_reflist(DiscoveredList& refs_list) {
   980   assert(!discovery_is_atomic(), "Else why call this method?");
   981   DiscoveredListIterator iter(refs_list, NULL, NULL);
   982   while (iter.has_next()) {
   983     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
   984     oop next = java_lang_ref_Reference::next(iter.obj());
   985     assert(next->is_oop_or_null(), "bad next field");
   986     // If referent has been cleared or Reference is not active,
   987     // drop it.
   988     if (iter.referent() == NULL || next != NULL) {
   989       debug_only(
   990         if (PrintGCDetails && TraceReferenceGC) {
   991           gclog_or_tty->print_cr("clean_up_discovered_list: Dropping Reference: "
   992             INTPTR_FORMAT " with next field: " INTPTR_FORMAT
   993             " and referent: " INTPTR_FORMAT,
   994             (void *)iter.obj(), (void *)next, (void *)iter.referent());
   995         }
   996       )
   997       // Remove Reference object from list
   998       iter.remove();
   999       iter.move_to_next();
  1000     } else {
  1001       iter.next();
  1004   NOT_PRODUCT(
  1005     if (PrintGCDetails && TraceReferenceGC) {
  1006       gclog_or_tty->print(
  1007         " Removed %d Refs with NULL referents out of %d discovered Refs",
  1008         iter.removed(), iter.processed());
  1013 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
  1014   uint id = 0;
  1015   // Determine the queue index to use for this object.
  1016   if (_discovery_is_mt) {
  1017     // During a multi-threaded discovery phase,
  1018     // each thread saves to its "own" list.
  1019     Thread* thr = Thread::current();
  1020     id = thr->as_Worker_thread()->id();
  1021   } else {
  1022     // single-threaded discovery, we save in round-robin
  1023     // fashion to each of the lists.
  1024     if (_processing_is_mt) {
  1025       id = next_id();
  1028   assert(0 <= id && id < _max_num_q, "Id is out-of-bounds (call Freud?)");
  1030   // Get the discovered queue to which we will add
  1031   DiscoveredList* list = NULL;
  1032   switch (rt) {
  1033     case REF_OTHER:
  1034       // Unknown reference type, no special treatment
  1035       break;
  1036     case REF_SOFT:
  1037       list = &_discoveredSoftRefs[id];
  1038       break;
  1039     case REF_WEAK:
  1040       list = &_discoveredWeakRefs[id];
  1041       break;
  1042     case REF_FINAL:
  1043       list = &_discoveredFinalRefs[id];
  1044       break;
  1045     case REF_PHANTOM:
  1046       list = &_discoveredPhantomRefs[id];
  1047       break;
  1048     case REF_CLEANER:
  1049       list = &_discoveredCleanerRefs[id];
  1050       break;
  1051     case REF_NONE:
  1052       // we should not reach here if we are an InstanceRefKlass
  1053     default:
  1054       ShouldNotReachHere();
  1056   if (TraceReferenceGC && PrintGCDetails) {
  1057     gclog_or_tty->print_cr("Thread %d gets list " INTPTR_FORMAT, id, list);
  1059   return list;
  1062 inline void
  1063 ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
  1064                                               oop             obj,
  1065                                               HeapWord*       discovered_addr) {
  1066   assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
  1067   // First we must make sure this object is only enqueued once. CAS in a non null
  1068   // discovered_addr.
  1069   oop current_head = refs_list.head();
  1070   // The last ref must have its discovered field pointing to itself.
  1071   oop next_discovered = (current_head != NULL) ? current_head : obj;
  1073   oop retest = oopDesc::atomic_compare_exchange_oop(next_discovered, discovered_addr,
  1074                                                     NULL);
  1075   if (retest == NULL) {
  1076     // This thread just won the right to enqueue the object.
  1077     // We have separate lists for enqueueing, so no synchronization
  1078     // is necessary.
  1079     refs_list.set_head(obj);
  1080     refs_list.inc_length(1);
  1082     if (TraceReferenceGC) {
  1083       gclog_or_tty->print_cr("Discovered reference (mt) (" INTPTR_FORMAT ": %s)",
  1084                              (void *)obj, obj->klass()->internal_name());
  1086   } else {
  1087     // If retest was non NULL, another thread beat us to it:
  1088     // The reference has already been discovered...
  1089     if (TraceReferenceGC) {
  1090       gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
  1091                              (void *)obj, obj->klass()->internal_name());
  1096 #ifndef PRODUCT
  1097 // Non-atomic (i.e. concurrent) discovery might allow us
  1098 // to observe j.l.References with NULL referents, being those
  1099 // cleared concurrently by mutators during (or after) discovery.
  1100 void ReferenceProcessor::verify_referent(oop obj) {
  1101   bool da = discovery_is_atomic();
  1102   oop referent = java_lang_ref_Reference::referent(obj);
  1103   assert(da ? referent->is_oop() : referent->is_oop_or_null(),
  1104          err_msg("Bad referent " INTPTR_FORMAT " found in Reference "
  1105                  INTPTR_FORMAT " during %satomic discovery ",
  1106                  (void *)referent, (void *)obj, da ? "" : "non-"));
  1108 #endif
  1110 // We mention two of several possible choices here:
  1111 // #0: if the reference object is not in the "originating generation"
  1112 //     (or part of the heap being collected, indicated by our "span"
  1113 //     we don't treat it specially (i.e. we scan it as we would
  1114 //     a normal oop, treating its references as strong references).
  1115 //     This means that references can't be discovered unless their
  1116 //     referent is also in the same span. This is the simplest,
  1117 //     most "local" and most conservative approach, albeit one
  1118 //     that may cause weak references to be enqueued least promptly.
  1119 //     We call this choice the "ReferenceBasedDiscovery" policy.
  1120 // #1: the reference object may be in any generation (span), but if
  1121 //     the referent is in the generation (span) being currently collected
  1122 //     then we can discover the reference object, provided
  1123 //     the object has not already been discovered by
  1124 //     a different concurrently running collector (as may be the
  1125 //     case, for instance, if the reference object is in CMS and
  1126 //     the referent in DefNewGeneration), and provided the processing
  1127 //     of this reference object by the current collector will
  1128 //     appear atomic to every other collector in the system.
  1129 //     (Thus, for instance, a concurrent collector may not
  1130 //     discover references in other generations even if the
  1131 //     referent is in its own generation). This policy may,
  1132 //     in certain cases, enqueue references somewhat sooner than
  1133 //     might Policy #0 above, but at marginally increased cost
  1134 //     and complexity in processing these references.
  1135 //     We call this choice the "RefeferentBasedDiscovery" policy.
  1136 bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) {
  1137   // Make sure we are discovering refs (rather than processing discovered refs).
  1138   if (!_discovering_refs || !RegisterReferences) {
  1139     return false;
  1141   // We only discover active references.
  1142   oop next = java_lang_ref_Reference::next(obj);
  1143   if (next != NULL) {   // Ref is no longer active
  1144     return false;
  1147   HeapWord* obj_addr = (HeapWord*)obj;
  1148   if (RefDiscoveryPolicy == ReferenceBasedDiscovery &&
  1149       !_span.contains(obj_addr)) {
  1150     // Reference is not in the originating generation;
  1151     // don't treat it specially (i.e. we want to scan it as a normal
  1152     // object with strong references).
  1153     return false;
  1156   // We only discover references whose referents are not (yet)
  1157   // known to be strongly reachable.
  1158   if (is_alive_non_header() != NULL) {
  1159     verify_referent(obj);
  1160     if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) {
  1161       return false;  // referent is reachable
  1164   if (rt == REF_SOFT) {
  1165     // For soft refs we can decide now if these are not
  1166     // current candidates for clearing, in which case we
  1167     // can mark through them now, rather than delaying that
  1168     // to the reference-processing phase. Since all current
  1169     // time-stamp policies advance the soft-ref clock only
  1170     // at a major collection cycle, this is always currently
  1171     // accurate.
  1172     if (!_current_soft_ref_policy->should_clear_reference(obj, _soft_ref_timestamp_clock)) {
  1173       return false;
  1177   ResourceMark rm;      // Needed for tracing.
  1179   HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr(obj);
  1180   const oop  discovered = java_lang_ref_Reference::discovered(obj);
  1181   assert(discovered->is_oop_or_null(), "bad discovered field");
  1182   if (discovered != NULL) {
  1183     // The reference has already been discovered...
  1184     if (TraceReferenceGC) {
  1185       gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
  1186                              (void *)obj, obj->klass()->internal_name());
  1188     if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
  1189       // assumes that an object is not processed twice;
  1190       // if it's been already discovered it must be on another
  1191       // generation's discovered list; so we won't discover it.
  1192       return false;
  1193     } else {
  1194       assert(RefDiscoveryPolicy == ReferenceBasedDiscovery,
  1195              "Unrecognized policy");
  1196       // Check assumption that an object is not potentially
  1197       // discovered twice except by concurrent collectors that potentially
  1198       // trace the same Reference object twice.
  1199       assert(UseConcMarkSweepGC || UseG1GC,
  1200              "Only possible with a concurrent marking collector");
  1201       return true;
  1205   if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
  1206     verify_referent(obj);
  1207     // Discover if and only if EITHER:
  1208     // .. reference is in our span, OR
  1209     // .. we are an atomic collector and referent is in our span
  1210     if (_span.contains(obj_addr) ||
  1211         (discovery_is_atomic() &&
  1212          _span.contains(java_lang_ref_Reference::referent(obj)))) {
  1213       // should_enqueue = true;
  1214     } else {
  1215       return false;
  1217   } else {
  1218     assert(RefDiscoveryPolicy == ReferenceBasedDiscovery &&
  1219            _span.contains(obj_addr), "code inconsistency");
  1222   // Get the right type of discovered queue head.
  1223   DiscoveredList* list = get_discovered_list(rt);
  1224   if (list == NULL) {
  1225     return false;   // nothing special needs to be done
  1228   if (_discovery_is_mt) {
  1229     add_to_discovered_list_mt(*list, obj, discovered_addr);
  1230   } else {
  1231     // We do a raw store here: the field will be visited later when processing
  1232     // the discovered references.
  1233     oop current_head = list->head();
  1234     // The last ref must have its discovered field pointing to itself.
  1235     oop next_discovered = (current_head != NULL) ? current_head : obj;
  1237     assert(discovered == NULL, "control point invariant");
  1238     oop_store_raw(discovered_addr, next_discovered);
  1239     list->set_head(obj);
  1240     list->inc_length(1);
  1242     if (TraceReferenceGC) {
  1243       gclog_or_tty->print_cr("Discovered reference (" INTPTR_FORMAT ": %s)",
  1244                                 (void *)obj, obj->klass()->internal_name());
  1247   assert(obj->is_oop(), "Discovered a bad reference");
  1248   verify_referent(obj);
  1249   return true;
  1252 // Preclean the discovered references by removing those
  1253 // whose referents are alive, and by marking from those that
  1254 // are not active. These lists can be handled here
  1255 // in any order and, indeed, concurrently.
  1256 void ReferenceProcessor::preclean_discovered_references(
  1257   BoolObjectClosure* is_alive,
  1258   OopClosure* keep_alive,
  1259   VoidClosure* complete_gc,
  1260   YieldClosure* yield,
  1261   GCTimer* gc_timer,
  1262   GCId     gc_id) {
  1264   NOT_PRODUCT(verify_ok_to_handle_reflists());
  1266   // Soft references
  1268     GCTraceTime tt("Preclean SoftReferences", PrintGCDetails && PrintReferenceGC,
  1269               false, gc_timer, gc_id);
  1270     for (uint i = 0; i < _max_num_q; i++) {
  1271       if (yield->should_return()) {
  1272         return;
  1274       preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive,
  1275                                   keep_alive, complete_gc, yield);
  1279   // Weak references
  1281     GCTraceTime tt("Preclean WeakReferences", PrintGCDetails && PrintReferenceGC,
  1282               false, gc_timer, gc_id);
  1283     for (uint i = 0; i < _max_num_q; i++) {
  1284       if (yield->should_return()) {
  1285         return;
  1287       preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive,
  1288                                   keep_alive, complete_gc, yield);
  1292   // Final references
  1294     GCTraceTime tt("Preclean FinalReferences", PrintGCDetails && PrintReferenceGC,
  1295               false, gc_timer, gc_id);
  1296     for (uint i = 0; i < _max_num_q; i++) {
  1297       if (yield->should_return()) {
  1298         return;
  1300       preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive,
  1301                                   keep_alive, complete_gc, yield);
  1305   // Phantom references
  1307     GCTraceTime tt("Preclean PhantomReferences", PrintGCDetails && PrintReferenceGC,
  1308               false, gc_timer, gc_id);
  1309     for (uint i = 0; i < _max_num_q; i++) {
  1310       if (yield->should_return()) {
  1311         return;
  1313       preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive,
  1314                                   keep_alive, complete_gc, yield);
  1317     // Cleaner references.  Included in timing for phantom references.  We
  1318     // expect Cleaner references to be temporary, and don't want to deal with
  1319     // possible incompatibilities arising from making it more visible.
  1320     for (uint i = 0; i < _max_num_q; i++) {
  1321       if (yield->should_return()) {
  1322         return;
  1324       preclean_discovered_reflist(_discoveredCleanerRefs[i], is_alive,
  1325                                   keep_alive, complete_gc, yield);
  1330 // Walk the given discovered ref list, and remove all reference objects
  1331 // whose referents are still alive, whose referents are NULL or which
  1332 // are not active (have a non-NULL next field). NOTE: When we are
  1333 // thus precleaning the ref lists (which happens single-threaded today),
  1334 // we do not disable refs discovery to honour the correct semantics of
  1335 // java.lang.Reference. As a result, we need to be careful below
  1336 // that ref removal steps interleave safely with ref discovery steps
  1337 // (in this thread).
  1338 void
  1339 ReferenceProcessor::preclean_discovered_reflist(DiscoveredList&    refs_list,
  1340                                                 BoolObjectClosure* is_alive,
  1341                                                 OopClosure*        keep_alive,
  1342                                                 VoidClosure*       complete_gc,
  1343                                                 YieldClosure*      yield) {
  1344   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
  1345   while (iter.has_next()) {
  1346     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
  1347     oop obj = iter.obj();
  1348     oop next = java_lang_ref_Reference::next(obj);
  1349     if (iter.referent() == NULL || iter.is_referent_alive() ||
  1350         next != NULL) {
  1351       // The referent has been cleared, or is alive, or the Reference is not
  1352       // active; we need to trace and mark its cohort.
  1353       if (TraceReferenceGC) {
  1354         gclog_or_tty->print_cr("Precleaning Reference (" INTPTR_FORMAT ": %s)",
  1355                                (void *)iter.obj(), iter.obj()->klass()->internal_name());
  1357       // Remove Reference object from list
  1358       iter.remove();
  1359       // Keep alive its cohort.
  1360       iter.make_referent_alive();
  1361       if (UseCompressedOops) {
  1362         narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr(obj);
  1363         keep_alive->do_oop(next_addr);
  1364       } else {
  1365         oop* next_addr = (oop*)java_lang_ref_Reference::next_addr(obj);
  1366         keep_alive->do_oop(next_addr);
  1368       iter.move_to_next();
  1369     } else {
  1370       iter.next();
  1373   // Close the reachable set
  1374   complete_gc->do_void();
  1376   NOT_PRODUCT(
  1377     if (PrintGCDetails && PrintReferenceGC && (iter.processed() > 0)) {
  1378       gclog_or_tty->print_cr(" Dropped %d Refs out of %d "
  1379         "Refs in discovered list " INTPTR_FORMAT,
  1380         iter.removed(), iter.processed(), (address)refs_list.head());
  1385 const char* ReferenceProcessor::list_name(uint i) {
  1386    assert(i >= 0 && i <= _max_num_q * number_of_subclasses_of_ref(),
  1387           "Out of bounds index");
  1389    int j = i / _max_num_q;
  1390    switch (j) {
  1391      case 0: return "SoftRef";
  1392      case 1: return "WeakRef";
  1393      case 2: return "FinalRef";
  1394      case 3: return "PhantomRef";
  1395      case 4: return "CleanerRef";
  1397    ShouldNotReachHere();
  1398    return NULL;
  1401 #ifndef PRODUCT
  1402 void ReferenceProcessor::verify_ok_to_handle_reflists() {
  1403   // empty for now
  1405 #endif
  1407 #ifndef PRODUCT
  1408 void ReferenceProcessor::clear_discovered_references() {
  1409   guarantee(!_discovering_refs, "Discovering refs?");
  1410   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
  1411     clear_discovered_references(_discovered_refs[i]);
  1415 #endif // PRODUCT

mercurial