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