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     // Process cleaners, but include them in phantom statistics.  We expect
 247     // Cleaner references to be temporary, and don't want to deal with
 248     // possible incompatibilities arising from making it more visible.
 249     phantom_count +=
 250       process_discovered_reflist(_discoveredCleanerRefs, NULL, true,
 251                                  is_alive, keep_alive, complete_gc, task_executor);
 252   }
 253 
 254   // Weak global JNI references. It would make more sense (semantically) to
 255   // traverse these simultaneously with the regular weak references above, but
 256   // that is not how the JDK1.2 specification is. See #4126360. Native code can
 257   // thus use JNI weak references to circumvent the phantom references and
 258   // resurrect a "post-mortem" object.
 259   {
 260     GCTraceTime tt("JNI Weak Reference", trace_time, false, gc_timer, gc_id);
 261     if (task_executor != NULL) {
 262       task_executor->set_single_threaded_mode();
 263     }
 264     process_phaseJNI(is_alive, keep_alive, complete_gc);
 265   }
 266 
 267   return ReferenceProcessorStats(soft_count, weak_count, final_count, phantom_count);
 268 }
 269 
 270 #ifndef PRODUCT
 271 // Calculate the number of jni handles.
 272 uint ReferenceProcessor::count_jni_refs() {
 273   class AlwaysAliveClosure: public BoolObjectClosure {
 274   public:
 275     virtual bool do_object_b(oop obj) { return true; }
 276   };
 277 
 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   AlwaysAliveClosure always_alive;
 289   JNIHandles::weak_oops_do(&always_alive, &global_handle_count);
 290   return global_handle_count.count();
 291 }
 292 #endif
 293 
 294 void ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive,
 295                                           OopClosure*        keep_alive,
 296                                           VoidClosure*       complete_gc) {
 297 #ifndef PRODUCT
 298   if (PrintGCDetails && PrintReferenceGC) {
 299     unsigned int count = count_jni_refs();
 300     gclog_or_tty->print(", %u refs", count);
 301   }
 302 #endif
 303   JNIHandles::weak_oops_do(is_alive, keep_alive);
 304   complete_gc->do_void();
 305 }
 306 
 307 
 308 template <class T>
 309 bool enqueue_discovered_ref_helper(ReferenceProcessor* ref,
 310                                    AbstractRefProcTaskExecutor* task_executor) {
 311 
 312   // Remember old value of pending references list
 313   T* pending_list_addr = (T*)java_lang_ref_Reference::pending_list_addr();
 314   T old_pending_list_value = *pending_list_addr;
 315 
 316   // Enqueue references that are not made active again, and
 317   // clear the decks for the next collection (cycle).
 318   ref->enqueue_discovered_reflists((HeapWord*)pending_list_addr, task_executor);
 319   // Do the post-barrier on pending_list_addr missed in
 320   // enqueue_discovered_reflist.
 321   oopDesc::bs()->write_ref_field(pending_list_addr, oopDesc::load_decode_heap_oop(pending_list_addr));
 322 
 323   // Stop treating discovered references specially.
 324   ref->disable_discovery();
 325 
 326   // Return true if new pending references were added
 327   return old_pending_list_value != *pending_list_addr;
 328 }
 329 
 330 bool ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor) {
 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 }
 337 
 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   if (TraceReferenceGC && PrintGCDetails) {
 353     gclog_or_tty->print_cr("ReferenceProcessor::enqueue_discovered_reflist list "
 354                            INTPTR_FORMAT, p2i(refs_list.head()));
 355   }
 356 
 357   oop obj = NULL;
 358   oop next_d = refs_list.head();
 359   // Walk down the list, self-looping the next field
 360   // so that the References are not considered active.
 361   while (obj != next_d) {
 362     obj = next_d;
 363     assert(obj->is_instanceRef(), "should be reference object");
 364     next_d = java_lang_ref_Reference::discovered(obj);
 365     if (TraceReferenceGC && PrintGCDetails) {
 366       gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT,
 367                              p2i(obj), p2i(next_d));
 368     }
 369     assert(java_lang_ref_Reference::next(obj) == NULL,
 370            "Reference not active; should not be discovered");
 371     // Self-loop next, so as to make Ref not active.
 372     java_lang_ref_Reference::set_next_raw(obj, obj);
 373     if (next_d != obj) {
 374       oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), next_d);
 375     } else {
 376       // This is the last object.
 377       // Swap refs_list into pending_list_addr and
 378       // set obj's discovered to what we read from pending_list_addr.
 379       oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
 380       // Need post-barrier on pending_list_addr. See enqueue_discovered_ref_helper() above.
 381       java_lang_ref_Reference::set_discovered_raw(obj, old); // old may be NULL
 382       oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), old);
 383     }
 384   }
 385 }
 386 
 387 // Parallel enqueue task
 388 class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask {
 389 public:
 390   RefProcEnqueueTask(ReferenceProcessor& ref_processor,
 391                      DiscoveredList      discovered_refs[],
 392                      HeapWord*           pending_list_addr,
 393                      int                 n_queues)
 394     : EnqueueTask(ref_processor, discovered_refs,
 395                   pending_list_addr, n_queues)
 396   { }
 397 
 398   virtual void work(unsigned int work_id) {
 399     assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds");
 400     // Simplest first cut: static partitioning.
 401     int index = work_id;
 402     // The increment on "index" must correspond to the maximum number of queues
 403     // (n_queues) with which that ReferenceProcessor was created.  That
 404     // is because of the "clever" way the discovered references lists were
 405     // allocated and are indexed into.
 406     assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected");
 407     for (int j = 0;
 408          j < ReferenceProcessor::number_of_subclasses_of_ref();
 409          j++, index += _n_queues) {
 410       _ref_processor.enqueue_discovered_reflist(
 411         _refs_lists[index], _pending_list_addr);
 412       _refs_lists[index].set_head(NULL);
 413       _refs_lists[index].set_length(0);
 414     }
 415   }
 416 };
 417 
 418 // Enqueue references that are not made active again
 419 void ReferenceProcessor::enqueue_discovered_reflists(HeapWord* pending_list_addr,
 420   AbstractRefProcTaskExecutor* task_executor) {
 421   if (_processing_is_mt && task_executor != NULL) {
 422     // Parallel code
 423     RefProcEnqueueTask tsk(*this, _discovered_refs,
 424                            pending_list_addr, _max_num_q);
 425     task_executor->execute(tsk);
 426   } else {
 427     // Serial code: call the parent class's implementation
 428     for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 429       enqueue_discovered_reflist(_discovered_refs[i], pending_list_addr);
 430       _discovered_refs[i].set_head(NULL);
 431       _discovered_refs[i].set_length(0);
 432     }
 433   }
 434 }
 435 
 436 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
 437   _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref);
 438   oop discovered = java_lang_ref_Reference::discovered(_ref);
 439   assert(_discovered_addr && discovered->is_oop_or_null(),
 440          err_msg("Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered)));
 441   _next = discovered;
 442   _referent_addr = java_lang_ref_Reference::referent_addr(_ref);
 443   _referent = java_lang_ref_Reference::referent(_ref);
 444   assert(Universe::heap()->is_in_reserved_or_null(_referent),
 445          "Wrong oop found in java.lang.Reference object");
 446   assert(allow_null_referent ?
 447              _referent->is_oop_or_null()
 448            : _referent->is_oop(),
 449          err_msg("Expected an oop%s for referent field at " PTR_FORMAT,
 450                  (allow_null_referent ? " or NULL" : ""),
 451                  p2i(_referent)));
 452 }
 453 
 454 void DiscoveredListIterator::remove() {
 455   assert(_ref->is_oop(), "Dropping a bad reference");
 456   oop_store_raw(_discovered_addr, NULL);
 457 
 458   // First _prev_next ref actually points into DiscoveredList (gross).
 459   oop new_next;
 460   if (_next == _ref) {
 461     // At the end of the list, we should make _prev point to itself.
 462     // If _ref is the first ref, then _prev_next will be in the DiscoveredList,
 463     // and _prev will be NULL.
 464     new_next = _prev;
 465   } else {
 466     new_next = _next;
 467   }
 468   // Remove Reference object from discovered list. Note that G1 does not need a
 469   // pre-barrier here because we know the Reference has already been found/marked,
 470   // that's how it ended up in the discovered list in the first place.
 471   oop_store_raw(_prev_next, new_next);
 472   NOT_PRODUCT(_removed++);
 473   _refs_list.dec_length(1);
 474 }
 475 
 476 void DiscoveredListIterator::clear_referent() {
 477   oop_store_raw(_referent_addr, NULL);
 478 }
 479 
 480 // NOTE: process_phase*() are largely similar, and at a high level
 481 // merely iterate over the extant list applying a predicate to
 482 // each of its elements and possibly removing that element from the
 483 // list and applying some further closures to that element.
 484 // We should consider the possibility of replacing these
 485 // process_phase*() methods by abstracting them into
 486 // a single general iterator invocation that receives appropriate
 487 // closures that accomplish this work.
 488 
 489 // (SoftReferences only) Traverse the list and remove any SoftReferences whose
 490 // referents are not alive, but that should be kept alive for policy reasons.
 491 // Keep alive the transitive closure of all such referents.
 492 void
 493 ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
 494                                    ReferencePolicy*   policy,
 495                                    BoolObjectClosure* is_alive,
 496                                    OopClosure*        keep_alive,
 497                                    VoidClosure*       complete_gc) {
 498   assert(policy != NULL, "Must have a non-NULL policy");
 499   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 500   // Decide which softly reachable refs should be kept alive.
 501   while (iter.has_next()) {
 502     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
 503     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
 504     if (referent_is_dead &&
 505         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
 506       if (TraceReferenceGC) {
 507         gclog_or_tty->print_cr("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
 508                                p2i(iter.obj()), iter.obj()->klass()->internal_name());
 509       }
 510       // Remove Reference object from list
 511       iter.remove();
 512       // keep the referent around
 513       iter.make_referent_alive();
 514       iter.move_to_next();
 515     } else {
 516       iter.next();
 517     }
 518   }
 519   // Close the reachable set
 520   complete_gc->do_void();
 521   NOT_PRODUCT(
 522     if (PrintGCDetails && TraceReferenceGC) {
 523       gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT
 524         " discovered Refs by policy, from list " INTPTR_FORMAT,
 525         iter.removed(), iter.processed(), p2i(refs_list.head()));
 526     }
 527   )
 528 }
 529 
 530 // Traverse the list and remove any Refs that are not active, or
 531 // whose referents are either alive or NULL.
 532 void
 533 ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
 534                              BoolObjectClosure* is_alive,
 535                              OopClosure*        keep_alive) {
 536   assert(discovery_is_atomic(), "Error");
 537   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 538   while (iter.has_next()) {
 539     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 540     DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
 541     assert(next == NULL, "Should not discover inactive Reference");
 542     if (iter.is_referent_alive()) {
 543       if (TraceReferenceGC) {
 544         gclog_or_tty->print_cr("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
 545                                p2i(iter.obj()), iter.obj()->klass()->internal_name());
 546       }
 547       // The referent is reachable after all.
 548       // Remove Reference object from list.
 549       iter.remove();
 550       // Update the referent pointer as necessary: Note that this
 551       // should not entail any recursive marking because the
 552       // referent must already have been traversed.
 553       iter.make_referent_alive();
 554       iter.move_to_next();
 555     } else {
 556       iter.next();
 557     }
 558   }
 559   NOT_PRODUCT(
 560     if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
 561       gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
 562         " Refs in discovered list " INTPTR_FORMAT,
 563         iter.removed(), iter.processed(), p2i(refs_list.head()));
 564     }
 565   )
 566 }
 567 
 568 void
 569 ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList&    refs_list,
 570                                                   BoolObjectClosure* is_alive,
 571                                                   OopClosure*        keep_alive,
 572                                                   VoidClosure*       complete_gc) {
 573   assert(!discovery_is_atomic(), "Error");
 574   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 575   while (iter.has_next()) {
 576     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
 577     HeapWord* next_addr = java_lang_ref_Reference::next_addr(iter.obj());
 578     oop next = java_lang_ref_Reference::next(iter.obj());
 579     if ((iter.referent() == NULL || iter.is_referent_alive() ||
 580          next != NULL)) {
 581       assert(next->is_oop_or_null(), err_msg("Expected an oop or NULL for next field at " PTR_FORMAT, p2i(next)));
 582       // Remove Reference object from list
 583       iter.remove();
 584       // Trace the cohorts
 585       iter.make_referent_alive();
 586       if (UseCompressedOops) {
 587         keep_alive->do_oop((narrowOop*)next_addr);
 588       } else {
 589         keep_alive->do_oop((oop*)next_addr);
 590       }
 591       iter.move_to_next();
 592     } else {
 593       iter.next();
 594     }
 595   }
 596   // Now close the newly reachable set
 597   complete_gc->do_void();
 598   NOT_PRODUCT(
 599     if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
 600       gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
 601         " Refs in discovered list " INTPTR_FORMAT,
 602         iter.removed(), iter.processed(), p2i(refs_list.head()));
 603     }
 604   )
 605 }
 606 
 607 // Traverse the list and process the referents, by either
 608 // clearing them or keeping them (and their reachable
 609 // closure) alive.
 610 void
 611 ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
 612                                    bool               clear_referent,
 613                                    BoolObjectClosure* is_alive,
 614                                    OopClosure*        keep_alive,
 615                                    VoidClosure*       complete_gc) {
 616   ResourceMark rm;
 617   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 618   while (iter.has_next()) {
 619     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 620     if (clear_referent) {
 621       // NULL out referent pointer
 622       iter.clear_referent();
 623     } else {
 624       // keep the referent around
 625       iter.make_referent_alive();
 626     }
 627     if (TraceReferenceGC) {
 628       gclog_or_tty->print_cr("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
 629                              clear_referent ? "cleared " : "",
 630                              p2i(iter.obj()), iter.obj()->klass()->internal_name());
 631     }
 632     assert(iter.obj()->is_oop(UseConcMarkSweepGC), "Adding a bad reference");
 633     iter.next();
 634   }
 635   // Close the reachable set
 636   complete_gc->do_void();
 637 }
 638 
 639 void
 640 ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) {
 641   oop obj = NULL;
 642   oop next = refs_list.head();
 643   while (next != obj) {
 644     obj = next;
 645     next = java_lang_ref_Reference::discovered(obj);
 646     java_lang_ref_Reference::set_discovered_raw(obj, NULL);
 647   }
 648   refs_list.set_head(NULL);
 649   refs_list.set_length(0);
 650 }
 651 
 652 void ReferenceProcessor::abandon_partial_discovery() {
 653   // loop over the lists
 654   for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 655     if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
 656       gclog_or_tty->print_cr("\nAbandoning %s discovered list", list_name(i));
 657     }
 658     clear_discovered_references(_discovered_refs[i]);
 659   }
 660 }
 661 
 662 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
 663 public:
 664   RefProcPhase1Task(ReferenceProcessor& ref_processor,
 665                     DiscoveredList      refs_lists[],
 666                     ReferencePolicy*    policy,
 667                     bool                marks_oops_alive)
 668     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 669       _policy(policy)
 670   { }
 671   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 672                     OopClosure& keep_alive,
 673                     VoidClosure& complete_gc)
 674   {
 675     Thread* thr = Thread::current();
 676     int refs_list_index = ((WorkerThread*)thr)->id();
 677     _ref_processor.process_phase1(_refs_lists[refs_list_index], _policy,
 678                                   &is_alive, &keep_alive, &complete_gc);
 679   }
 680 private:
 681   ReferencePolicy* _policy;
 682 };
 683 
 684 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
 685 public:
 686   RefProcPhase2Task(ReferenceProcessor& ref_processor,
 687                     DiscoveredList      refs_lists[],
 688                     bool                marks_oops_alive)
 689     : ProcessTask(ref_processor, refs_lists, marks_oops_alive)
 690   { }
 691   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 692                     OopClosure& keep_alive,
 693                     VoidClosure& complete_gc)
 694   {
 695     _ref_processor.process_phase2(_refs_lists[i],
 696                                   &is_alive, &keep_alive, &complete_gc);
 697   }
 698 };
 699 
 700 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
 701 public:
 702   RefProcPhase3Task(ReferenceProcessor& ref_processor,
 703                     DiscoveredList      refs_lists[],
 704                     bool                clear_referent,
 705                     bool                marks_oops_alive)
 706     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 707       _clear_referent(clear_referent)
 708   { }
 709   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 710                     OopClosure& keep_alive,
 711                     VoidClosure& complete_gc)
 712   {
 713     // Don't use "refs_list_index" calculated in this way because
 714     // balance_queues() has moved the Ref's into the first n queues.
 715     // Thread* thr = Thread::current();
 716     // int refs_list_index = ((WorkerThread*)thr)->id();
 717     // _ref_processor.process_phase3(_refs_lists[refs_list_index], _clear_referent,
 718     _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
 719                                   &is_alive, &keep_alive, &complete_gc);
 720   }
 721 private:
 722   bool _clear_referent;
 723 };
 724 
 725 // Balances reference queues.
 726 // Move entries from all queues[0, 1, ..., _max_num_q-1] to
 727 // queues[0, 1, ..., _num_q-1] because only the first _num_q
 728 // corresponding to the active workers will be processed.
 729 void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
 730 {
 731   // calculate total length
 732   size_t total_refs = 0;
 733   if (TraceReferenceGC && PrintGCDetails) {
 734     gclog_or_tty->print_cr("\nBalance ref_lists ");
 735   }
 736 
 737   for (uint i = 0; i < _max_num_q; ++i) {
 738     total_refs += ref_lists[i].length();
 739     if (TraceReferenceGC && PrintGCDetails) {
 740       gclog_or_tty->print(SIZE_FORMAT " ", ref_lists[i].length());
 741     }
 742   }
 743   if (TraceReferenceGC && PrintGCDetails) {
 744     gclog_or_tty->print_cr(" = " SIZE_FORMAT, total_refs);
 745   }
 746   size_t avg_refs = total_refs / _num_q + 1;
 747   uint to_idx = 0;
 748   for (uint from_idx = 0; from_idx < _max_num_q; from_idx++) {
 749     bool move_all = false;
 750     if (from_idx >= _num_q) {
 751       move_all = ref_lists[from_idx].length() > 0;
 752     }
 753     while ((ref_lists[from_idx].length() > avg_refs) ||
 754            move_all) {
 755       assert(to_idx < _num_q, "Sanity Check!");
 756       if (ref_lists[to_idx].length() < avg_refs) {
 757         // move superfluous refs
 758         size_t refs_to_move;
 759         // Move all the Ref's if the from queue will not be processed.
 760         if (move_all) {
 761           refs_to_move = MIN2(ref_lists[from_idx].length(),
 762                               avg_refs - ref_lists[to_idx].length());
 763         } else {
 764           refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
 765                               avg_refs - ref_lists[to_idx].length());
 766         }
 767 
 768         assert(refs_to_move > 0, "otherwise the code below will fail");
 769 
 770         oop move_head = ref_lists[from_idx].head();
 771         oop move_tail = move_head;
 772         oop new_head  = move_head;
 773         // find an element to split the list on
 774         for (size_t j = 0; j < refs_to_move; ++j) {
 775           move_tail = new_head;
 776           new_head = java_lang_ref_Reference::discovered(new_head);
 777         }
 778 
 779         // Add the chain to the to list.
 780         if (ref_lists[to_idx].head() == NULL) {
 781           // to list is empty. Make a loop at the end.
 782           java_lang_ref_Reference::set_discovered_raw(move_tail, move_tail);
 783         } else {
 784           java_lang_ref_Reference::set_discovered_raw(move_tail, ref_lists[to_idx].head());
 785         }
 786         ref_lists[to_idx].set_head(move_head);
 787         ref_lists[to_idx].inc_length(refs_to_move);
 788 
 789         // Remove the chain from the from list.
 790         if (move_tail == new_head) {
 791           // We found the end of the from list.
 792           ref_lists[from_idx].set_head(NULL);
 793         } else {
 794           ref_lists[from_idx].set_head(new_head);
 795         }
 796         ref_lists[from_idx].dec_length(refs_to_move);
 797         if (ref_lists[from_idx].length() == 0) {
 798           break;
 799         }
 800       } else {
 801         to_idx = (to_idx + 1) % _num_q;
 802       }
 803     }
 804   }
 805 #ifdef ASSERT
 806   size_t balanced_total_refs = 0;
 807   for (uint i = 0; i < _max_num_q; ++i) {
 808     balanced_total_refs += ref_lists[i].length();
 809     if (TraceReferenceGC && PrintGCDetails) {
 810       gclog_or_tty->print(SIZE_FORMAT " ", ref_lists[i].length());
 811     }
 812   }
 813   if (TraceReferenceGC && PrintGCDetails) {
 814     gclog_or_tty->print_cr(" = " SIZE_FORMAT, balanced_total_refs);
 815     gclog_or_tty->flush();
 816   }
 817   assert(total_refs == balanced_total_refs, "Balancing was incomplete");
 818 #endif
 819 }
 820 
 821 void ReferenceProcessor::balance_all_queues() {
 822   balance_queues(_discoveredSoftRefs);
 823   balance_queues(_discoveredWeakRefs);
 824   balance_queues(_discoveredFinalRefs);
 825   balance_queues(_discoveredPhantomRefs);
 826   balance_queues(_discoveredCleanerRefs);
 827 }
 828 
 829 size_t
 830 ReferenceProcessor::process_discovered_reflist(
 831   DiscoveredList               refs_lists[],
 832   ReferencePolicy*             policy,
 833   bool                         clear_referent,
 834   BoolObjectClosure*           is_alive,
 835   OopClosure*                  keep_alive,
 836   VoidClosure*                 complete_gc,
 837   AbstractRefProcTaskExecutor* task_executor)
 838 {
 839   bool mt_processing = task_executor != NULL && _processing_is_mt;
 840   // If discovery used MT and a dynamic number of GC threads, then
 841   // the queues must be balanced for correctness if fewer than the
 842   // maximum number of queues were used.  The number of queue used
 843   // during discovery may be different than the number to be used
 844   // for processing so don't depend of _num_q < _max_num_q as part
 845   // of the test.
 846   bool must_balance = _discovery_is_mt;
 847 
 848   if ((mt_processing && ParallelRefProcBalancingEnabled) ||
 849       must_balance) {
 850     balance_queues(refs_lists);
 851   }
 852 
 853   size_t total_list_count = total_count(refs_lists);
 854 
 855   if (PrintReferenceGC && PrintGCDetails) {
 856     gclog_or_tty->print(", " SIZE_FORMAT " refs", total_list_count);
 857   }
 858 
 859   // Phase 1 (soft refs only):
 860   // . Traverse the list and remove any SoftReferences whose
 861   //   referents are not alive, but that should be kept alive for
 862   //   policy reasons. Keep alive the transitive closure of all
 863   //   such referents.
 864   if (policy != NULL) {
 865     if (mt_processing) {
 866       RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/);
 867       task_executor->execute(phase1);
 868     } else {
 869       for (uint i = 0; i < _max_num_q; i++) {
 870         process_phase1(refs_lists[i], policy,
 871                        is_alive, keep_alive, complete_gc);
 872       }
 873     }
 874   } else { // policy == NULL
 875     assert(refs_lists != _discoveredSoftRefs,
 876            "Policy must be specified for soft references.");
 877   }
 878 
 879   // Phase 2:
 880   // . Traverse the list and remove any refs whose referents are alive.
 881   if (mt_processing) {
 882     RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/);
 883     task_executor->execute(phase2);
 884   } else {
 885     for (uint i = 0; i < _max_num_q; i++) {
 886       process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
 887     }
 888   }
 889 
 890   // Phase 3:
 891   // . Traverse the list and process referents as appropriate.
 892   if (mt_processing) {
 893     RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/);
 894     task_executor->execute(phase3);
 895   } else {
 896     for (uint i = 0; i < _max_num_q; i++) {
 897       process_phase3(refs_lists[i], clear_referent,
 898                      is_alive, keep_alive, complete_gc);
 899     }
 900   }
 901 
 902   return total_list_count;
 903 }
 904 
 905 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
 906   uint id = 0;
 907   // Determine the queue index to use for this object.
 908   if (_discovery_is_mt) {
 909     // During a multi-threaded discovery phase,
 910     // each thread saves to its "own" list.
 911     Thread* thr = Thread::current();
 912     id = thr->as_Worker_thread()->id();
 913   } else {
 914     // single-threaded discovery, we save in round-robin
 915     // fashion to each of the lists.
 916     if (_processing_is_mt) {
 917       id = next_id();
 918     }
 919   }
 920   assert(id < _max_num_q, "Id is out-of-bounds (call Freud?)");
 921 
 922   // Get the discovered queue to which we will add
 923   DiscoveredList* list = NULL;
 924   switch (rt) {
 925     case REF_OTHER:
 926       // Unknown reference type, no special treatment
 927       break;
 928     case REF_SOFT:
 929       list = &_discoveredSoftRefs[id];
 930       break;
 931     case REF_WEAK:
 932       list = &_discoveredWeakRefs[id];
 933       break;
 934     case REF_FINAL:
 935       list = &_discoveredFinalRefs[id];
 936       break;
 937     case REF_PHANTOM:
 938       list = &_discoveredPhantomRefs[id];
 939       break;
 940     case REF_CLEANER:
 941       list = &_discoveredCleanerRefs[id];
 942       break;
 943     case REF_NONE:
 944       // we should not reach here if we are an InstanceRefKlass
 945     default:
 946       ShouldNotReachHere();
 947   }
 948   if (TraceReferenceGC && PrintGCDetails) {
 949     gclog_or_tty->print_cr("Thread %d gets list " INTPTR_FORMAT, id, p2i(list));
 950   }
 951   return list;
 952 }
 953 
 954 inline void
 955 ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
 956                                               oop             obj,
 957                                               HeapWord*       discovered_addr) {
 958   assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
 959   // First we must make sure this object is only enqueued once. CAS in a non null
 960   // discovered_addr.
 961   oop current_head = refs_list.head();
 962   // The last ref must have its discovered field pointing to itself.
 963   oop next_discovered = (current_head != NULL) ? current_head : obj;
 964 
 965   oop retest = oopDesc::atomic_compare_exchange_oop(next_discovered, discovered_addr,
 966                                                     NULL);
 967   if (retest == NULL) {
 968     // This thread just won the right to enqueue the object.
 969     // We have separate lists for enqueueing, so no synchronization
 970     // is necessary.
 971     refs_list.set_head(obj);
 972     refs_list.inc_length(1);
 973 
 974     if (TraceReferenceGC) {
 975       gclog_or_tty->print_cr("Discovered reference (mt) (" INTPTR_FORMAT ": %s)",
 976                              p2i(obj), obj->klass()->internal_name());
 977     }
 978   } else {
 979     // If retest was non NULL, another thread beat us to it:
 980     // The reference has already been discovered...
 981     if (TraceReferenceGC) {
 982       gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
 983                              p2i(obj), obj->klass()->internal_name());
 984     }
 985   }
 986 }
 987 
 988 #ifndef PRODUCT
 989 // Non-atomic (i.e. concurrent) discovery might allow us
 990 // to observe j.l.References with NULL referents, being those
 991 // cleared concurrently by mutators during (or after) discovery.
 992 void ReferenceProcessor::verify_referent(oop obj) {
 993   bool da = discovery_is_atomic();
 994   oop referent = java_lang_ref_Reference::referent(obj);
 995   assert(da ? referent->is_oop() : referent->is_oop_or_null(),
 996          err_msg("Bad referent " INTPTR_FORMAT " found in Reference "
 997                  INTPTR_FORMAT " during %satomic discovery ",
 998                  p2i(referent), p2i(obj), da ? "" : "non-"));
 999 }
