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