1000 #endif
1001 
1002 // We mention two of several possible choices here:
1003 // #0: if the reference object is not in the "originating generation"
1004 //     (or part of the heap being collected, indicated by our "span"
1005 //     we don't treat it specially (i.e. we scan it as we would
1006 //     a normal oop, treating its references as strong references).
1007 //     This means that references can't be discovered unless their
1008 //     referent is also in the same span. This is the simplest,
1009 //     most "local" and most conservative approach, albeit one
1010 //     that may cause weak references to be enqueued least promptly.
1011 //     We call this choice the "ReferenceBasedDiscovery" policy.
1012 // #1: the reference object may be in any generation (span), but if
1013 //     the referent is in the generation (span) being currently collected
1014 //     then we can discover the reference object, provided
1015 //     the object has not already been discovered by
1016 //     a different concurrently running collector (as may be the
1017 //     case, for instance, if the reference object is in CMS and
1018 //     the referent in DefNewGeneration), and provided the processing
1019 //     of this reference object by the current collector will
1020 //     appear atomic to every other collector in the system.
1021 //     (Thus, for instance, a concurrent collector may not
1022 //     discover references in other generations even if the
1023 //     referent is in its own generation). This policy may,
1024 //     in certain cases, enqueue references somewhat sooner than
1025 //     might Policy #0 above, but at marginally increased cost
1026 //     and complexity in processing these references.
1027 //     We call this choice the "RefeferentBasedDiscovery" policy.
1028 bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) {
1029   // Make sure we are discovering refs (rather than processing discovered refs).
1030   if (!_discovering_refs || !RegisterReferences) {
1031     return false;
1032   }
1033   // We only discover active references.
1034   oop next = java_lang_ref_Reference::next(obj);
1035   if (next != NULL) {   // Ref is no longer active
1036     return false;
1037   }
1038 
1039   HeapWord* obj_addr = (HeapWord*)obj;
1040   if (RefDiscoveryPolicy == ReferenceBasedDiscovery &&
1041       !_span.contains(obj_addr)) {
1042     // Reference is not in the originating generation;
1043     // don't treat it specially (i.e. we want to scan it as a normal
1044     // object with strong references).
1045     return false;
1046   }
1047 
1048   // We only discover references whose referents are not (yet)
1049   // known to be strongly reachable.
1050   if (is_alive_non_header() != NULL) {
1051     verify_referent(obj);
1052     if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) {
1053       return false;  // referent is reachable
1054     }
1055   }
1056   if (rt == REF_SOFT) {
1057     // For soft refs we can decide now if these are not
1058     // current candidates for clearing, in which case we
1059     // can mark through them now, rather than delaying that
1060     // to the reference-processing phase. Since all current
1061     // time-stamp policies advance the soft-ref clock only
1062     // at a major collection cycle, this is always currently
1063     // accurate.
1064     if (!_current_soft_ref_policy->should_clear_reference(obj, _soft_ref_timestamp_clock)) {
1065       return false;
1066     }
1067   }
1068 
1069   ResourceMark rm;      // Needed for tracing.
1070 
1071   HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr(obj);
1072   const oop  discovered = java_lang_ref_Reference::discovered(obj);
1073   assert(discovered->is_oop_or_null(), err_msg("Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered)));
1074   if (discovered != NULL) {
1075     // The reference has already been discovered...
1076     if (TraceReferenceGC) {
1077       gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
1078                              p2i(obj), obj->klass()->internal_name());
1079     }
1080     if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
1081       // assumes that an object is not processed twice;
1082       // if it's been already discovered it must be on another
1083       // generation's discovered list; so we won't discover it.
1084       return false;
1085     } else {
1086       assert(RefDiscoveryPolicy == ReferenceBasedDiscovery,
1087              "Unrecognized policy");
1088       // Check assumption that an object is not potentially
1089       // discovered twice except by concurrent collectors that potentially
1090       // trace the same Reference object twice.
1091       assert(UseConcMarkSweepGC || UseG1GC,
1092              "Only possible with a concurrent marking collector");
1093       return true;
1094     }
1095   }
1096 
1097   if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
1098     verify_referent(obj);
1099     // Discover if and only if EITHER:
1100     // .. reference is in our span, OR
1101     // .. we are an atomic collector and referent is in our span
1102     if (_span.contains(obj_addr) ||
1103         (discovery_is_atomic() &&
1104          _span.contains(java_lang_ref_Reference::referent(obj)))) {
1105       // should_enqueue = true;
1106     } else {
1107       return false;
1108     }
1109   } else {
1110     assert(RefDiscoveryPolicy == ReferenceBasedDiscovery &&
1111            _span.contains(obj_addr), "code inconsistency");
1112   }
1113 
1114   // Get the right type of discovered queue head.
1115   DiscoveredList* list = get_discovered_list(rt);
1116   if (list == NULL) {
1117     return false;   // nothing special needs to be done
1118   }
1119 
1120   if (_discovery_is_mt) {
1121     add_to_discovered_list_mt(*list, obj, discovered_addr);
1122   } else {
1123     // We do a raw store here: the field will be visited later when processing
1124     // the discovered references.
1125     oop current_head = list->head();
1126     // The last ref must have its discovered field pointing to itself.
1127     oop next_discovered = (current_head != NULL) ? current_head : obj;
1128 
1129     assert(discovered == NULL, "control point invariant");
1130     oop_store_raw(discovered_addr, next_discovered);
1131     list->set_head(obj);
1132     list->inc_length(1);
1133 
1134     if (TraceReferenceGC) {
1135       gclog_or_tty->print_cr("Discovered reference (" INTPTR_FORMAT ": %s)",
1136                                 p2i(obj), obj->klass()->internal_name());
1137     }
1138   }
1139   assert(obj->is_oop(), "Discovered a bad reference");
1140   verify_referent(obj);
1141   return true;
1142 }
1143 
1144 // Preclean the discovered references by removing those
1145 // whose referents are alive, and by marking from those that
1146 // are not active. These lists can be handled here
1147 // in any order and, indeed, concurrently.
1148 void ReferenceProcessor::preclean_discovered_references(
1149   BoolObjectClosure* is_alive,
1150   OopClosure* keep_alive,
1151   VoidClosure* complete_gc,
1152   YieldClosure* yield,
1153   GCTimer* gc_timer,
1154   GCId     gc_id) {
1155 
1156   // Soft references
1157   {
1158     GCTraceTime tt("Preclean SoftReferences", PrintGCDetails && PrintReferenceGC,
1159               false, gc_timer, gc_id);
1160     for (uint i = 0; i < _max_num_q; i++) {
1161       if (yield->should_return()) {
1162         return;
1163       }
1164       preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive,
1165                                   keep_alive, complete_gc, yield);
1166     }
1167   }
1168 
1169   // Weak references
1170   {
1171     GCTraceTime tt("Preclean WeakReferences", PrintGCDetails && PrintReferenceGC,
1172               false, gc_timer, gc_id);
1173     for (uint i = 0; i < _max_num_q; i++) {
1174       if (yield->should_return()) {
1175         return;
1176       }
1177       preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive,
1178                                   keep_alive, complete_gc, yield);
1179     }
1180   }
1181 
1182   // Final references
1183   {
1184     GCTraceTime tt("Preclean FinalReferences", PrintGCDetails && PrintReferenceGC,
1185               false, gc_timer, gc_id);
1186     for (uint i = 0; i < _max_num_q; i++) {
1187       if (yield->should_return()) {
1188         return;
1189       }
1190       preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive,
1191                                   keep_alive, complete_gc, yield);
1192     }
1193   }
1194 
1195   // Phantom references
1196   {
1197     GCTraceTime tt("Preclean PhantomReferences", PrintGCDetails && PrintReferenceGC,
1198               false, gc_timer, gc_id);
1199     for (uint i = 0; i < _max_num_q; i++) {
1200       if (yield->should_return()) {
1201         return;
1202       }
1203       preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive,
1204                                   keep_alive, complete_gc, yield);
1205     }
1206 
1207     // Cleaner references.  Included in timing for phantom references.  We
1208     // expect Cleaner references to be temporary, and don't want to deal with
1209     // possible incompatibilities arising from making it more visible.
1210     for (uint i = 0; i < _max_num_q; i++) {
1211       if (yield->should_return()) {
1212         return;
1213       }
1214       preclean_discovered_reflist(_discoveredCleanerRefs[i], is_alive,
1215                                   keep_alive, complete_gc, yield);
1216     }
1217   }
1218 }
1219 
1220 // Walk the given discovered ref list, and remove all reference objects
1221 // whose referents are still alive, whose referents are NULL or which
1222 // are not active (have a non-NULL next field). NOTE: When we are
1223 // thus precleaning the ref lists (which happens single-threaded today),
1224 // we do not disable refs discovery to honor the correct semantics of
1225 // java.lang.Reference. As a result, we need to be careful below
1226 // that ref removal steps interleave safely with ref discovery steps
1227 // (in this thread).
1228 void
1229 ReferenceProcessor::preclean_discovered_reflist(DiscoveredList&    refs_list,
1230                                                 BoolObjectClosure* is_alive,
1231                                                 OopClosure*        keep_alive,
1232                                                 VoidClosure*       complete_gc,
1233                                                 YieldClosure*      yield) {
1234   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
1235   while (iter.has_next()) {
1236     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
1237     oop obj = iter.obj();
1238     oop next = java_lang_ref_Reference::next(obj);
1239     if (iter.referent() == NULL || iter.is_referent_alive() ||
1240         next != NULL) {
1241       // The referent has been cleared, or is alive, or the Reference is not
1242       // active; we need to trace and mark its cohort.
1243       if (TraceReferenceGC) {
1244         gclog_or_tty->print_cr("Precleaning Reference (" INTPTR_FORMAT ": %s)",
1245                                p2i(iter.obj()), iter.obj()->klass()->internal_name());
1246       }
1247       // Remove Reference object from list
1248       iter.remove();
1249       // Keep alive its cohort.
1250       iter.make_referent_alive();
1251       if (UseCompressedOops) {
1252         narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr(obj);
1253         keep_alive->do_oop(next_addr);
1254       } else {
1255         oop* next_addr = (oop*)java_lang_ref_Reference::next_addr(obj);
1256         keep_alive->do_oop(next_addr);
1257       }
1258       iter.move_to_next();
1259     } else {
1260       iter.next();
1261     }
1262   }
1263   // Close the reachable set
1264   complete_gc->do_void();
1265 
1266   NOT_PRODUCT(
1267     if (PrintGCDetails && PrintReferenceGC && (iter.processed() > 0)) {
1268       gclog_or_tty->print_cr(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT
1269         " Refs in discovered list " INTPTR_FORMAT,
1270         iter.removed(), iter.processed(), p2i(refs_list.head()));
1271     }
1272   )
1273 }
1274 
1275 const char* ReferenceProcessor::list_name(uint i) {
1276    assert(i <= _max_num_q * number_of_subclasses_of_ref(),
1277           "Out of bounds index");
1278 
1279    int j = i / _max_num_q;
1280    switch (j) {
1281      case 0: return "SoftRef";
1282      case 1: return "WeakRef";
1283      case 2: return "FinalRef";
1284      case 3: return "PhantomRef";
1285      case 4: return "CleanerRef";
1286    }
1287    ShouldNotReachHere();
1288    return NULL;
1289 }
1290